Merge "Prevent refocus after entering touch mode" into klp-dev
diff --git a/Android.mk b/Android.mk
index 22ee3a6..656e40c 100644
--- a/Android.mk
+++ b/Android.mk
@@ -355,6 +355,7 @@
 	frameworks/base/core/java/android/content/SyncStats.aidl \
 	frameworks/base/core/java/android/content/res/Configuration.aidl \
 	frameworks/base/core/java/android/database/CursorWindow.aidl \
+	frameworks/base/core/java/android/hardware/location/GeofenceHardwareRequestParcelable.aidl \
 	frameworks/base/core/java/android/net/Uri.aidl \
 	frameworks/base/core/java/android/nfc/NdefMessage.aidl \
 	frameworks/base/core/java/android/nfc/NdefRecord.aidl \
@@ -391,6 +392,8 @@
 	frameworks/base/telephony/java/android/telephony/ServiceState.aidl \
 	frameworks/base/telephony/java/com/android/internal/telephony/IPhoneSubInfo.aidl \
 	frameworks/base/telephony/java/com/android/internal/telephony/ITelephony.aidl \
+	frameworks/base/wifi/java/android/net/wifi/BatchedScanSettings.aidl \
+	frameworks/base/wifi/java/android/net/wifi/BatchedScanResult.aidl \
 
 gen := $(TARGET_OUT_COMMON_INTERMEDIATES)/framework.aidl
 $(gen): PRIVATE_SRC_FILES := $(aidl_files)
diff --git a/api/current.txt b/api/current.txt
index 002b8d7..3943695 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -10757,7 +10757,119 @@
     method public void readFromParcel(android.os.Parcel);
     method public void set(android.hardware.camera2.CameraMetadata.Key<T>, T);
     method public void writeToParcel(android.os.Parcel, int);
+    field public static final int COLOR_CORRECTION_MODE_FAST = 1; // 0x1
+    field public static final int COLOR_CORRECTION_MODE_HIGH_QUALITY = 2; // 0x2
+    field public static final int COLOR_CORRECTION_MODE_TRANSFORM_MATRIX = 0; // 0x0
+    field public static final int CONTROL_AE_ANTIBANDING_MODE_50HZ = 1; // 0x1
+    field public static final int CONTROL_AE_ANTIBANDING_MODE_60HZ = 2; // 0x2
+    field public static final int CONTROL_AE_ANTIBANDING_MODE_AUTO = 3; // 0x3
+    field public static final int CONTROL_AE_ANTIBANDING_MODE_OFF = 0; // 0x0
+    field public static final int CONTROL_AE_MODE_OFF = 0; // 0x0
+    field public static final int CONTROL_AE_MODE_ON = 1; // 0x1
+    field public static final int CONTROL_AE_MODE_ON_ALWAYS_FLASH = 3; // 0x3
+    field public static final int CONTROL_AE_MODE_ON_AUTO_FLASH = 2; // 0x2
+    field public static final int CONTROL_AE_MODE_ON_AUTO_FLASH_REDEYE = 4; // 0x4
+    field public static final int CONTROL_AE_PRECAPTURE_TRIGGER_IDLE = 0; // 0x0
+    field public static final int CONTROL_AE_PRECAPTURE_TRIGGER_START = 1; // 0x1
+    field public static final int CONTROL_AE_STATE_CONVERGED = 2; // 0x2
+    field public static final int CONTROL_AE_STATE_FLASH_REQUIRED = 4; // 0x4
+    field public static final int CONTROL_AE_STATE_INACTIVE = 0; // 0x0
+    field public static final int CONTROL_AE_STATE_LOCKED = 3; // 0x3
+    field public static final int CONTROL_AE_STATE_PRECAPTURE = 5; // 0x5
+    field public static final int CONTROL_AE_STATE_SEARCHING = 1; // 0x1
+    field public static final int CONTROL_AF_MODE_AUTO = 1; // 0x1
+    field public static final int CONTROL_AF_MODE_CONTINUOUS_PICTURE = 4; // 0x4
+    field public static final int CONTROL_AF_MODE_CONTINUOUS_VIDEO = 3; // 0x3
+    field public static final int CONTROL_AF_MODE_EDOF = 5; // 0x5
+    field public static final int CONTROL_AF_MODE_MACRO = 2; // 0x2
+    field public static final int CONTROL_AF_MODE_OFF = 0; // 0x0
+    field public static final int CONTROL_AF_STATE_ACTIVE_SCAN = 3; // 0x3
+    field public static final int CONTROL_AF_STATE_FOCUSED_LOCKED = 4; // 0x4
+    field public static final int CONTROL_AF_STATE_INACTIVE = 0; // 0x0
+    field public static final int CONTROL_AF_STATE_NOT_FOCUSED_LOCKED = 5; // 0x5
+    field public static final int CONTROL_AF_STATE_PASSIVE_FOCUSED = 2; // 0x2
+    field public static final int CONTROL_AF_STATE_PASSIVE_SCAN = 1; // 0x1
+    field public static final int CONTROL_AF_TRIGGER_CANCEL = 2; // 0x2
+    field public static final int CONTROL_AF_TRIGGER_IDLE = 0; // 0x0
+    field public static final int CONTROL_AF_TRIGGER_START = 1; // 0x1
+    field public static final int CONTROL_AWB_MODE_AUTO = 1; // 0x1
+    field public static final int CONTROL_AWB_MODE_CLOUDY_DAYLIGHT = 6; // 0x6
+    field public static final int CONTROL_AWB_MODE_DAYLIGHT = 5; // 0x5
+    field public static final int CONTROL_AWB_MODE_FLUORESCENT = 3; // 0x3
+    field public static final int CONTROL_AWB_MODE_INCANDESCENT = 2; // 0x2
+    field public static final int CONTROL_AWB_MODE_OFF = 0; // 0x0
+    field public static final int CONTROL_AWB_MODE_SHADE = 8; // 0x8
+    field public static final int CONTROL_AWB_MODE_TWILIGHT = 7; // 0x7
+    field public static final int CONTROL_AWB_MODE_WARM_FLUORESCENT = 4; // 0x4
+    field public static final int CONTROL_AWB_STATE_CONVERGED = 2; // 0x2
+    field public static final int CONTROL_AWB_STATE_INACTIVE = 0; // 0x0
+    field public static final int CONTROL_AWB_STATE_LOCKED = 3; // 0x3
+    field public static final int CONTROL_AWB_STATE_SEARCHING = 1; // 0x1
+    field public static final int CONTROL_CAPTURE_INTENT_CUSTOM = 0; // 0x0
+    field public static final int CONTROL_CAPTURE_INTENT_PREVIEW = 1; // 0x1
+    field public static final int CONTROL_CAPTURE_INTENT_STILL_CAPTURE = 2; // 0x2
+    field public static final int CONTROL_CAPTURE_INTENT_VIDEO_RECORD = 3; // 0x3
+    field public static final int CONTROL_CAPTURE_INTENT_VIDEO_SNAPSHOT = 4; // 0x4
+    field public static final int CONTROL_CAPTURE_INTENT_ZERO_SHUTTER_LAG = 5; // 0x5
+    field public static final int CONTROL_EFFECT_MODE_AQUA = 8; // 0x8
+    field public static final int CONTROL_EFFECT_MODE_BLACKBOARD = 7; // 0x7
+    field public static final int CONTROL_EFFECT_MODE_MONO = 1; // 0x1
+    field public static final int CONTROL_EFFECT_MODE_NEGATIVE = 2; // 0x2
+    field public static final int CONTROL_EFFECT_MODE_OFF = 0; // 0x0
+    field public static final int CONTROL_EFFECT_MODE_POSTERIZE = 5; // 0x5
+    field public static final int CONTROL_EFFECT_MODE_SEPIA = 4; // 0x4
+    field public static final int CONTROL_EFFECT_MODE_SOLARIZE = 3; // 0x3
+    field public static final int CONTROL_EFFECT_MODE_WHITEBOARD = 6; // 0x6
+    field public static final int CONTROL_MODE_AUTO = 1; // 0x1
+    field public static final int CONTROL_MODE_OFF = 0; // 0x0
+    field public static final int CONTROL_MODE_USE_SCENE_MODE = 2; // 0x2
+    field public static final int CONTROL_SCENE_MODE_ACTION = 2; // 0x2
+    field public static final int CONTROL_SCENE_MODE_BARCODE = 16; // 0x10
+    field public static final int CONTROL_SCENE_MODE_BEACH = 8; // 0x8
+    field public static final int CONTROL_SCENE_MODE_CANDLELIGHT = 15; // 0xf
+    field public static final int CONTROL_SCENE_MODE_FACE_PRIORITY = 1; // 0x1
+    field public static final int CONTROL_SCENE_MODE_FIREWORKS = 12; // 0xc
+    field public static final int CONTROL_SCENE_MODE_LANDSCAPE = 4; // 0x4
+    field public static final int CONTROL_SCENE_MODE_NIGHT = 5; // 0x5
+    field public static final int CONTROL_SCENE_MODE_NIGHT_PORTRAIT = 6; // 0x6
+    field public static final int CONTROL_SCENE_MODE_PARTY = 14; // 0xe
+    field public static final int CONTROL_SCENE_MODE_PORTRAIT = 3; // 0x3
+    field public static final int CONTROL_SCENE_MODE_SNOW = 9; // 0x9
+    field public static final int CONTROL_SCENE_MODE_SPORTS = 13; // 0xd
+    field public static final int CONTROL_SCENE_MODE_STEADYPHOTO = 11; // 0xb
+    field public static final int CONTROL_SCENE_MODE_SUNSET = 10; // 0xa
+    field public static final int CONTROL_SCENE_MODE_THEATRE = 7; // 0x7
+    field public static final int CONTROL_SCENE_MODE_UNSUPPORTED = 0; // 0x0
     field public static final android.os.Parcelable.Creator CREATOR;
+    field public static final int EDGE_MODE_FAST = 1; // 0x1
+    field public static final int EDGE_MODE_HIGH_QUALITY = 2; // 0x2
+    field public static final int EDGE_MODE_OFF = 0; // 0x0
+    field public static final int FLASH_MODE_OFF = 0; // 0x0
+    field public static final int FLASH_MODE_SINGLE = 1; // 0x1
+    field public static final int FLASH_MODE_TORCH = 2; // 0x2
+    field public static final int FLASH_STATE_CHARGING = 1; // 0x1
+    field public static final int FLASH_STATE_FIRED = 3; // 0x3
+    field public static final int FLASH_STATE_READY = 2; // 0x2
+    field public static final int FLASH_STATE_UNAVAILABLE = 0; // 0x0
+    field public static final int INFO_SUPPORTED_HARDWARE_LEVEL_FULL = 1; // 0x1
+    field public static final int INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED = 0; // 0x0
+    field public static final int LENS_FACING_BACK = 1; // 0x1
+    field public static final int LENS_FACING_FRONT = 0; // 0x0
+    field public static final int LENS_OPTICAL_STABILIZATION_MODE_OFF = 0; // 0x0
+    field public static final int LENS_OPTICAL_STABILIZATION_MODE_ON = 1; // 0x1
+    field public static final int LENS_STATE_STATIONARY = 0; // 0x0
+    field public static final int NOISE_REDUCTION_MODE_FAST = 1; // 0x1
+    field public static final int NOISE_REDUCTION_MODE_HIGH_QUALITY = 2; // 0x2
+    field public static final int NOISE_REDUCTION_MODE_OFF = 0; // 0x0
+    field public static final int STATISTICS_FACE_DETECT_MODE_FULL = 2; // 0x2
+    field public static final int STATISTICS_FACE_DETECT_MODE_OFF = 0; // 0x0
+    field public static final int STATISTICS_FACE_DETECT_MODE_SIMPLE = 1; // 0x1
+    field public static final int STATISTICS_SCENE_FLICKER_50HZ = 1; // 0x1
+    field public static final int STATISTICS_SCENE_FLICKER_60HZ = 2; // 0x2
+    field public static final int STATISTICS_SCENE_FLICKER_NONE = 0; // 0x0
+    field public static final int TONEMAP_MODE_CONTRAST_CURVE = 0; // 0x0
+    field public static final int TONEMAP_MODE_FAST = 1; // 0x1
+    field public static final int TONEMAP_MODE_HIGH_QUALITY = 2; // 0x2
   }
 
   public static class CameraMetadata.Key {
@@ -10769,38 +10881,149 @@
 
   public final class CameraProperties extends android.hardware.camera2.CameraMetadata {
     ctor public CameraProperties();
-    field public static final android.hardware.camera2.CameraMetadata.Key INFO_IDENTIFIER;
-    field public static final android.hardware.camera2.CameraMetadata.Key INFO_MODEL;
-    field public static final android.hardware.camera2.CameraMetadata.Key INFO_REMOVABLE;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AE_AVAILABLE_ANTIBANDING_MODES;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AE_COMPENSATION_RANGE;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AE_COMPENSATION_STEP;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AF_AVAILABLE_MODES;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AVAILABLE_EFFECTS;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AVAILABLE_SCENE_MODES;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AVAILABLE_VIDEO_STABILIZATION_MODES;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AWB_AVAILABLE_MODES;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_MAX_REGIONS;
+    field public static final android.hardware.camera2.CameraMetadata.Key FLASH_INFO_AVAILABLE;
     field public static final android.hardware.camera2.CameraMetadata.Key INFO_SUPPORTED_HARDWARE_LEVEL;
-    field public static final int INFO_SUPPORTED_HARDWARE_LEVEL_FULL = 1; // 0x1
-    field public static final int INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED = 0; // 0x0
+    field public static final android.hardware.camera2.CameraMetadata.Key JPEG_AVAILABLE_THUMBNAIL_SIZES;
+    field public static final android.hardware.camera2.CameraMetadata.Key LENS_FACING;
+    field public static final android.hardware.camera2.CameraMetadata.Key LENS_INFO_AVAILABLE_APERTURES;
+    field public static final android.hardware.camera2.CameraMetadata.Key LENS_INFO_AVAILABLE_FILTER_DENSITIES;
+    field public static final android.hardware.camera2.CameraMetadata.Key LENS_INFO_AVAILABLE_FOCAL_LENGTHS;
+    field public static final android.hardware.camera2.CameraMetadata.Key LENS_INFO_AVAILABLE_OPTICAL_STABILIZATION;
+    field public static final android.hardware.camera2.CameraMetadata.Key LENS_INFO_HYPERFOCAL_DISTANCE;
+    field public static final android.hardware.camera2.CameraMetadata.Key LENS_INFO_MINIMUM_FOCUS_DISTANCE;
+    field public static final android.hardware.camera2.CameraMetadata.Key LENS_INFO_SHADING_MAP_SIZE;
+    field public static final android.hardware.camera2.CameraMetadata.Key REQUEST_MAX_NUM_OUTPUT_STREAMS;
     field public static final android.hardware.camera2.CameraMetadata.Key SCALER_AVAILABLE_FORMATS;
+    field public static final android.hardware.camera2.CameraMetadata.Key SCALER_AVAILABLE_JPEG_MIN_DURATIONS;
     field public static final android.hardware.camera2.CameraMetadata.Key SCALER_AVAILABLE_JPEG_SIZES;
+    field public static final android.hardware.camera2.CameraMetadata.Key SCALER_AVAILABLE_MAX_DIGITAL_ZOOM;
+    field public static final android.hardware.camera2.CameraMetadata.Key SCALER_AVAILABLE_PROCESSED_MIN_DURATIONS;
     field public static final android.hardware.camera2.CameraMetadata.Key SCALER_AVAILABLE_PROCESSED_SIZES;
-    field public static final android.hardware.camera2.CameraMetadata.Key SCALER_AVAILABLE_RAW_SIZES;
-    field public static final android.hardware.camera2.CameraMetadata.Key SENSOR_ACTIVE_ARRAY_SIZE;
-    field public static final android.hardware.camera2.CameraMetadata.Key SENSOR_PIXEL_ARRAY_SIZE;
+    field public static final android.hardware.camera2.CameraMetadata.Key SENSOR_BASE_GAIN_FACTOR;
+    field public static final android.hardware.camera2.CameraMetadata.Key SENSOR_INFO_ACTIVE_ARRAY_SIZE;
+    field public static final android.hardware.camera2.CameraMetadata.Key SENSOR_INFO_EXPOSURE_TIME_RANGE;
+    field public static final android.hardware.camera2.CameraMetadata.Key SENSOR_INFO_MAX_FRAME_DURATION;
+    field public static final android.hardware.camera2.CameraMetadata.Key SENSOR_INFO_PHYSICAL_SIZE;
+    field public static final android.hardware.camera2.CameraMetadata.Key SENSOR_INFO_SENSITIVITY_RANGE;
+    field public static final android.hardware.camera2.CameraMetadata.Key SENSOR_MAX_ANALOG_SENSITIVITY;
+    field public static final android.hardware.camera2.CameraMetadata.Key SENSOR_ORIENTATION;
+    field public static final android.hardware.camera2.CameraMetadata.Key STATISTICS_INFO_AVAILABLE_FACE_DETECT_MODES;
+    field public static final android.hardware.camera2.CameraMetadata.Key STATISTICS_INFO_MAX_FACE_COUNT;
+    field public static final android.hardware.camera2.CameraMetadata.Key TONEMAP_MAX_CURVE_POINTS;
   }
 
   public final class CaptureRequest extends android.hardware.camera2.CameraMetadata implements android.os.Parcelable {
     method public void addTarget(android.view.Surface);
     method public void removeTarget(android.view.Surface);
+    field public static final android.hardware.camera2.CameraMetadata.Key BLACK_LEVEL_LOCK;
+    field public static final android.hardware.camera2.CameraMetadata.Key COLOR_CORRECTION_GAINS;
+    field public static final android.hardware.camera2.CameraMetadata.Key COLOR_CORRECTION_MODE;
+    field public static final android.hardware.camera2.CameraMetadata.Key COLOR_CORRECTION_TRANSFORM;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AE_ANTIBANDING_MODE;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AE_EXPOSURE_COMPENSATION;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AE_LOCK;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AE_MODE;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AE_PRECAPTURE_TRIGGER;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AE_REGIONS;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AE_TARGET_FPS_RANGE;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AF_MODE;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AF_REGIONS;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AF_TRIGGER;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AWB_LOCK;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AWB_MODE;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AWB_REGIONS;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_CAPTURE_INTENT;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_EFFECT_MODE;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_MODE;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_SCENE_MODE;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_VIDEO_STABILIZATION_MODE;
     field public static final android.os.Parcelable.Creator CREATOR;
+    field public static final android.hardware.camera2.CameraMetadata.Key EDGE_MODE;
+    field public static final android.hardware.camera2.CameraMetadata.Key FLASH_MODE;
+    field public static final android.hardware.camera2.CameraMetadata.Key JPEG_GPS_COORDINATES;
+    field public static final android.hardware.camera2.CameraMetadata.Key JPEG_GPS_PROCESSING_METHOD;
+    field public static final android.hardware.camera2.CameraMetadata.Key JPEG_GPS_TIMESTAMP;
+    field public static final android.hardware.camera2.CameraMetadata.Key JPEG_ORIENTATION;
+    field public static final android.hardware.camera2.CameraMetadata.Key JPEG_QUALITY;
+    field public static final android.hardware.camera2.CameraMetadata.Key JPEG_THUMBNAIL_QUALITY;
+    field public static final android.hardware.camera2.CameraMetadata.Key JPEG_THUMBNAIL_SIZE;
+    field public static final android.hardware.camera2.CameraMetadata.Key LENS_APERTURE;
+    field public static final android.hardware.camera2.CameraMetadata.Key LENS_FILTER_DENSITY;
+    field public static final android.hardware.camera2.CameraMetadata.Key LENS_FOCAL_LENGTH;
+    field public static final android.hardware.camera2.CameraMetadata.Key LENS_FOCUS_DISTANCE;
+    field public static final android.hardware.camera2.CameraMetadata.Key LENS_OPTICAL_STABILIZATION_MODE;
+    field public static final android.hardware.camera2.CameraMetadata.Key NOISE_REDUCTION_MODE;
+    field public static final android.hardware.camera2.CameraMetadata.Key SCALER_CROP_REGION;
     field public static final android.hardware.camera2.CameraMetadata.Key SENSOR_EXPOSURE_TIME;
+    field public static final android.hardware.camera2.CameraMetadata.Key SENSOR_FRAME_DURATION;
     field public static final android.hardware.camera2.CameraMetadata.Key SENSOR_SENSITIVITY;
+    field public static final android.hardware.camera2.CameraMetadata.Key STATISTICS_FACE_DETECT_MODE;
+    field public static final android.hardware.camera2.CameraMetadata.Key TONEMAP_CURVE_BLUE;
+    field public static final android.hardware.camera2.CameraMetadata.Key TONEMAP_CURVE_GREEN;
+    field public static final android.hardware.camera2.CameraMetadata.Key TONEMAP_CURVE_RED;
+    field public static final android.hardware.camera2.CameraMetadata.Key TONEMAP_MODE;
   }
 
   public final class CaptureResult extends android.hardware.camera2.CameraMetadata {
+    field public static final android.hardware.camera2.CameraMetadata.Key BLACK_LEVEL_LOCK;
+    field public static final android.hardware.camera2.CameraMetadata.Key COLOR_CORRECTION_GAINS;
+    field public static final android.hardware.camera2.CameraMetadata.Key COLOR_CORRECTION_TRANSFORM;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AE_REGIONS;
     field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AE_STATE;
-    field public static final int CONTROL_AE_STATE_CONVERGED = 2; // 0x2
-    field public static final int CONTROL_AE_STATE_FLASH_REQUIRED = 4; // 0x4
-    field public static final int CONTROL_AE_STATE_INACTIVE = 0; // 0x0
-    field public static final int CONTROL_AE_STATE_LOCKED = 3; // 0x3
-    field public static final int CONTROL_AE_STATE_PRECAPTURE = 5; // 0x5
-    field public static final int CONTROL_AE_STATE_SEARCHING = 1; // 0x1
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AF_MODE;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AF_REGIONS;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AF_STATE;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AWB_MODE;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AWB_REGIONS;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_AWB_STATE;
+    field public static final android.hardware.camera2.CameraMetadata.Key CONTROL_MODE;
+    field public static final android.hardware.camera2.CameraMetadata.Key EDGE_MODE;
+    field public static final android.hardware.camera2.CameraMetadata.Key FLASH_MODE;
+    field public static final android.hardware.camera2.CameraMetadata.Key FLASH_STATE;
+    field public static final android.hardware.camera2.CameraMetadata.Key JPEG_GPS_COORDINATES;
+    field public static final android.hardware.camera2.CameraMetadata.Key JPEG_GPS_PROCESSING_METHOD;
+    field public static final android.hardware.camera2.CameraMetadata.Key JPEG_GPS_TIMESTAMP;
+    field public static final android.hardware.camera2.CameraMetadata.Key JPEG_ORIENTATION;
+    field public static final android.hardware.camera2.CameraMetadata.Key JPEG_QUALITY;
+    field public static final android.hardware.camera2.CameraMetadata.Key JPEG_THUMBNAIL_QUALITY;
+    field public static final android.hardware.camera2.CameraMetadata.Key JPEG_THUMBNAIL_SIZE;
+    field public static final android.hardware.camera2.CameraMetadata.Key LENS_APERTURE;
+    field public static final android.hardware.camera2.CameraMetadata.Key LENS_FILTER_DENSITY;
+    field public static final android.hardware.camera2.CameraMetadata.Key LENS_FOCAL_LENGTH;
+    field public static final android.hardware.camera2.CameraMetadata.Key LENS_FOCUS_DISTANCE;
+    field public static final android.hardware.camera2.CameraMetadata.Key LENS_FOCUS_RANGE;
+    field public static final android.hardware.camera2.CameraMetadata.Key LENS_OPTICAL_STABILIZATION_MODE;
+    field public static final android.hardware.camera2.CameraMetadata.Key LENS_STATE;
+    field public static final android.hardware.camera2.CameraMetadata.Key NOISE_REDUCTION_MODE;
+    field public static final android.hardware.camera2.CameraMetadata.Key REQUEST_FRAME_COUNT;
+    field public static final android.hardware.camera2.CameraMetadata.Key SCALER_CROP_REGION;
+    field public static final android.hardware.camera2.CameraMetadata.Key SENSOR_EXPOSURE_TIME;
+    field public static final android.hardware.camera2.CameraMetadata.Key SENSOR_FRAME_DURATION;
+    field public static final android.hardware.camera2.CameraMetadata.Key SENSOR_SENSITIVITY;
     field public static final android.hardware.camera2.CameraMetadata.Key SENSOR_TIMESTAMP;
-    field public static final android.hardware.camera2.CameraMetadata.Key STATISTICS_DETECTED_FACES;
+    field public static final android.hardware.camera2.CameraMetadata.Key STATISTICS_FACE_DETECT_MODE;
+    field public static final android.hardware.camera2.CameraMetadata.Key STATISTICS_FACE_IDS;
+    field public static final android.hardware.camera2.CameraMetadata.Key STATISTICS_FACE_LANDMARKS;
+    field public static final android.hardware.camera2.CameraMetadata.Key STATISTICS_FACE_RECTANGLES;
+    field public static final android.hardware.camera2.CameraMetadata.Key STATISTICS_FACE_SCORES;
+    field public static final android.hardware.camera2.CameraMetadata.Key STATISTICS_LENS_SHADING_MAP;
+    field public static final android.hardware.camera2.CameraMetadata.Key STATISTICS_PREDICTED_COLOR_GAINS;
+    field public static final android.hardware.camera2.CameraMetadata.Key STATISTICS_PREDICTED_COLOR_TRANSFORM;
+    field public static final android.hardware.camera2.CameraMetadata.Key STATISTICS_SCENE_FLICKER;
+    field public static final android.hardware.camera2.CameraMetadata.Key TONEMAP_CURVE_BLUE;
+    field public static final android.hardware.camera2.CameraMetadata.Key TONEMAP_CURVE_GREEN;
+    field public static final android.hardware.camera2.CameraMetadata.Key TONEMAP_CURVE_RED;
+    field public static final android.hardware.camera2.CameraMetadata.Key TONEMAP_MODE;
   }
 
   public static class CaptureResult.Face {
@@ -11582,6 +11805,18 @@
     field public static final int TEMPORARILY_UNAVAILABLE = 1; // 0x1
   }
 
+  public abstract class SettingInjectorService extends android.app.IntentService {
+    ctor public SettingInjectorService(java.lang.String);
+    method protected abstract android.location.SettingInjectorService.Status getStatus();
+    method protected final void onHandleIntent(android.content.Intent);
+  }
+
+  public static final class SettingInjectorService.Status {
+    ctor public SettingInjectorService.Status(java.lang.String, boolean);
+    field public final boolean enabled;
+    field public final java.lang.String summary;
+  }
+
 }
 
 package android.media {
@@ -12059,6 +12294,7 @@
     method public final void queueSecureInputBuffer(int, int, android.media.MediaCodec.CryptoInfo, long, int) throws android.media.MediaCodec.CryptoException;
     method public final void release();
     method public final void releaseOutputBuffer(int, boolean);
+    method public final void setParameters(java.util.Map<java.lang.String, java.lang.Object>);
     method public final void setVideoScalingMode(int);
     method public final void signalEndOfInputStream();
     method public final void start();
@@ -12072,6 +12308,9 @@
     field public static final int INFO_OUTPUT_BUFFERS_CHANGED = -3; // 0xfffffffd
     field public static final int INFO_OUTPUT_FORMAT_CHANGED = -2; // 0xfffffffe
     field public static final int INFO_TRY_AGAIN_LATER = -1; // 0xffffffff
+    field public static final java.lang.String PARAMETER_KEY_REQUEST_SYNC_FRAME = "request-sync";
+    field public static final java.lang.String PARAMETER_KEY_SUSPEND = "drop-input-frames";
+    field public static final java.lang.String PARAMETER_KEY_VIDEO_BITRATE = "videoBitrate";
     field public static final int VIDEO_SCALING_MODE_SCALE_TO_FIT = 1; // 0x1
     field public static final int VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING = 2; // 0x2
   }
@@ -12113,6 +12352,7 @@
 
   public static final class MediaCodecInfo.CodecCapabilities {
     ctor public MediaCodecInfo.CodecCapabilities();
+    method public final boolean isFeatureSupported(java.lang.String);
     field public static final int COLOR_Format12bitRGB444 = 3; // 0x3
     field public static final int COLOR_Format16bitARGB1555 = 5; // 0x5
     field public static final int COLOR_Format16bitARGB4444 = 4; // 0x4
@@ -12159,6 +12399,7 @@
     field public static final int COLOR_FormatYUV444Interleaved = 29; // 0x1d
     field public static final int COLOR_QCOM_FormatYUV420SemiPlanar = 2141391872; // 0x7fa30c00
     field public static final int COLOR_TI_FormatYUV420PackedSemiPlanar = 2130706688; // 0x7f000100
+    field public static final java.lang.String FEATURE_AdaptivePlayback = "adaptive-playback";
     field public int[] colorFormats;
     field public android.media.MediaCodecInfo.CodecProfileLevel[] profileLevels;
   }
diff --git a/core/java/android/app/FragmentManager.java b/core/java/android/app/FragmentManager.java
index 7358f73..a7789d6 100644
--- a/core/java/android/app/FragmentManager.java
+++ b/core/java/android/app/FragmentManager.java
@@ -1328,12 +1328,19 @@
         }
     }
 
+    /**
+     * Adds an action to the queue of pending actions.
+     *
+     * @param action the action to add
+     * @param allowStateLoss whether to allow loss of state information
+     * @throws IllegalStateException if the activity has been destroyed
+     */
     public void enqueueAction(Runnable action, boolean allowStateLoss) {
         if (!allowStateLoss) {
             checkStateLoss();
         }
         synchronized (this) {
-            if (mActivity == null) {
+            if (mDestroyed || mActivity == null) {
                 throw new IllegalStateException("Activity has been destroyed");
             }
             if (mPendingActions == null) {
diff --git a/core/java/android/bluetooth/BluetoothAdapter.java b/core/java/android/bluetooth/BluetoothAdapter.java
index 1ea13e1..e062fa8 100644
--- a/core/java/android/bluetooth/BluetoothAdapter.java
+++ b/core/java/android/bluetooth/BluetoothAdapter.java
@@ -1704,7 +1704,7 @@
         public void onGetDescriptor(String address, int srvcType,
                                     int srvcInstId, ParcelUuid srvcUuid,
                                     int charInstId, ParcelUuid charUuid,
-                                    ParcelUuid descUuid) {
+                                    int descInstId, ParcelUuid descUuid) {
             // no op
         }
 
@@ -1734,14 +1734,14 @@
         public void onDescriptorRead(String address, int status, int srvcType,
                                      int srvcInstId, ParcelUuid srvcUuid,
                                      int charInstId, ParcelUuid charUuid,
-                                     ParcelUuid descrUuid, byte[] value) {
+                                     int descInstId, ParcelUuid descrUuid, byte[] value) {
             // no op
         }
 
         public void onDescriptorWrite(String address, int status, int srvcType,
                                       int srvcInstId, ParcelUuid srvcUuid,
                                       int charInstId, ParcelUuid charUuid,
-                                      ParcelUuid descrUuid) {
+                                      int descInstId, ParcelUuid descrUuid) {
             // no op
         }
 
@@ -1752,6 +1752,10 @@
         public void onReadRemoteRssi(String address, int rssi, int status) {
             // no op
         }
+
+        public void onListen(int status) {
+            // no op
+        }
     }
 
 }
diff --git a/core/java/android/bluetooth/BluetoothGatt.java b/core/java/android/bluetooth/BluetoothGatt.java
index df3ec1a..a8c310b 100644
--- a/core/java/android/bluetooth/BluetoothGatt.java
+++ b/core/java/android/bluetooth/BluetoothGatt.java
@@ -261,7 +261,7 @@
             public void onGetDescriptor(String address, int srvcType,
                              int srvcInstId, ParcelUuid srvcUuid,
                              int charInstId, ParcelUuid charUuid,
-                             ParcelUuid descUuid) {
+                             int descrInstId, ParcelUuid descUuid) {
                 if (DBG) Log.d(TAG, "onGetDescriptor() - Device=" + address + " UUID=" + descUuid);
 
                 if (!address.equals(mDevice.getAddress())) {
@@ -276,7 +276,7 @@
                 if (characteristic == null) return;
 
                 characteristic.addDescriptor(new BluetoothGattDescriptor(
-                    characteristic, descUuid.getUuid(), 0));
+                    characteristic, descUuid.getUuid(), descrInstId, 0));
             }
 
             /**
@@ -429,7 +429,8 @@
             public void onDescriptorRead(String address, int status, int srvcType,
                              int srvcInstId, ParcelUuid srvcUuid,
                              int charInstId, ParcelUuid charUuid,
-                             ParcelUuid descrUuid, byte[] value) {
+                             int descrInstId, ParcelUuid descrUuid,
+                             byte[] value) {
                 if (DBG) Log.d(TAG, "onDescriptorRead() - Device=" + address + " UUID=" + charUuid);
 
                 if (!address.equals(mDevice.getAddress())) {
@@ -444,7 +445,7 @@
                 if (characteristic == null) return;
 
                 BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
-                        descrUuid.getUuid());
+                        descrUuid.getUuid(), descrInstId);
                 if (descriptor == null) return;
 
                 if (status == 0) descriptor.setValue(value);
@@ -456,7 +457,7 @@
                         mAuthRetry = true;
                         mService.readDescriptor(mClientIf, address,
                             srvcType, srvcInstId, srvcUuid, charInstId, charUuid,
-                            descrUuid, AUTHENTICATION_MITM);
+                            descrInstId, descrUuid, AUTHENTICATION_MITM);
                     } catch (RemoteException e) {
                         Log.e(TAG,"",e);
                     }
@@ -478,7 +479,7 @@
             public void onDescriptorWrite(String address, int status, int srvcType,
                              int srvcInstId, ParcelUuid srvcUuid,
                              int charInstId, ParcelUuid charUuid,
-                             ParcelUuid descrUuid) {
+                             int descrInstId, ParcelUuid descrUuid) {
                 if (DBG) Log.d(TAG, "onDescriptorWrite() - Device=" + address + " UUID=" + charUuid);
 
                 if (!address.equals(mDevice.getAddress())) {
@@ -493,7 +494,7 @@
                 if (characteristic == null) return;
 
                 BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
-                        descrUuid.getUuid());
+                        descrUuid.getUuid(), descrInstId);
                 if (descriptor == null) return;
 
                 if ((status == GATT_INSUFFICIENT_AUTHENTICATION
@@ -503,7 +504,7 @@
                         mAuthRetry = true;
                         mService.writeDescriptor(mClientIf, address,
                             srvcType, srvcInstId, srvcUuid, charInstId, charUuid,
-                            descrUuid, characteristic.getWriteType(),
+                            descrInstId, descrUuid, characteristic.getWriteType(),
                             AUTHENTICATION_MITM, descriptor.getValue());
                     } catch (RemoteException e) {
                         Log.e(TAG,"",e);
@@ -552,6 +553,14 @@
                     Log.w(TAG, "Unhandled exception in callback", ex);
                 }
             }
+
+            /**
+             * Listen command status callback
+             * @hide
+             */
+            public void onListen(int status) {
+                if (DBG) Log.d(TAG, "onListen() - status=" + status);
+            }
         };
 
     /*package*/ BluetoothGatt(Context context, IBluetoothGatt iGatt, BluetoothDevice device) {
@@ -684,6 +693,63 @@
         return true;
     }
 
+   /**
+     * Starts or stops sending of advertisement packages to listen for connection
+     * requests from a central devices.
+     *
+     * <p>Requires {@link android.Manifest.permission#BLUETOOTH} permission.
+     *
+     * @param start Start or stop advertising
+     */
+    /*package*/ void listen(boolean start) {
+        if (DBG) Log.d(TAG, "listen() - start: " + start);
+        if (mService == null || mClientIf == 0) return;
+
+        try {
+            mService.clientListen(mClientIf, start);
+        } catch (RemoteException e) {
+            Log.e(TAG,"",e);
+        }
+    }
+
+    /**
+     * Sets the advertising data contained in the adv. response packet.
+     *
+     * <p>Requires {@link android.Manifest.permission#BLUETOOTH} permission.
+     *
+     * @param advData true to set adv. data, false to set scan response
+     * @param includeName Inlucde the name in the adv. response
+     * @param includeTxPower Include TX power value
+     * @param minInterval Minimum desired scan interval (optional)
+     * @param maxInterval Maximum desired scan interval (optional)
+     * @param appearance The appearance flags for the device (optional)
+     * @param manufacturerData Manufacturer specific data including company ID (optional)
+     */
+    /*package*/ void setAdvData(boolean advData, boolean includeName, boolean includeTxPower,
+                           Integer minInterval, Integer maxInterval,
+                           Integer appearance, Byte[] manufacturerData) {
+        if (DBG) Log.d(TAG, "setAdvData()");
+        if (mService == null || mClientIf == 0) return;
+
+        byte[] data = new byte[0];
+        if (manufacturerData != null) {
+            data = new byte[manufacturerData.length];
+            for(int i = 0; i != manufacturerData.length; ++i) {
+                data[i] = manufacturerData[i];
+            }
+        }
+
+        try {
+            mService.setAdvData(mClientIf, !advData,
+                includeName, includeTxPower,
+                minInterval != null ? minInterval : 0,
+                maxInterval != null ? maxInterval : 0,
+                appearance != null ? appearance : 0, data);
+        } catch (RemoteException e) {
+            Log.e(TAG,"",e);
+        }
+    }
+
     /**
      * Disconnects an established connection, or cancels a connection attempt
      * currently in progress.
@@ -915,11 +981,11 @@
         if (device == null) return false;
 
         try {
-            mService.readDescriptor(mClientIf, device.getAddress(),
-                service.getType(), service.getInstanceId(),
-                new ParcelUuid(service.getUuid()), characteristic.getInstanceId(),
-                new ParcelUuid(characteristic.getUuid()),
-                new ParcelUuid(descriptor.getUuid()), AUTHENTICATION_NONE);
+            mService.readDescriptor(mClientIf, device.getAddress(), service.getType(),
+                service.getInstanceId(), new ParcelUuid(service.getUuid()),
+                characteristic.getInstanceId(), new ParcelUuid(characteristic.getUuid()),
+                descriptor.getInstanceId(), new ParcelUuid(descriptor.getUuid()),
+                AUTHENTICATION_NONE);
         } catch (RemoteException e) {
             Log.e(TAG,"",e);
             return false;
@@ -953,11 +1019,10 @@
         if (device == null) return false;
 
         try {
-            mService.writeDescriptor(mClientIf, device.getAddress(),
-                service.getType(), service.getInstanceId(),
-                new ParcelUuid(service.getUuid()), characteristic.getInstanceId(),
-                new ParcelUuid(characteristic.getUuid()),
-                new ParcelUuid(descriptor.getUuid()),
+            mService.writeDescriptor(mClientIf, device.getAddress(), service.getType(),
+                service.getInstanceId(), new ParcelUuid(service.getUuid()),
+                characteristic.getInstanceId(), new ParcelUuid(characteristic.getUuid()),
+                descriptor.getInstanceId(), new ParcelUuid(descriptor.getUuid()),
                 characteristic.getWriteType(), AUTHENTICATION_NONE,
                 descriptor.getValue());
         } catch (RemoteException e) {
diff --git a/core/java/android/bluetooth/BluetoothGattCharacteristic.java b/core/java/android/bluetooth/BluetoothGattCharacteristic.java
index 033f079..f0ecbb4 100644
--- a/core/java/android/bluetooth/BluetoothGattCharacteristic.java
+++ b/core/java/android/bluetooth/BluetoothGattCharacteristic.java
@@ -283,6 +283,20 @@
     }
 
     /**
+     * Get a descriptor by UUID and isntance id.
+     * @hide
+     */
+    /*package*/  BluetoothGattDescriptor getDescriptor(UUID uuid, int instanceId) {
+        for(BluetoothGattDescriptor descriptor : mDescriptors) {
+            if (descriptor.getUuid().equals(uuid)
+             && descriptor.getInstanceId() == instanceId) {
+                return descriptor;
+            }
+        }
+        return null;
+    }
+
+    /**
      * Returns the service this characteristic belongs to.
      * @return The asscociated service
      */
diff --git a/core/java/android/bluetooth/BluetoothGattDescriptor.java b/core/java/android/bluetooth/BluetoothGattDescriptor.java
index 1cd6878..5f525dc 100644
--- a/core/java/android/bluetooth/BluetoothGattDescriptor.java
+++ b/core/java/android/bluetooth/BluetoothGattDescriptor.java
@@ -91,6 +91,12 @@
     protected UUID mUuid;
 
     /**
+     * Instance ID for this descriptor.
+     * @hide
+     */
+    protected int mInstance;
+
+    /**
      * Permissions for this descriptor
      * @hide
      */
@@ -116,7 +122,7 @@
      * @param permissions Permissions for this descriptor
      */
     public BluetoothGattDescriptor(UUID uuid, int permissions) {
-        initDescriptor(null, uuid, permissions);
+        initDescriptor(null, uuid, 0, permissions);
     }
 
     /**
@@ -128,14 +134,15 @@
      * @param permissions Permissions for this descriptor
      */
     /*package*/ BluetoothGattDescriptor(BluetoothGattCharacteristic characteristic, UUID uuid,
-                                    int permissions) {
-        initDescriptor(characteristic, uuid, permissions);
+                                    int instance, int permissions) {
+        initDescriptor(characteristic, uuid, instance, permissions);
     }
 
     private void initDescriptor(BluetoothGattCharacteristic characteristic, UUID uuid,
-                                int permissions) {
+                                int instance, int permissions) {
         mCharacteristic = characteristic;
         mUuid = uuid;
+        mInstance = instance;
         mPermissions = permissions;
     }
 
@@ -165,6 +172,21 @@
     }
 
     /**
+     * Returns the instance ID for this descriptor.
+     *
+     * <p>If a remote device offers multiple descriptors with the same UUID,
+     * the instance ID is used to distuinguish between descriptors.
+     *
+     * <p>Requires {@link android.Manifest.permission#BLUETOOTH} permission.
+     *
+     * @return Instance ID of this descriptor
+     * @hide
+     */
+    public int getInstanceId() {
+        return mInstance;
+    }
+
+    /**
      * Returns the permissions for this descriptor.
      *
      * @return Permissions of this descriptor
diff --git a/core/java/android/bluetooth/BluetoothGattService.java b/core/java/android/bluetooth/BluetoothGattService.java
index 39a435b..1e66369 100644
--- a/core/java/android/bluetooth/BluetoothGattService.java
+++ b/core/java/android/bluetooth/BluetoothGattService.java
@@ -152,8 +152,8 @@
      */
     /*package*/ BluetoothGattCharacteristic getCharacteristic(UUID uuid, int instanceId) {
         for(BluetoothGattCharacteristic characteristic : mCharacteristics) {
-            if (uuid.equals(characteristic.getUuid()) &&
-                    mInstanceId == instanceId)
+            if (uuid.equals(characteristic.getUuid())
+             && characteristic.getInstanceId() == instanceId)
                 return characteristic;
         }
         return null;
diff --git a/core/java/android/bluetooth/IBluetoothGatt.aidl b/core/java/android/bluetooth/IBluetoothGatt.aidl
index c89d132..df393db 100644
--- a/core/java/android/bluetooth/IBluetoothGatt.aidl
+++ b/core/java/android/bluetooth/IBluetoothGatt.aidl
@@ -37,6 +37,10 @@
     void unregisterClient(in int clientIf);
     void clientConnect(in int clientIf, in String address, in boolean isDirect);
     void clientDisconnect(in int clientIf, in String address);
+    void clientListen(in int clientIf, in boolean start);
+    void setAdvData(in int clientIf, in boolean setScanRsp, in boolean inclName,
+                            in boolean inclTxPower, in int minInterval, in int maxInterval,
+                            in int appearance, in byte[] manufacturerData);
     void refreshDevice(in int clientIf, in String address);
     void discoverServices(in int clientIf, in String address);
     void readCharacteristic(in int clientIf, in String address, in int srvcType,
@@ -50,12 +54,13 @@
     void readDescriptor(in int clientIf, in String address, in int srvcType,
                             in int srvcInstanceId, in ParcelUuid srvcId,
                             in int charInstanceId, in ParcelUuid charId,
-                            in ParcelUuid descrUuid, in int authReq);
+                            in int descrInstanceId, in ParcelUuid descrUuid,
+                            in int authReq);
     void writeDescriptor(in int clientIf, in String address, in int srvcType,
                             in int srvcInstanceId, in ParcelUuid srvcId,
                             in int charInstanceId, in ParcelUuid charId,
-                            in ParcelUuid descrId, in int writeType,
-                            in int authReq, in byte[] value);
+                            in int descrInstanceId, in ParcelUuid descrId,
+                            in int writeType, in int authReq, in byte[] value);
     void registerForNotification(in int clientIf, in String address, in int srvcType,
                             in int srvcInstanceId, in ParcelUuid srvcId,
                             in int charInstanceId, in ParcelUuid charId,
diff --git a/core/java/android/bluetooth/IBluetoothGattCallback.aidl b/core/java/android/bluetooth/IBluetoothGattCallback.aidl
index fc52172..60c297b 100644
--- a/core/java/android/bluetooth/IBluetoothGattCallback.aidl
+++ b/core/java/android/bluetooth/IBluetoothGattCallback.aidl
@@ -39,7 +39,7 @@
     void onGetDescriptor(in String address, in int srvcType,
                              in int srvcInstId, in ParcelUuid srvcUuid,
                              in int charInstId, in ParcelUuid charUuid,
-                             in ParcelUuid descrUuid);
+                             in int descrInstId, in ParcelUuid descrUuid);
     void onSearchComplete(in String address, in int status);
     void onCharacteristicRead(in String address, in int status, in int srvcType,
                              in int srvcInstId, in ParcelUuid srvcUuid,
@@ -52,14 +52,16 @@
     void onDescriptorRead(in String address, in int status, in int srvcType,
                              in int srvcInstId, in ParcelUuid srvcUuid,
                              in int charInstId, in ParcelUuid charUuid,
-                             in ParcelUuid descrUuid, in byte[] value);
+                             in int descrInstId, in ParcelUuid descrUuid,
+                             in byte[] value);
     void onDescriptorWrite(in String address, in int status, in int srvcType,
                              in int srvcInstId, in ParcelUuid srvcUuid,
                              in int charInstId, in ParcelUuid charUuid,
-                             in ParcelUuid descrUuid);
+                             in int descrInstId, in ParcelUuid descrUuid);
     void onNotify(in String address, in int srvcType,
                              in int srvcInstId, in ParcelUuid srvcUuid,
                              in int charInstId, in ParcelUuid charUuid,
                              in byte[] value);
     void onReadRemoteRssi(in String address, in int rssi, in int status);
+    void onListen(in int status);
 }
diff --git a/core/java/android/content/res/Configuration.java b/core/java/android/content/res/Configuration.java
index 1c28138..0402eeb 100644
--- a/core/java/android/content/res/Configuration.java
+++ b/core/java/android/content/res/Configuration.java
@@ -786,9 +786,11 @@
             // 2 most significant bits in screenLayout).
             setLayoutDirection(locale);
         }
-        if (delta.screenLayout != 0 && screenLayout != delta.screenLayout) {
+        final int deltaScreenLayoutDir = delta.screenLayout & SCREENLAYOUT_LAYOUTDIR_MASK;
+        if (deltaScreenLayoutDir != SCREENLAYOUT_LAYOUTDIR_UNDEFINED &&
+                deltaScreenLayoutDir != (screenLayout & SCREENLAYOUT_LAYOUTDIR_MASK)) {
+            screenLayout = (screenLayout & ~SCREENLAYOUT_LAYOUTDIR_MASK) | deltaScreenLayoutDir;
             changed |= ActivityInfo.CONFIG_LAYOUT_DIRECTION;
-            setLayoutDirection(locale);
         }
         if (delta.userSetLocale && (!userSetLocale || ((changed & ActivityInfo.CONFIG_LOCALE) != 0)))
         {
@@ -937,7 +939,9 @@
             changed |= ActivityInfo.CONFIG_LOCALE;
             changed |= ActivityInfo.CONFIG_LAYOUT_DIRECTION;
         }
-        if (delta.screenLayout != 0 && screenLayout != delta.screenLayout) {
+        final int deltaScreenLayoutDir = delta.screenLayout & SCREENLAYOUT_LAYOUTDIR_MASK;
+        if (deltaScreenLayoutDir != SCREENLAYOUT_LAYOUTDIR_UNDEFINED &&
+                deltaScreenLayoutDir != (screenLayout & SCREENLAYOUT_LAYOUTDIR_MASK)) {
             changed |= ActivityInfo.CONFIG_LAYOUT_DIRECTION;
         }
         if (delta.touchscreen != TOUCHSCREEN_UNDEFINED
diff --git a/core/java/android/hardware/camera2/CameraDevice.java b/core/java/android/hardware/camera2/CameraDevice.java
index 422d827..19b6057 100644
--- a/core/java/android/hardware/camera2/CameraDevice.java
+++ b/core/java/android/hardware/camera2/CameraDevice.java
@@ -157,14 +157,13 @@
      *   obtain the Surface with
      *   {@link android.renderscript.Allocation#getSurface}.</li>
      *
-     * <li>For access to uncompressed, JPEG, or raw sensor data in the
-     *   application: Create a {@link android.media.ImageReader} object with the
-     *   desired {@link CameraProperties#SCALER_AVAILABLE_FORMATS image format},
-     *   and a size from the matching
+     * <li>For access to uncompressed or JPEG data in the application: Create a
+     *   {@link android.media.ImageReader} object with the desired
+     *   {@link CameraProperties#SCALER_AVAILABLE_FORMATS image format}, and a
+     *   size from the matching
      *   {@link CameraProperties#SCALER_AVAILABLE_PROCESSED_SIZES processed},
-     *   {@link CameraProperties#SCALER_AVAILABLE_JPEG_SIZES jpeg}, or
-     *   {@link CameraProperties#SCALER_AVAILABLE_RAW_SIZES raw} sizes. Then
-     *   obtain a Surface from it.</li>
+     *   {@link CameraProperties#SCALER_AVAILABLE_JPEG_SIZES jpeg}. Then obtain
+     *   a Surface from it.</li>
      *
      * </ul>
      *
@@ -173,6 +172,11 @@
      * <p>This function can take several hundred milliseconds to execute, since
      * camera hardware may need to be powered on or reconfigured.</p>
      *
+     * <p>The camera device will query each Surface's size and formats upon this
+     * call, so they must be set to a valid setting at this time (in particular:
+     * if the format is user-visible, it must be one of android.scaler.availableFormats;
+     * and the size must be one of android.scaler.available[Processed|Jpeg]Sizes).</p>
+     *
      * <p>To change the configuration after requests have been submitted to the
      * device, the camera device must be idle. To idle the device, stop any
      * repeating requests with {@link #stopRepeating stopRepeating}, and then
diff --git a/core/java/android/hardware/camera2/CameraMetadata.java b/core/java/android/hardware/camera2/CameraMetadata.java
index e7f34d8..3fda3b7 100644
--- a/core/java/android/hardware/camera2/CameraMetadata.java
+++ b/core/java/android/hardware/camera2/CameraMetadata.java
@@ -25,11 +25,6 @@
 import android.util.Log;
 
 import java.lang.reflect.Array;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Field;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
 import java.nio.ByteBuffer;
 import java.nio.ByteOrder;
 import java.util.ArrayList;
@@ -275,110 +270,11 @@
             boolean sizeOnly) {
 
         MetadataMarshalClass<T> marshaler = getMarshaler(type, nativeType);
-        if (marshaler != null) {
-            return marshaler.marshal(value, buffer, nativeType, sizeOnly);
+        if (marshaler == null) {
+            throw new IllegalArgumentException(String.format("Unknown Key type: %s", type));
         }
 
-        /**
-         * FIXME: This doesn't actually work because getFields() returns fields in an unordered
-         * manner. Although we could sort and get the data to come out correctly on the *java* side,
-         * it would not be data-compatible with our strict XML definitions.
-         *
-         * Rewrite this code to use Parcelables instead, they are most likely compatible with
-         * what we are trying to do in general.
-         */
-        List<Field> instanceFields = findInstanceFields(type);
-        if (instanceFields.size() == 0) {
-            throw new UnsupportedOperationException("Class has no instance fields: " + type);
-        }
-
-        int fieldCount = instanceFields.size();
-        int bufferSize = 0;
-
-        HashSet<Class<?>> fieldTypes = new HashSet<Class<?>>();
-        for (Field f : instanceFields) {
-            fieldTypes.add(f.getType());
-        }
-
-        /**
-         * Pack arguments one field at a time. If we can't access field, look for its accessor
-         * method instead.
-         */
-        for (int i = 0; i < fieldCount; ++i) {
-            Object arg;
-
-            Field f = instanceFields.get(i);
-
-            if ((f.getModifiers() & Modifier.PUBLIC) != 0) {
-                try {
-                    arg = f.get(value);
-                } catch (IllegalAccessException e) {
-                    throw new UnsupportedOperationException(
-                            "Failed to access field " + f + " of type " + type, e);
-                } catch (IllegalArgumentException e) {
-                    throw new UnsupportedOperationException(
-                            "Illegal arguments when accessing field " + f + " of type " + type, e);
-                }
-            } else {
-                Method accessor = null;
-                // try to find a public accessor method
-                for(Method m : type.getMethods()) {
-                    Log.v(TAG, String.format("Looking for getter in method %s for field %s", m, f));
-
-                    // Must have 0 arguments
-                    if (m.getParameterTypes().length != 0) {
-                        continue;
-                    }
-
-                    // Return type must be same as field type
-                    if (m.getReturnType() != f.getType()) {
-                        continue;
-                    }
-
-                    // Strip 'm' from variable prefix if the next letter is capitalized
-                    String fieldName = f.getName();
-                    char[] nameChars = f.getName().toCharArray();
-                    if (nameChars.length >= 2 && nameChars[0] == 'm'
-                            && Character.isUpperCase(nameChars[1])) {
-                        fieldName = String.valueOf(nameChars, /*start*/1, nameChars.length - 1);
-                    }
-
-                    Log.v(TAG, String.format("Normalized field name: %s", fieldName));
-
-                    // #getFoo() , getfoo(), foo(), all match.
-                    if (m.getName().toLowerCase().equals(fieldName.toLowerCase()) ||
-                            m.getName().toLowerCase().equals("get" + fieldName.toLowerCase())) {
-                        accessor = m;
-                        break;
-                    }
-                }
-
-                if (accessor == null) {
-                    throw new UnsupportedOperationException(
-                            "Failed to find getter method for field " + f + " in type " + type);
-                }
-
-                try {
-                    arg = accessor.invoke(value);
-                } catch (IllegalAccessException e) {
-                    // Impossible
-                    throw new UnsupportedOperationException("Failed to access method + " + accessor
-                            + " in type " + type, e);
-                } catch (IllegalArgumentException e) {
-                    // Impossible
-                    throw new UnsupportedOperationException("Bad arguments for method + " + accessor
-                            + " in type " + type, e);
-                } catch (InvocationTargetException e) {
-                    // Possibly but extremely unlikely
-                    throw new UnsupportedOperationException("Failed to invoke method + " + accessor
-                            + " in type " + type, e);
-                }
-            }
-
-            bufferSize += packSingle(arg, buffer, (Class<Object>)f.getType(), nativeType, sizeOnly);
-        }
-
-        return bufferSize;
+        return marshaler.marshal(value, buffer, nativeType, sizeOnly);
     }
 
     private static <T> int packArray(T value, ByteBuffer buffer, Class<T> type, int nativeType,
@@ -442,30 +338,6 @@
         return val;
     }
 
-    private static <T> List<Field> findInstanceFields(Class<T> type) {
-        List<Field> fields = new ArrayList<Field>();
-
-        for (Field f : type.getDeclaredFields()) {
-            if (f.isSynthetic()) {
-                throw new UnsupportedOperationException(
-                        "Marshalling synthetic fields not supported in type " + type);
-            }
-
-            // Skip static fields
-            int modifiers = f.getModifiers();
-            if ((modifiers & Modifier.STATIC) == 0) {
-                fields.add(f);
-            }
-
-            Log.v(TAG, String.format("Field %s has modifiers %d", f, modifiers));
-        }
-
-        if (type.getDeclaredFields().length == 0) {
-            Log.w(TAG, String.format("Type %s had 0 fields of any kind", type));
-        }
-        return fields;
-    }
-
     @SuppressWarnings({"unchecked", "rawtypes"})
     private static <T> T unpackSingle(ByteBuffer buffer, Class<T> type, int nativeType) {
 
@@ -486,84 +358,6 @@
         return instance;
     }
 
-    private static <T> Constructor<T> findApplicableConstructor(Class<T> type) {
-
-        List<Field> instanceFields = findInstanceFields(type);
-        if (instanceFields.size() == 0) {
-            throw new UnsupportedOperationException("Class has no instance fields: " + type);
-        }
-
-        Constructor<T> constructor = null;
-        int fieldCount = instanceFields.size();
-
-        HashSet<Class<?>> fieldTypes = new HashSet<Class<?>>();
-        for (Field f : instanceFields) {
-            fieldTypes.add(f.getType());
-        }
-
-        /**
-         * Find which constructor to use:
-         * - must be public
-         * - same amount of arguments as there are instance fields
-         * - each argument is same type as each field (in any order)
-         */
-        @SuppressWarnings("unchecked")
-        Constructor<T>[] constructors = (Constructor<T>[]) type.getConstructors();
-        for (Constructor<T> ctor : constructors) {
-            Log.v(TAG, String.format("Inspecting constructor '%s'", ctor));
-
-            Class<?>[] parameterTypes = ctor.getParameterTypes();
-            if (parameterTypes.length == fieldCount) {
-                boolean match = true;
-
-                HashSet<Class<?>> argTypes = new HashSet<Class<?>>();
-                for (Class<?> t : parameterTypes) {
-                    argTypes.add(t);
-                }
-
-                // Order does not matter
-                match = argTypes.equals(fieldTypes);
-
-                /*
-                // check if the types are the same
-                for (int i = 0; i < fieldCount; ++i) {
-                    if (parameterTypes[i] != instanceFields.get(i).getType()) {
-
-                        Log.v(TAG, String.format(
-                                "Constructor arg (%d) type %s did not match field type %s", i,
-                                parameterTypes[i], instanceFields.get(i).getType()));
-
-                        match = false;
-                        break;
-                    }
-                }
-                */
-
-                if (match) {
-                    constructor = ctor;
-                    break;
-                } else {
-                    Log.w(TAG, String.format("Constructor args did not have matching types"));
-                }
-            } else {
-                Log.v(TAG, String.format(
-                        "Constructor did not have expected amount of fields (had %d, expected %d)",
-                        parameterTypes.length, fieldCount));
-            }
-        }
-
-        if (constructors.length == 0) {
-            Log.w(TAG, String.format("Type %s had no public constructors", type));
-        }
-
-        if (constructor == null) {
-            throw new UnsupportedOperationException(
-                    "Failed to find any applicable constructors for type " + type);
-        }
-
-        return constructor;
-    }
-
     private static <T extends Enum<T>> T unpackEnum(ByteBuffer buffer, Class<T> type,
             int nativeType) {
         int ordinal = unpackSingleNative(buffer, Integer.TYPE, nativeType);
@@ -573,55 +367,11 @@
     private static <T> T unpackClass(ByteBuffer buffer, Class<T> type, int nativeType) {
 
         MetadataMarshalClass<T> marshaler = getMarshaler(type, nativeType);
-        if (marshaler != null) {
-            return marshaler.unmarshal(buffer, nativeType);
+        if (marshaler == null) {
+            throw new IllegalArgumentException("Unknown class type: " + type);
         }
 
-        /**
-         * FIXME: This doesn't actually work because getFields() returns fields in an unordered
-         * manner. Although we could sort and get the data to come out correctly on the *java* side,
-         * it would not be data-compatible with our strict XML definitions.
-         *
-         * Rewrite this code to use Parcelables instead, they are most likely compatible with
-         * what we are trying to do in general.
-         */
-
-        List<Field> instanceFields = findInstanceFields(type);
-        if (instanceFields.size() == 0) {
-            throw new UnsupportedOperationException("Class has no instance fields: " + type);
-        }
-        int fieldCount = instanceFields.size();
-
-        Constructor<T> constructor = findApplicableConstructor(type);
-
-        /**
-         * Build the arguments by unpacking one field at a time
-         * (note that while the field type might be different, the native type is the same)
-         */
-        Object[] arguments = new Object[fieldCount];
-        for (int i = 0; i < fieldCount; ++i) {
-            Object o = unpackSingle(buffer, instanceFields.get(i).getType(), nativeType);
-            arguments[i] = o;
-        }
-
-        T instance;
-        try {
-            instance = constructor.newInstance(arguments);
-        } catch (InstantiationException e) {
-            // type is abstract class, interface, etc...
-            throw new UnsupportedOperationException("Failed to instantiate type " + type, e);
-        } catch (IllegalAccessException e) {
-            // This could happen if we have to access a private.
-            throw new UnsupportedOperationException("Failed to access type " + type, e);
-        } catch (IllegalArgumentException e) {
-            throw new UnsupportedOperationException("Illegal arguments for constructor of type "
-                    + type, e);
-        } catch (InvocationTargetException e) {
-            throw new UnsupportedOperationException(
-                    "Underlying constructor threw exception for type " + type, e);
-        }
-
-        return instance;
+        return marshaler.unmarshal(buffer, nativeType);
     }
 
     @SuppressWarnings("unchecked")
@@ -1011,4 +761,1025 @@
 
         Log.v(TAG, "Registered metadata marshalers");
     }
+
+    /*@O~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~
+     * The enum values below this point are generated from metadata
+     * definitions in /system/media/camera/docs. Do not modify by hand or
+     * modify the comment blocks at the start or end.
+     *~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~*/
+
+    //
+    // Enumeration values for CameraProperties#LENS_FACING
+    //
+
+    /**
+     * @see CameraProperties#LENS_FACING
+     */
+    public static final int LENS_FACING_FRONT = 0;
+
+    /**
+     * @see CameraProperties#LENS_FACING
+     */
+    public static final int LENS_FACING_BACK = 1;
+
+    //
+    // Enumeration values for CameraProperties#LED_AVAILABLE_LEDS
+    //
+
+    /**
+     * <p>
+     * android.led.transmit control is used
+     * </p>
+     * @see CameraProperties#LED_AVAILABLE_LEDS
+     * @hide
+     */
+    public static final int LED_AVAILABLE_LEDS_TRANSMIT = 0;
+
+    //
+    // Enumeration values for CameraProperties#INFO_SUPPORTED_HARDWARE_LEVEL
+    //
+
+    /**
+     * @see CameraProperties#INFO_SUPPORTED_HARDWARE_LEVEL
+     */
+    public static final int INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED = 0;
+
+    /**
+     * @see CameraProperties#INFO_SUPPORTED_HARDWARE_LEVEL
+     */
+    public static final int INFO_SUPPORTED_HARDWARE_LEVEL_FULL = 1;
+
+    //
+    // Enumeration values for CaptureRequest#COLOR_CORRECTION_MODE
+    //
+
+    /**
+     * <p>
+     * Use the android.colorCorrection.transform matrix
+     * and android.colorCorrection.gains to do color conversion
+     * </p>
+     * @see CaptureRequest#COLOR_CORRECTION_MODE
+     */
+    public static final int COLOR_CORRECTION_MODE_TRANSFORM_MATRIX = 0;
+
+    /**
+     * <p>
+     * Must not slow down frame rate relative to raw
+     * bayer output
+     * </p>
+     * @see CaptureRequest#COLOR_CORRECTION_MODE
+     */
+    public static final int COLOR_CORRECTION_MODE_FAST = 1;
+
+    /**
+     * <p>
+     * Frame rate may be reduced by high
+     * quality
+     * </p>
+     * @see CaptureRequest#COLOR_CORRECTION_MODE
+     */
+    public static final int COLOR_CORRECTION_MODE_HIGH_QUALITY = 2;
+
+    //
+    // Enumeration values for CaptureRequest#CONTROL_AE_ANTIBANDING_MODE
+    //
+
+    /**
+     * @see CaptureRequest#CONTROL_AE_ANTIBANDING_MODE
+     */
+    public static final int CONTROL_AE_ANTIBANDING_MODE_OFF = 0;
+
+    /**
+     * @see CaptureRequest#CONTROL_AE_ANTIBANDING_MODE
+     */
+    public static final int CONTROL_AE_ANTIBANDING_MODE_50HZ = 1;
+
+    /**
+     * @see CaptureRequest#CONTROL_AE_ANTIBANDING_MODE
+     */
+    public static final int CONTROL_AE_ANTIBANDING_MODE_60HZ = 2;
+
+    /**
+     * @see CaptureRequest#CONTROL_AE_ANTIBANDING_MODE
+     */
+    public static final int CONTROL_AE_ANTIBANDING_MODE_AUTO = 3;
+
+    //
+    // Enumeration values for CaptureRequest#CONTROL_AE_MODE
+    //
+
+    /**
+     * <p>
+     * Autoexposure is disabled; sensor.exposureTime,
+     * sensor.sensitivity and sensor.frameDuration are used
+     * </p>
+     * @see CaptureRequest#CONTROL_AE_MODE
+     */
+    public static final int CONTROL_AE_MODE_OFF = 0;
+
+    /**
+     * <p>
+     * Autoexposure is active, no flash
+     * control
+     * </p>
+     * @see CaptureRequest#CONTROL_AE_MODE
+     */
+    public static final int CONTROL_AE_MODE_ON = 1;
+
+    /**
+     * <p>
+     * if flash exists Autoexposure is active, auto
+     * flash control; flash may be fired when precapture
+     * trigger is activated, and for captures for which
+     * captureIntent = STILL_CAPTURE
+     * </p>
+     * @see CaptureRequest#CONTROL_AE_MODE
+     */
+    public static final int CONTROL_AE_MODE_ON_AUTO_FLASH = 2;
+
+    /**
+     * <p>
+     * if flash exists Autoexposure is active, auto
+     * flash control for precapture trigger and always flash
+     * when captureIntent = STILL_CAPTURE
+     * </p>
+     * @see CaptureRequest#CONTROL_AE_MODE
+     */
+    public static final int CONTROL_AE_MODE_ON_ALWAYS_FLASH = 3;
+
+    /**
+     * <p>
+     * optional Automatic red eye reduction with flash.
+     * If deemed necessary, red eye reduction sequence should
+     * fire when precapture trigger is activated, and final
+     * flash should fire when captureIntent =
+     * STILL_CAPTURE
+     * </p>
+     * @see CaptureRequest#CONTROL_AE_MODE
+     */
+    public static final int CONTROL_AE_MODE_ON_AUTO_FLASH_REDEYE = 4;
+
+    //
+    // Enumeration values for CaptureRequest#CONTROL_AE_PRECAPTURE_TRIGGER
+    //
+
+    /**
+     * <p>
+     * The trigger is idle.
+     * </p>
+     * @see CaptureRequest#CONTROL_AE_PRECAPTURE_TRIGGER
+     */
+    public static final int CONTROL_AE_PRECAPTURE_TRIGGER_IDLE = 0;
+
+    /**
+     * <p>
+     * The precapture metering sequence
+     * must be started. The exact effect of the precapture
+     * trigger depends on the current AE mode and
+     * state.
+     * </p>
+     * @see CaptureRequest#CONTROL_AE_PRECAPTURE_TRIGGER
+     */
+    public static final int CONTROL_AE_PRECAPTURE_TRIGGER_START = 1;
+
+    //
+    // Enumeration values for CaptureRequest#CONTROL_AF_MODE
+    //
+
+    /**
+     * <p>
+     * The 3A routines do not control the lens;
+     * android.lens.focusDistance is controlled by the
+     * application
+     * </p>
+     * @see CaptureRequest#CONTROL_AF_MODE
+     */
+    public static final int CONTROL_AF_MODE_OFF = 0;
+
+    /**
+     * <p>
+     * if lens is not fixed focus.
+     * </p><p>
+     * Use android.lens.minimumFocusDistance to determine if lens
+     * is fixed focus In this mode, the lens does not move unless
+     * the autofocus trigger action is called. When that trigger
+     * is activated, AF must transition to ACTIVE_SCAN, then to
+     * the outcome of the scan (FOCUSED or
+     * NOT_FOCUSED).
+     * </p><p>
+     * Triggering cancel AF resets the lens position to default,
+     * and sets the AF state to INACTIVE.
+     * </p>
+     * @see CaptureRequest#CONTROL_AF_MODE
+     */
+    public static final int CONTROL_AF_MODE_AUTO = 1;
+
+    /**
+     * <p>
+     * In this mode, the lens does not move unless the
+     * autofocus trigger action is called.
+     * </p><p>
+     * When that trigger is activated, AF must transition to
+     * ACTIVE_SCAN, then to the outcome of the scan (FOCUSED or
+     * NOT_FOCUSED).  Triggering cancel AF resets the lens
+     * position to default, and sets the AF state to
+     * INACTIVE.
+     * </p>
+     * @see CaptureRequest#CONTROL_AF_MODE
+     */
+    public static final int CONTROL_AF_MODE_MACRO = 2;
+
+    /**
+     * <p>
+     * In this mode, the AF algorithm modifies the lens
+     * position continually to attempt to provide a
+     * constantly-in-focus image stream.
+     * </p><p>
+     * The focusing behavior should be suitable for good quality
+     * video recording; typically this means slower focus
+     * movement and no overshoots. When the AF trigger is not
+     * involved, the AF algorithm should start in INACTIVE state,
+     * and then transition into PASSIVE_SCAN and PASSIVE_FOCUSED
+     * states as appropriate. When the AF trigger is activated,
+     * the algorithm should immediately transition into
+     * AF_FOCUSED or AF_NOT_FOCUSED as appropriate, and lock the
+     * lens position until a cancel AF trigger is received.
+     * </p><p>
+     * Once cancel is received, the algorithm should transition
+     * back to INACTIVE and resume passive scan. Note that this
+     * behavior is not identical to CONTINUOUS_PICTURE, since an
+     * ongoing PASSIVE_SCAN must immediately be
+     * canceled.
+     * </p>
+     * @see CaptureRequest#CONTROL_AF_MODE
+     */
+    public static final int CONTROL_AF_MODE_CONTINUOUS_VIDEO = 3;
+
+    /**
+     * <p>
+     * In this mode, the AF algorithm modifies the lens
+     * position continually to attempt to provide a
+     * constantly-in-focus image stream.
+     * </p><p>
+     * The focusing behavior should be suitable for still image
+     * capture; typically this means focusing as fast as
+     * possible. When the AF trigger is not involved, the AF
+     * algorithm should start in INACTIVE state, and then
+     * transition into PASSIVE_SCAN and PASSIVE_FOCUSED states as
+     * appropriate as it attempts to maintain focus. When the AF
+     * trigger is activated, the algorithm should finish its
+     * PASSIVE_SCAN if active, and then transition into
+     * AF_FOCUSED or AF_NOT_FOCUSED as appropriate, and lock the
+     * lens position until a cancel AF trigger is received.
+     * </p><p>
+     * When the AF cancel trigger is activated, the algorithm
+     * should transition back to INACTIVE and then act as if it
+     * has just been started.
+     * </p>
+     * @see CaptureRequest#CONTROL_AF_MODE
+     */
+    public static final int CONTROL_AF_MODE_CONTINUOUS_PICTURE = 4;
+
+    /**
+     * <p>
+     * Extended depth of field (digital focus). AF
+     * trigger is ignored, AF state should always be
+     * INACTIVE.
+     * </p>
+     * @see CaptureRequest#CONTROL_AF_MODE
+     */
+    public static final int CONTROL_AF_MODE_EDOF = 5;
+
+    //
+    // Enumeration values for CaptureRequest#CONTROL_AF_TRIGGER
+    //
+
+    /**
+     * <p>
+     * The trigger is idle.
+     * </p>
+     * @see CaptureRequest#CONTROL_AF_TRIGGER
+     */
+    public static final int CONTROL_AF_TRIGGER_IDLE = 0;
+
+    /**
+     * <p>
+     * Autofocus must trigger now.
+     * </p>
+     * @see CaptureRequest#CONTROL_AF_TRIGGER
+     */
+    public static final int CONTROL_AF_TRIGGER_START = 1;
+
+    /**
+     * <p>
+     * Autofocus must return to initial
+     * state, and cancel any active trigger.
+     * </p>
+     * @see CaptureRequest#CONTROL_AF_TRIGGER
+     */
+    public static final int CONTROL_AF_TRIGGER_CANCEL = 2;
+
+    //
+    // Enumeration values for CaptureRequest#CONTROL_AWB_MODE
+    //
+
+    /**
+     * @see CaptureRequest#CONTROL_AWB_MODE
+     */
+    public static final int CONTROL_AWB_MODE_OFF = 0;
+
+    /**
+     * @see CaptureRequest#CONTROL_AWB_MODE
+     */
+    public static final int CONTROL_AWB_MODE_AUTO = 1;
+
+    /**
+     * @see CaptureRequest#CONTROL_AWB_MODE
+     */
+    public static final int CONTROL_AWB_MODE_INCANDESCENT = 2;
+
+    /**
+     * @see CaptureRequest#CONTROL_AWB_MODE
+     */
+    public static final int CONTROL_AWB_MODE_FLUORESCENT = 3;
+
+    /**
+     * @see CaptureRequest#CONTROL_AWB_MODE
+     */
+    public static final int CONTROL_AWB_MODE_WARM_FLUORESCENT = 4;
+
+    /**
+     * @see CaptureRequest#CONTROL_AWB_MODE
+     */
+    public static final int CONTROL_AWB_MODE_DAYLIGHT = 5;
+
+    /**
+     * @see CaptureRequest#CONTROL_AWB_MODE
+     */
+    public static final int CONTROL_AWB_MODE_CLOUDY_DAYLIGHT = 6;
+
+    /**
+     * @see CaptureRequest#CONTROL_AWB_MODE
+     */
+    public static final int CONTROL_AWB_MODE_TWILIGHT = 7;
+
+    /**
+     * @see CaptureRequest#CONTROL_AWB_MODE
+     */
+    public static final int CONTROL_AWB_MODE_SHADE = 8;
+
+    //
+    // Enumeration values for CaptureRequest#CONTROL_CAPTURE_INTENT
+    //
+
+    /**
+     * <p>
+     * This request doesn't fall into the other
+     * categories. Default to preview-like
+     * behavior.
+     * </p>
+     * @see CaptureRequest#CONTROL_CAPTURE_INTENT
+     */
+    public static final int CONTROL_CAPTURE_INTENT_CUSTOM = 0;
+
+    /**
+     * <p>
+     * This request is for a preview-like usecase. The
+     * precapture trigger may be used to start off a metering
+     * w/flash sequence
+     * </p>
+     * @see CaptureRequest#CONTROL_CAPTURE_INTENT
+     */
+    public static final int CONTROL_CAPTURE_INTENT_PREVIEW = 1;
+
+    /**
+     * <p>
+     * This request is for a still capture-type
+     * usecase.
+     * </p>
+     * @see CaptureRequest#CONTROL_CAPTURE_INTENT
+     */
+    public static final int CONTROL_CAPTURE_INTENT_STILL_CAPTURE = 2;
+
+    /**
+     * <p>
+     * This request is for a video recording
+     * usecase.
+     * </p>
+     * @see CaptureRequest#CONTROL_CAPTURE_INTENT
+     */
+    public static final int CONTROL_CAPTURE_INTENT_VIDEO_RECORD = 3;
+
+    /**
+     * <p>
+     * This request is for a video snapshot (still
+     * image while recording video) usecase
+     * </p>
+     * @see CaptureRequest#CONTROL_CAPTURE_INTENT
+     */
+    public static final int CONTROL_CAPTURE_INTENT_VIDEO_SNAPSHOT = 4;
+
+    /**
+     * <p>
+     * This request is for a ZSL usecase; the
+     * application will stream full-resolution images and
+     * reprocess one or several later for a final
+     * capture
+     * </p>
+     * @see CaptureRequest#CONTROL_CAPTURE_INTENT
+     */
+    public static final int CONTROL_CAPTURE_INTENT_ZERO_SHUTTER_LAG = 5;
+
+    //
+    // Enumeration values for CaptureRequest#CONTROL_EFFECT_MODE
+    //
+
+    /**
+     * @see CaptureRequest#CONTROL_EFFECT_MODE
+     */
+    public static final int CONTROL_EFFECT_MODE_OFF = 0;
+
+    /**
+     * @see CaptureRequest#CONTROL_EFFECT_MODE
+     */
+    public static final int CONTROL_EFFECT_MODE_MONO = 1;
+
+    /**
+     * @see CaptureRequest#CONTROL_EFFECT_MODE
+     */
+    public static final int CONTROL_EFFECT_MODE_NEGATIVE = 2;
+
+    /**
+     * @see CaptureRequest#CONTROL_EFFECT_MODE
+     */
+    public static final int CONTROL_EFFECT_MODE_SOLARIZE = 3;
+
+    /**
+     * @see CaptureRequest#CONTROL_EFFECT_MODE
+     */
+    public static final int CONTROL_EFFECT_MODE_SEPIA = 4;
+
+    /**
+     * @see CaptureRequest#CONTROL_EFFECT_MODE
+     */
+    public static final int CONTROL_EFFECT_MODE_POSTERIZE = 5;
+
+    /**
+     * @see CaptureRequest#CONTROL_EFFECT_MODE
+     */
+    public static final int CONTROL_EFFECT_MODE_WHITEBOARD = 6;
+
+    /**
+     * @see CaptureRequest#CONTROL_EFFECT_MODE
+     */
+    public static final int CONTROL_EFFECT_MODE_BLACKBOARD = 7;
+
+    /**
+     * @see CaptureRequest#CONTROL_EFFECT_MODE
+     */
+    public static final int CONTROL_EFFECT_MODE_AQUA = 8;
+
+    //
+    // Enumeration values for CaptureRequest#CONTROL_MODE
+    //
+
+    /**
+     * <p>
+     * Full application control of pipeline. All 3A
+     * routines are disabled, no other settings in
+     * android.control.* have any effect
+     * </p>
+     * @see CaptureRequest#CONTROL_MODE
+     */
+    public static final int CONTROL_MODE_OFF = 0;
+
+    /**
+     * <p>
+     * Use settings for each individual 3A routine.
+     * Manual control of capture parameters is disabled. All
+     * controls in android.control.* besides sceneMode take
+     * effect
+     * </p>
+     * @see CaptureRequest#CONTROL_MODE
+     */
+    public static final int CONTROL_MODE_AUTO = 1;
+
+    /**
+     * <p>
+     * Use specific scene mode. Enabling this disables
+     * control.aeMode, control.awbMode and control.afMode
+     * controls; the HAL must ignore those settings while
+     * USE_SCENE_MODE is active (except for FACE_PRIORITY
+     * scene mode). Other control entries are still active.
+     * This setting can only be used if availableSceneModes !=
+     * UNSUPPORTED
+     * </p>
+     * @see CaptureRequest#CONTROL_MODE
+     */
+    public static final int CONTROL_MODE_USE_SCENE_MODE = 2;
+
+    //
+    // Enumeration values for CaptureRequest#CONTROL_SCENE_MODE
+    //
+
+    /**
+     * @see CaptureRequest#CONTROL_SCENE_MODE
+     */
+    public static final int CONTROL_SCENE_MODE_UNSUPPORTED = 0;
+
+    /**
+     * <p>
+     * if face detection support exists Use face
+     * detection data to drive 3A routines. If face detection
+     * statistics are disabled, should still operate correctly
+     * (but not return face detection statistics to the
+     * framework).
+     * </p><p>
+     * Unlike the other scene modes, aeMode, awbMode, and afMode
+     * remain active when FACE_PRIORITY is set. This is due to
+     * compatibility concerns with the old camera
+     * API
+     * </p>
+     * @see CaptureRequest#CONTROL_SCENE_MODE
+     */
+    public static final int CONTROL_SCENE_MODE_FACE_PRIORITY = 1;
+
+    /**
+     * @see CaptureRequest#CONTROL_SCENE_MODE
+     */
+    public static final int CONTROL_SCENE_MODE_ACTION = 2;
+
+    /**
+     * @see CaptureRequest#CONTROL_SCENE_MODE
+     */
+    public static final int CONTROL_SCENE_MODE_PORTRAIT = 3;
+
+    /**
+     * @see CaptureRequest#CONTROL_SCENE_MODE
+     */
+    public static final int CONTROL_SCENE_MODE_LANDSCAPE = 4;
+
+    /**
+     * @see CaptureRequest#CONTROL_SCENE_MODE
+     */
+    public static final int CONTROL_SCENE_MODE_NIGHT = 5;
+
+    /**
+     * @see CaptureRequest#CONTROL_SCENE_MODE
+     */
+    public static final int CONTROL_SCENE_MODE_NIGHT_PORTRAIT = 6;
+
+    /**
+     * @see CaptureRequest#CONTROL_SCENE_MODE
+     */
+    public static final int CONTROL_SCENE_MODE_THEATRE = 7;
+
+    /**
+     * @see CaptureRequest#CONTROL_SCENE_MODE
+     */
+    public static final int CONTROL_SCENE_MODE_BEACH = 8;
+
+    /**
+     * @see CaptureRequest#CONTROL_SCENE_MODE
+     */
+    public static final int CONTROL_SCENE_MODE_SNOW = 9;
+
+    /**
+     * @see CaptureRequest#CONTROL_SCENE_MODE
+     */
+    public static final int CONTROL_SCENE_MODE_SUNSET = 10;
+
+    /**
+     * @see CaptureRequest#CONTROL_SCENE_MODE
+     */
+    public static final int CONTROL_SCENE_MODE_STEADYPHOTO = 11;
+
+    /**
+     * @see CaptureRequest#CONTROL_SCENE_MODE
+     */
+    public static final int CONTROL_SCENE_MODE_FIREWORKS = 12;
+
+    /**
+     * @see CaptureRequest#CONTROL_SCENE_MODE
+     */
+    public static final int CONTROL_SCENE_MODE_SPORTS = 13;
+
+    /**
+     * @see CaptureRequest#CONTROL_SCENE_MODE
+     */
+    public static final int CONTROL_SCENE_MODE_PARTY = 14;
+
+    /**
+     * @see CaptureRequest#CONTROL_SCENE_MODE
+     */
+    public static final int CONTROL_SCENE_MODE_CANDLELIGHT = 15;
+
+    /**
+     * @see CaptureRequest#CONTROL_SCENE_MODE
+     */
+    public static final int CONTROL_SCENE_MODE_BARCODE = 16;
+
+    //
+    // Enumeration values for CaptureRequest#EDGE_MODE
+    //
+
+    /**
+     * <p>
+     * No edge enhancement is applied
+     * </p>
+     * @see CaptureRequest#EDGE_MODE
+     */
+    public static final int EDGE_MODE_OFF = 0;
+
+    /**
+     * <p>
+     * Must not slow down frame rate relative to raw
+     * bayer output
+     * </p>
+     * @see CaptureRequest#EDGE_MODE
+     */
+    public static final int EDGE_MODE_FAST = 1;
+
+    /**
+     * <p>
+     * Frame rate may be reduced by high
+     * quality
+     * </p>
+     * @see CaptureRequest#EDGE_MODE
+     */
+    public static final int EDGE_MODE_HIGH_QUALITY = 2;
+
+    //
+    // Enumeration values for CaptureRequest#FLASH_MODE
+    //
+
+    /**
+     * <p>
+     * Do not fire the flash for this
+     * capture
+     * </p>
+     * @see CaptureRequest#FLASH_MODE
+     */
+    public static final int FLASH_MODE_OFF = 0;
+
+    /**
+     * <p>
+     * if android.flash.available is true Fire flash
+     * for this capture based on firingPower,
+     * firingTime.
+     * </p>
+     * @see CaptureRequest#FLASH_MODE
+     */
+    public static final int FLASH_MODE_SINGLE = 1;
+
+    /**
+     * <p>
+     * if android.flash.available is true Flash
+     * continuously on, power set by
+     * firingPower
+     * </p>
+     * @see CaptureRequest#FLASH_MODE
+     */
+    public static final int FLASH_MODE_TORCH = 2;
+
+    //
+    // Enumeration values for CaptureRequest#LENS_OPTICAL_STABILIZATION_MODE
+    //
+
+    /**
+     * @see CaptureRequest#LENS_OPTICAL_STABILIZATION_MODE
+     */
+    public static final int LENS_OPTICAL_STABILIZATION_MODE_OFF = 0;
+
+    /**
+     * @see CaptureRequest#LENS_OPTICAL_STABILIZATION_MODE
+     */
+    public static final int LENS_OPTICAL_STABILIZATION_MODE_ON = 1;
+
+    //
+    // Enumeration values for CaptureRequest#NOISE_REDUCTION_MODE
+    //
+
+    /**
+     * <p>
+     * No noise reduction is applied
+     * </p>
+     * @see CaptureRequest#NOISE_REDUCTION_MODE
+     */
+    public static final int NOISE_REDUCTION_MODE_OFF = 0;
+
+    /**
+     * <p>
+     * Must not slow down frame rate relative to raw
+     * bayer output
+     * </p>
+     * @see CaptureRequest#NOISE_REDUCTION_MODE
+     */
+    public static final int NOISE_REDUCTION_MODE_FAST = 1;
+
+    /**
+     * <p>
+     * May slow down frame rate to provide highest
+     * quality
+     * </p>
+     * @see CaptureRequest#NOISE_REDUCTION_MODE
+     */
+    public static final int NOISE_REDUCTION_MODE_HIGH_QUALITY = 2;
+
+    //
+    // Enumeration values for CaptureRequest#STATISTICS_FACE_DETECT_MODE
+    //
+
+    /**
+     * @see CaptureRequest#STATISTICS_FACE_DETECT_MODE
+     */
+    public static final int STATISTICS_FACE_DETECT_MODE_OFF = 0;
+
+    /**
+     * <p>
+     * Optional Return rectangle and confidence
+     * only
+     * </p>
+     * @see CaptureRequest#STATISTICS_FACE_DETECT_MODE
+     */
+    public static final int STATISTICS_FACE_DETECT_MODE_SIMPLE = 1;
+
+    /**
+     * <p>
+     * Optional Return all face
+     * metadata
+     * </p>
+     * @see CaptureRequest#STATISTICS_FACE_DETECT_MODE
+     */
+    public static final int STATISTICS_FACE_DETECT_MODE_FULL = 2;
+
+    //
+    // Enumeration values for CaptureRequest#TONEMAP_MODE
+    //
+
+    /**
+     * <p>
+     * Use the tone mapping curve specified in
+     * android.tonemap.curve
+     * </p>
+     * @see CaptureRequest#TONEMAP_MODE
+     */
+    public static final int TONEMAP_MODE_CONTRAST_CURVE = 0;
+
+    /**
+     * <p>
+     * Must not slow down frame rate relative to raw
+     * bayer output
+     * </p>
+     * @see CaptureRequest#TONEMAP_MODE
+     */
+    public static final int TONEMAP_MODE_FAST = 1;
+
+    /**
+     * <p>
+     * Frame rate may be reduced by high
+     * quality
+     * </p>
+     * @see CaptureRequest#TONEMAP_MODE
+     */
+    public static final int TONEMAP_MODE_HIGH_QUALITY = 2;
+
+    //
+    // Enumeration values for CaptureResult#CONTROL_AE_STATE
+    //
+
+    /**
+     * <p>
+     * AE is off.  When a camera device is opened, it starts in
+     * this state.
+     * </p>
+     * @see CaptureResult#CONTROL_AE_STATE
+     */
+    public static final int CONTROL_AE_STATE_INACTIVE = 0;
+
+    /**
+     * <p>
+     * AE doesn't yet have a good set of control values
+     * for the current scene
+     * </p>
+     * @see CaptureResult#CONTROL_AE_STATE
+     */
+    public static final int CONTROL_AE_STATE_SEARCHING = 1;
+
+    /**
+     * <p>
+     * AE has a good set of control values for the
+     * current scene
+     * </p>
+     * @see CaptureResult#CONTROL_AE_STATE
+     */
+    public static final int CONTROL_AE_STATE_CONVERGED = 2;
+
+    /**
+     * <p>
+     * AE has been locked (aeMode =
+     * LOCKED)
+     * </p>
+     * @see CaptureResult#CONTROL_AE_STATE
+     */
+    public static final int CONTROL_AE_STATE_LOCKED = 3;
+
+    /**
+     * <p>
+     * AE has a good set of control values, but flash
+     * needs to be fired for good quality still
+     * capture
+     * </p>
+     * @see CaptureResult#CONTROL_AE_STATE
+     */
+    public static final int CONTROL_AE_STATE_FLASH_REQUIRED = 4;
+
+    /**
+     * <p>
+     * AE has been asked to do a precapture sequence
+     * (through the
+     * trigger_action(CAMERA2_TRIGGER_PRECAPTURE_METERING)
+     * call), and is currently executing it. Once PRECAPTURE
+     * completes, AE will transition to CONVERGED or
+     * FLASH_REQUIRED as appropriate
+     * </p>
+     * @see CaptureResult#CONTROL_AE_STATE
+     */
+    public static final int CONTROL_AE_STATE_PRECAPTURE = 5;
+
+    //
+    // Enumeration values for CaptureResult#CONTROL_AF_STATE
+    //
+
+    /**
+     * <p>
+     * AF off or has not yet tried to scan/been asked
+     * to scan.  When a camera device is opened, it starts in
+     * this state.
+     * </p>
+     * @see CaptureResult#CONTROL_AF_STATE
+     */
+    public static final int CONTROL_AF_STATE_INACTIVE = 0;
+
+    /**
+     * <p>
+     * if CONTINUOUS_* modes are supported AF is
+     * currently doing an AF scan initiated by a continuous
+     * autofocus mode
+     * </p>
+     * @see CaptureResult#CONTROL_AF_STATE
+     */
+    public static final int CONTROL_AF_STATE_PASSIVE_SCAN = 1;
+
+    /**
+     * <p>
+     * if CONTINUOUS_* modes are supported AF currently
+     * believes it is in focus, but may restart scanning at
+     * any time.
+     * </p>
+     * @see CaptureResult#CONTROL_AF_STATE
+     */
+    public static final int CONTROL_AF_STATE_PASSIVE_FOCUSED = 2;
+
+    /**
+     * <p>
+     * if AUTO or MACRO modes are supported AF is doing
+     * an AF scan because it was triggered by AF
+     * trigger
+     * </p>
+     * @see CaptureResult#CONTROL_AF_STATE
+     */
+    public static final int CONTROL_AF_STATE_ACTIVE_SCAN = 3;
+
+    /**
+     * <p>
+     * if any AF mode besides OFF is supported AF
+     * believes it is focused correctly and is
+     * locked
+     * </p>
+     * @see CaptureResult#CONTROL_AF_STATE
+     */
+    public static final int CONTROL_AF_STATE_FOCUSED_LOCKED = 4;
+
+    /**
+     * <p>
+     * if any AF mode besides OFF is supported AF has
+     * failed to focus successfully and is
+     * locked
+     * </p>
+     * @see CaptureResult#CONTROL_AF_STATE
+     */
+    public static final int CONTROL_AF_STATE_NOT_FOCUSED_LOCKED = 5;
+
+    //
+    // Enumeration values for CaptureResult#CONTROL_AWB_STATE
+    //
+
+    /**
+     * <p>
+     * AWB is not in auto mode.  When a camera device is opened, it
+     * starts in this state.
+     * </p>
+     * @see CaptureResult#CONTROL_AWB_STATE
+     */
+    public static final int CONTROL_AWB_STATE_INACTIVE = 0;
+
+    /**
+     * <p>
+     * AWB doesn't yet have a good set of control
+     * values for the current scene
+     * </p>
+     * @see CaptureResult#CONTROL_AWB_STATE
+     */
+    public static final int CONTROL_AWB_STATE_SEARCHING = 1;
+
+    /**
+     * <p>
+     * AWB has a good set of control values for the
+     * current scene
+     * </p>
+     * @see CaptureResult#CONTROL_AWB_STATE
+     */
+    public static final int CONTROL_AWB_STATE_CONVERGED = 2;
+
+    /**
+     * <p>
+     * AE has been locked (aeMode =
+     * LOCKED)
+     * </p>
+     * @see CaptureResult#CONTROL_AWB_STATE
+     */
+    public static final int CONTROL_AWB_STATE_LOCKED = 3;
+
+    //
+    // Enumeration values for CaptureResult#FLASH_STATE
+    //
+
+    /**
+     * <p>
+     * No flash on camera
+     * </p>
+     * @see CaptureResult#FLASH_STATE
+     */
+    public static final int FLASH_STATE_UNAVAILABLE = 0;
+
+    /**
+     * <p>
+     * if android.flash.available is true Flash is
+     * charging and cannot be fired
+     * </p>
+     * @see CaptureResult#FLASH_STATE
+     */
+    public static final int FLASH_STATE_CHARGING = 1;
+
+    /**
+     * <p>
+     * if android.flash.available is true Flash is
+     * ready to fire
+     * </p>
+     * @see CaptureResult#FLASH_STATE
+     */
+    public static final int FLASH_STATE_READY = 2;
+
+    /**
+     * <p>
+     * if android.flash.available is true Flash fired
+     * for this capture
+     * </p>
+     * @see CaptureResult#FLASH_STATE
+     */
+    public static final int FLASH_STATE_FIRED = 3;
+
+    //
+    // Enumeration values for CaptureResult#LENS_STATE
+    //
+
+    /**
+     * @see CaptureResult#LENS_STATE
+     */
+    public static final int LENS_STATE_STATIONARY = 0;
+
+    //
+    // Enumeration values for CaptureResult#STATISTICS_SCENE_FLICKER
+    //
+
+    /**
+     * @see CaptureResult#STATISTICS_SCENE_FLICKER
+     */
+    public static final int STATISTICS_SCENE_FLICKER_NONE = 0;
+
+    /**
+     * @see CaptureResult#STATISTICS_SCENE_FLICKER
+     */
+    public static final int STATISTICS_SCENE_FLICKER_50HZ = 1;
+
+    /**
+     * @see CaptureResult#STATISTICS_SCENE_FLICKER
+     */
+    public static final int STATISTICS_SCENE_FLICKER_60HZ = 2;
+
+    /*~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~
+     * End generated code
+     *~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~O@*/
+
 }
diff --git a/core/java/android/hardware/camera2/CameraProperties.java b/core/java/android/hardware/camera2/CameraProperties.java
index 89e1f2a..e713d21 100644
--- a/core/java/android/hardware/camera2/CameraProperties.java
+++ b/core/java/android/hardware/camera2/CameraProperties.java
@@ -32,216 +32,466 @@
  * @see CameraManager
  */
 public final class CameraProperties extends CameraMetadata {
-    /**
-     * The model name of the camera. For fixed (non-removable) cameras, this is
-     * the manufacturer's name. For removable cameras, this is a string that
-     * uniquely identifies the camera model and manufacturer. The
-     * {@link #INFO_IDENTIFIER} can be used to distinguish between multiple
-     * removable cameras of the same model.
-     */
-    public static final Key<String> INFO_MODEL =
-            new Key<String>("android.info.model", String.class);
+
+    /*@O~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~
+     * The key entries below this point are generated from metadata
+     * definitions in /system/media/camera/docs. Do not modify by hand or
+     * modify the comment blocks at the start or end.
+     *~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~*/
 
     /**
-     * A unique identifier for this camera. For removable cameras, every
-     * camera will have a unique identifier, including two cameras of the
-     * same model and manufacturer. For non-removable cameras, the
-     * identifier is equal to the the device's id.
+     * <p>
+     * Which set of antibanding modes are
+     * supported
+     * </p>
      */
-    public static final Key<String> INFO_IDENTIFIER =
-            new Key<String>("android.info.identifier", String.class);
+    public static final Key<byte[]> CONTROL_AE_AVAILABLE_ANTIBANDING_MODES =
+            new Key<byte[]>("android.control.aeAvailableAntibandingModes", byte[].class);
 
     /**
-     * <p>Whether this camera is removable or not.</p>
-     *
-     * <p>Applications using a removable camera must be prepared for the camera
-     * to be disconnected during use. Use the {@link #INFO_IDENTIFIER} field to
-     * determine if this camera is a match for a camera device seen earlier.</p>
+     * <p>
+     * List of frame rate ranges supported by the
+     * AE algorithm/hardware
+     * </p>
      */
-    public static final Key<Boolean> INFO_REMOVABLE =
-            new Key<Boolean>("android.info.isRemovable", Boolean.TYPE);
+    public static final Key<int[]> CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES =
+            new Key<int[]>("android.control.aeAvailableTargetFpsRanges", int[].class);
 
     /**
-     * <p>The hardware operational model of this device. One of the
-     * INFO_SUPPORTED_HARDWARE_LEVEL_* constants.</p>
-     *
-     * <p>Limited-capability devices have a number of limitations relative to
-     * full-capability cameras. Roughly, they have capabilities comparable to
-     * those provided by the deprecated {@link android.hardware.Camera}
-     * class.</p>
-     *
-     * <p>Specifically, limited-mode devices:</p>
-     *
-     * <ol>
-     *
-     *  <li>Do not provide per-frame result metadata for repeating
-     *  captures. This means that a CaptureListener will not be called for
-     *  captures done through {@link CameraDevice#setRepeatingRequest
-     *  setRepeatingRequest} or {@link CameraDevice#setRepeatingBurst
-     *  setRepeatingBurst}.</li>
-     *
-     *  <li>Do not support complete result metadata. Only a few fields are
-     *  provided, such as the timestamp (TODO).</li>
-     *
-     *  <li>Do not support manual capture controls. Only the (TODO)
-     *  ANDROID_CONTROL_* fields and TODO controls are used, and the various
-     *  AE/AF/AWB_OFF control values cannot be used.</li>
-     *
-     *  <li>Do not support high frame rate captures. To obtain high frame rate,
-     *  the {@link CameraDevice#setRepeatingRequest setRepeatingRequest} method
-     *  must be used. The {@link CameraDevice#capture capture},
-     *  {@link CameraDevice#captureBurst captureBurst}, and
-     *  {@link CameraDevice#setRepeatingBurst setRepeatingBurst} methods will
-     *  result in slow frame captures.</li>
-     *
-     * </ol>
-     *
-     * @see #INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED
-     * @see #INFO_SUPPORTED_HARDWARE_LEVEL_FULL
+     * <p>
+     * Maximum and minimum exposure compensation
+     * setting, in counts of
+     * android.control.aeCompensationStepSize
+     * </p>
      */
-    public static final Key<Integer> INFO_SUPPORTED_HARDWARE_LEVEL =
-            new Key<Integer>("android.info.supportedHardwareLevel", Integer.TYPE);
+    public static final Key<int[]> CONTROL_AE_COMPENSATION_RANGE =
+            new Key<int[]>("android.control.aeCompensationRange", int[].class);
 
     /**
-     * <p>The type reported by limited-capability camera devices.</p>
-     *
-     * <p>Limited-capability devices have a number of limitations relative to
-     * full-capability cameras. Roughly, they have capabilities comparable to
-     * those provided by the deprecated {@link android.hardware.Camera}
-     * class.</p>
-     *
-     * <p>Specifically, limited-mode devices:</p>
-     *
-     * <ol>
-     *
-     *  <li>Do not provide per-frame result metadata for repeating
-     *  captures. This means that a CaptureListener will not be called for
-     *  captures done through {@link CameraDevice#setRepeatingRequest
-     *  setRepeatingRequest} or {@link CameraDevice#setRepeatingBurst
-     *  setRepeatingBurst}.</li>
-     *
-     *  <li>Do not support complete result metadata. Only a few fields are
-     *  provided, such as the timestamp (TODO).</li>
-     *
-     *  <li>Do not support manual capture controls. Only the (TODO)
-     *  ANDROID_CONTROL_* fields and TODO controls are used, and the various
-     *  AE/AF/AWB_OFF control values cannot be used.</li>
-     *
-     *  <li>Do not support high frame rate captures. To obtain high frame rate,
-     *  the {@link CameraDevice#setRepeatingRequest setRepeatingRequest} method
-     *  must be used. The {@link CameraDevice#capture capture},
-     *  {@link CameraDevice#captureBurst captureBurst}, and
-     *  {@link CameraDevice#setRepeatingBurst setRepeatingBurst} methods will
-     *  result in slow frame captures.</li>
-     *
-     * </ol>
-     *
-     * @see #INFO_SUPPORTED_HARDWARE_LEVEL
+     * <p>
+     * Smallest step by which exposure compensation
+     * can be changed
+     * </p>
      */
-    public static final int INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED = 0;
+    public static final Key<Rational> CONTROL_AE_COMPENSATION_STEP =
+            new Key<Rational>("android.control.aeCompensationStep", Rational.class);
 
     /**
-     * <p>The type reported by full-capability camera devices</p>
-     *
-     * <p>Full-capability devices allow for per-frame control of capture
-     * hardware and post-processing parameters at high frame rates. They also
-     * provide output data at high resolution in uncompressed formats, in
-     * addition to compressed JPEG output.</p>
-     *
-     * @see #INFO_SUPPORTED_HARDWARE_LEVEL
+     * <p>
+     * List of AF modes that can be
+     * selected
+     * </p>
      */
-    public static final int INFO_SUPPORTED_HARDWARE_LEVEL_FULL = 1;
+    public static final Key<byte[]> CONTROL_AF_AVAILABLE_MODES =
+            new Key<byte[]>("android.control.afAvailableModes", byte[].class);
 
     /**
-     * <p>The available output formats from this camera device. When using a
-     * {@link android.media.ImageReader} as an output target, the
-     * ImageReader must be configured to use one of these formats.</p>
-     *
-     * <p>The list is a subset of the formats defined in
-     * {@link android.graphics.ImageFormat}.</p>
-     *
-     * <p>The image formats {@link android.graphics.ImageFormat#JPEG},
-     * {@link android.graphics.ImageFormat#YUV_420_888} are guaranteed to be
-     * supported.</p>
+     * <p>
+     * what subset of the full color effect enum
+     * list is supported
+     * </p>
+     */
+    public static final Key<byte[]> CONTROL_AVAILABLE_EFFECTS =
+            new Key<byte[]>("android.control.availableEffects", byte[].class);
+
+    /**
+     * <p>
+     * what subset of the scene mode enum list is
+     * supported.
+     * </p>
+     */
+    public static final Key<byte[]> CONTROL_AVAILABLE_SCENE_MODES =
+            new Key<byte[]>("android.control.availableSceneModes", byte[].class);
+
+    /**
+     * <p>
+     * List of video stabilization modes that can
+     * be supported
+     * </p>
+     */
+    public static final Key<byte[]> CONTROL_AVAILABLE_VIDEO_STABILIZATION_MODES =
+            new Key<byte[]>("android.control.availableVideoStabilizationModes", byte[].class);
+
+    /**
+     */
+    public static final Key<byte[]> CONTROL_AWB_AVAILABLE_MODES =
+            new Key<byte[]>("android.control.awbAvailableModes", byte[].class);
+
+    /**
+     * <p>
+     * For AE, AWB, and AF, how many individual
+     * regions can be listed for metering?
+     * </p>
+     */
+    public static final Key<Integer> CONTROL_MAX_REGIONS =
+            new Key<Integer>("android.control.maxRegions", int.class);
+
+    /**
+     * <p>
+     * Whether this camera has a
+     * flash
+     * </p>
+     * <p>
+     * If no flash, none of the flash controls do
+     * anything. All other metadata should return 0
+     * </p>
+     */
+    public static final Key<Byte> FLASH_INFO_AVAILABLE =
+            new Key<Byte>("android.flash.info.available", byte.class);
+
+    /**
+     * <p>
+     * Supported resolutions for the JPEG
+     * thumbnail
+     * </p>
+     */
+    public static final Key<android.hardware.camera2.Size[]> JPEG_AVAILABLE_THUMBNAIL_SIZES =
+            new Key<android.hardware.camera2.Size[]>("android.jpeg.availableThumbnailSizes", android.hardware.camera2.Size[].class);
+
+    /**
+     * <p>
+     * List of supported aperture
+     * values
+     * </p>
+     * <p>
+     * If variable aperture not available, only setting
+     * should be for the fixed aperture
+     * </p>
+     */
+    public static final Key<float[]> LENS_INFO_AVAILABLE_APERTURES =
+            new Key<float[]>("android.lens.info.availableApertures", float[].class);
+
+    /**
+     * <p>
+     * List of supported ND filter
+     * values
+     * </p>
+     * <p>
+     * If not available, only setting is 0. Otherwise,
+     * lists the available exposure index values for dimming
+     * (2 would mean the filter is set to reduce incoming
+     * light by two stops)
+     * </p>
+     */
+    public static final Key<float[]> LENS_INFO_AVAILABLE_FILTER_DENSITIES =
+            new Key<float[]>("android.lens.info.availableFilterDensities", float[].class);
+
+    /**
+     * <p>
+     * If fitted with optical zoom, what focal
+     * lengths are available. If not, the static focal
+     * length
+     * </p>
+     * <p>
+     * If optical zoom not supported, only one value
+     * should be reported
+     * </p>
+     */
+    public static final Key<float[]> LENS_INFO_AVAILABLE_FOCAL_LENGTHS =
+            new Key<float[]>("android.lens.info.availableFocalLengths", float[].class);
+
+    /**
+     * <p>
+     * List of supported optical image
+     * stabilization modes
+     * </p>
+     */
+    public static final Key<byte[]> LENS_INFO_AVAILABLE_OPTICAL_STABILIZATION =
+            new Key<byte[]>("android.lens.info.availableOpticalStabilization", byte[].class);
+
+    /**
+     * <p>
+     * Hyperfocal distance for this lens; set to
+     * 0 if fixed focus
+     * </p>
+     * <p>
+     * The hyperfocal distance is used for the old
+     * API's 'fixed' setting
+     * </p>
+     */
+    public static final Key<Float> LENS_INFO_HYPERFOCAL_DISTANCE =
+            new Key<Float>("android.lens.info.hyperfocalDistance", float.class);
+
+    /**
+     * <p>
+     * Shortest distance from frontmost surface
+     * of the lens that can be focused correctly
+     * </p>
+     * <p>
+     * If the lens is fixed-focus, this should be
+     * 0
+     * </p>
+     */
+    public static final Key<Float> LENS_INFO_MINIMUM_FOCUS_DISTANCE =
+            new Key<Float>("android.lens.info.minimumFocusDistance", float.class);
+
+    /**
+     * <p>
+     * Dimensions of lens shading
+     * map
+     * </p>
+     */
+    public static final Key<android.hardware.camera2.Size> LENS_INFO_SHADING_MAP_SIZE =
+            new Key<android.hardware.camera2.Size>("android.lens.info.shadingMapSize", android.hardware.camera2.Size.class);
+
+    /**
+     * <p>
+     * Direction the camera faces relative to
+     * device screen
+     * </p>
+     * @see #LENS_FACING_FRONT
+     * @see #LENS_FACING_BACK
+     */
+    public static final Key<Integer> LENS_FACING =
+            new Key<Integer>("android.lens.facing", int.class);
+
+    /**
+     * <p>
+     * How many output streams can be allocated at
+     * the same time for each type of stream
+     * </p>
+     * <p>
+     * Video snapshot with preview callbacks requires 3
+     * processed streams (preview, record, app callbacks) and
+     * one JPEG stream (snapshot)
+     * </p>
+     */
+    public static final Key<int[]> REQUEST_MAX_NUM_OUTPUT_STREAMS =
+            new Key<int[]>("android.request.maxNumOutputStreams", int[].class);
+
+    /**
+     * <p>
+     * List of app-visible formats
+     * </p>
      */
     public static final Key<int[]> SCALER_AVAILABLE_FORMATS =
             new Key<int[]>("android.scaler.availableFormats", int[].class);
 
     /**
-     * <p>The available output sizes for JPEG buffers from this camera
-     * device. When using a {@link android.media.ImageReader} as an output
-     * target, the ImageReader must be configured to use one of these sizes
-     * when using format {@link android.graphics.ImageFormat#JPEG}.</p>
+     * <p>
+     * The minimum frame duration that is supported
+     * for each resolution in availableJpegSizes. Should
+     * correspond to the frame duration when only that JPEG
+     * stream is active and captured in a burst, with all
+     * processing set to FAST
+     * </p>
+     * <p>
+     * When multiple streams are configured, the minimum
+     * frame duration will be >= max(individual stream min
+     * durations)
+     * </p>
      */
-    public static final Key<Size[]> SCALER_AVAILABLE_JPEG_SIZES =
-            new Key<Size[]>("android.scaler.availableJpegSizes", Size[].class);
+    public static final Key<long[]> SCALER_AVAILABLE_JPEG_MIN_DURATIONS =
+            new Key<long[]>("android.scaler.availableJpegMinDurations", long[].class);
 
     /**
-     * <p>The available sizes for output buffers from this camera device, when
-     * the buffers are neither of the {@link android.graphics.ImageFormat#JPEG}
-     * or of the {@link android.graphics.ImageFormat#RAW_SENSOR} type.</p>
-     *
-     * <p>When using a {@link android.view.SurfaceView},
-     * {@link android.graphics.SurfaceTexture},
-     * {@link android.media.MediaRecorder}, {@link android.media.MediaCodec}, or
-     * {@link android.renderscript.Allocation} as an output target, that target
-     * must be configured to one of these sizes. See
-     * {@link CameraDevice#configureOutputs} for details.
-     *
-     * <p>When using a {@link android.media.ImageReader} as an output
-     * target, the ImageReader must be configured to use one of these sizes
-     * when using format {@link android.graphics.ImageFormat#YUV_420_888}.</p>
-     *
+     * <p>
+     * The resolutions available for output from
+     * the JPEG block. Listed as width x height
+     * </p>
      */
-    public static final Key<Size[]> SCALER_AVAILABLE_PROCESSED_SIZES =
-            new Key<Size[]>("android.scaler.availableProcessedSizes", Size[].class);
+    public static final Key<android.hardware.camera2.Size[]> SCALER_AVAILABLE_JPEG_SIZES =
+            new Key<android.hardware.camera2.Size[]>("android.scaler.availableJpegSizes", android.hardware.camera2.Size[].class);
 
     /**
-     * <p>The available sizes for output buffers from this camera device, when
-     * the buffers are of the {@link android.graphics.ImageFormat#RAW_SENSOR} type. This type of output may not be
-     * supported by the device; check {@link #SCALER_AVAILABLE_FORMATS} to
-     * check. In that case, this list will not exist.</p>
-     *
-     * <p>When using a {@link android.media.ImageReader} as an output
-     * target, the ImageReader must be configured to use one of these sizes
-     * when using image format {@link android.graphics.ImageFormat#RAW_SENSOR}.</p>
+     * <p>
+     * The maximum ratio between active area width
+     * and crop region width, or between active area height and
+     * crop region height, if the crop region height is larger
+     * than width
+     * </p>
      */
-    public static final Key<Size[]> SCALER_AVAILABLE_RAW_SIZES =
-            new Key<Size[]>("android.scaler.availableRawSizes", Size[].class);
+    public static final Key<Float> SCALER_AVAILABLE_MAX_DIGITAL_ZOOM =
+            new Key<Float>("android.scaler.availableMaxDigitalZoom", float.class);
 
     /**
-     * <p>The coordinates of the sensor's active pixel array, relative to its
-     * total pixel array. These are the pixels that are actually used for image
-     * capture. The active pixel region may be smaller than the total number of
-     * pixels, if some pixels are used for other tasks such as calibrating the
-     * sensor's black level. If all pixels available for readout are used for
-     * imaging, then this rectangle will be
-     * {@code (0,0) - (SENSOR_PIXEL_ARRAY_SIZE.width,
-     * SENSOR_PIXEL_ARRAY_SIZE.height)}.</p>
-     *
-     * <p>If raw sensor capture is supported by this device, the width and
-     * height of the active pixel array match up to one of the supported raw
-     * capture sizes, and using that size will capture just the active pixel
-     * array region.</p>
-     *
-     * <p>Most other coordinates used by the camera device (for example, for
-     * metering and crop region selection, or for reporting detected faces) use
-     * a coordinate system based on the active array dimensions, with (0,0)
-     * being the top-left corner of the active array.</p>
+     * <p>
+     * The minimum frame duration that is supported
+     * for each resolution in availableProcessedSizes. Should
+     * correspond to the frame duration when only that processed
+     * stream is active, with all processing set to
+     * FAST
+     * </p>
+     * <p>
+     * When multiple streams are configured, the minimum
+     * frame duration will be >= max(individual stream min
+     * durations)
+     * </p>
      */
-    public static final Key<Rect> SENSOR_ACTIVE_ARRAY_SIZE =
-            new Key<Rect>("android.sensor.activeArraySize", Rect.class);
+    public static final Key<long[]> SCALER_AVAILABLE_PROCESSED_MIN_DURATIONS =
+            new Key<long[]>("android.scaler.availableProcessedMinDurations", long[].class);
 
     /**
-     * <p>The size of the sensor's total pixel array available for readout. Some
-     * of these pixels may not be used for image capture, in which case
-     * {@link #SENSOR_ACTIVE_ARRAY_SIZE} will describe a rectangle smaller than
-     * this. If raw sensor capture is supported by this device, this is one of
-     * the supported capture sizes.</p>
+     * <p>
+     * The resolutions available for use with
+     * processed output streams, such as YV12, NV12, and
+     * platform opaque YUV/RGB streams to the GPU or video
+     * encoders. Listed as width, height
+     * </p>
      */
-    public static final Key<Size> SENSOR_PIXEL_ARRAY_SIZE =
-            new Key<Size>("android.sensor.activeArraySize", Size.class);
+    public static final Key<android.hardware.camera2.Size[]> SCALER_AVAILABLE_PROCESSED_SIZES =
+            new Key<android.hardware.camera2.Size[]>("android.scaler.availableProcessedSizes", android.hardware.camera2.Size[].class);
 
-    // TODO: Many more of these.
+    /**
+     * <p>
+     * Area of raw data which corresponds to only
+     * active pixels; smaller or equal to
+     * pixelArraySize.
+     * </p>
+     */
+    public static final Key<android.graphics.Rect> SENSOR_INFO_ACTIVE_ARRAY_SIZE =
+            new Key<android.graphics.Rect>("android.sensor.info.activeArraySize", android.graphics.Rect.class);
 
+    /**
+     * <p>
+     * Range of valid sensitivities
+     * </p>
+     */
+    public static final Key<int[]> SENSOR_INFO_SENSITIVITY_RANGE =
+            new Key<int[]>("android.sensor.info.sensitivityRange", int[].class);
+
+    /**
+     * <p>
+     * Range of valid exposure
+     * times
+     * </p>
+     */
+    public static final Key<long[]> SENSOR_INFO_EXPOSURE_TIME_RANGE =
+            new Key<long[]>("android.sensor.info.exposureTimeRange", long[].class);
+
+    /**
+     * <p>
+     * Maximum possible frame duration (minimum frame
+     * rate)
+     * </p>
+     * <p>
+     * Minimum duration is a function of resolution,
+     * processing settings. See
+     * android.scaler.availableProcessedMinDurations
+     * android.scaler.availableJpegMinDurations
+     * android.scaler.availableRawMinDurations
+     * </p>
+     */
+    public static final Key<Long> SENSOR_INFO_MAX_FRAME_DURATION =
+            new Key<Long>("android.sensor.info.maxFrameDuration", long.class);
+
+    /**
+     * <p>
+     * The physical dimensions of the full pixel
+     * array
+     * </p>
+     * <p>
+     * Needed for FOV calculation for old API
+     * </p>
+     */
+    public static final Key<android.hardware.camera2.Size> SENSOR_INFO_PHYSICAL_SIZE =
+            new Key<android.hardware.camera2.Size>("android.sensor.info.physicalSize", android.hardware.camera2.Size.class);
+
+    /**
+     * <p>
+     * Gain factor from electrons to raw units when
+     * ISO=100
+     * </p>
+     */
+    public static final Key<Rational> SENSOR_BASE_GAIN_FACTOR =
+            new Key<Rational>("android.sensor.baseGainFactor", Rational.class);
+
+    /**
+     * <p>
+     * Maximum sensitivity that is implemented
+     * purely through analog gain
+     * </p>
+     * <p>
+     * For android.sensor.sensitivity values less than or
+     * equal to this, all applied gain must be analog. For
+     * values above this, it can be a mix of analog and
+     * digital
+     * </p>
+     */
+    public static final Key<Integer> SENSOR_MAX_ANALOG_SENSITIVITY =
+            new Key<Integer>("android.sensor.maxAnalogSensitivity", int.class);
+
+    /**
+     * <p>
+     * Clockwise angle through which the output
+     * image needs to be rotated to be upright on the device
+     * screen in its native orientation. Also defines the
+     * direction of rolling shutter readout, which is from top
+     * to bottom in the sensor's coordinate system
+     * </p>
+     */
+    public static final Key<Integer> SENSOR_ORIENTATION =
+            new Key<Integer>("android.sensor.orientation", int.class);
+
+    /**
+     * <p>
+     * Which face detection modes are available,
+     * if any
+     * </p>
+     * <p>
+     * OFF means face detection is disabled, it must
+     * be included in the list.
+     * </p><p>
+     * SIMPLE means the device supports the
+     * android.statistics.faceRectangles and
+     * android.statistics.faceScores outputs.
+     * </p><p>
+     * FULL means the device additionally supports the
+     * android.statistics.faceIds and
+     * android.statistics.faceLandmarks outputs.
+     * </p>
+     */
+    public static final Key<byte[]> STATISTICS_INFO_AVAILABLE_FACE_DETECT_MODES =
+            new Key<byte[]>("android.statistics.info.availableFaceDetectModes", byte[].class);
+
+    /**
+     * <p>
+     * Maximum number of simultaneously detectable
+     * faces
+     * </p>
+     */
+    public static final Key<Integer> STATISTICS_INFO_MAX_FACE_COUNT =
+            new Key<Integer>("android.statistics.info.maxFaceCount", int.class);
+
+    /**
+     * <p>
+     * Maximum number of supported points in the
+     * tonemap curve
+     * </p>
+     */
+    public static final Key<Integer> TONEMAP_MAX_CURVE_POINTS =
+            new Key<Integer>("android.tonemap.maxCurvePoints", int.class);
+
+    /**
+     * <p>
+     * A list of camera LEDs that are available on this system.
+     * </p>
+     * @see #LED_AVAILABLE_LEDS_TRANSMIT
+     *
+     * @hide
+     */
+    public static final Key<int[]> LED_AVAILABLE_LEDS =
+            new Key<int[]>("android.led.availableLeds", int[].class);
+
+    /**
+     * <p>
+     * The camera 3 HAL device can implement one of two possible
+     * operational modes; limited and full. Full support is
+     * expected from new higher-end devices. Limited mode has
+     * hardware requirements roughly in line with those for a
+     * camera HAL device v1 implementation, and is expected from
+     * older or inexpensive devices. Full is a strict superset of
+     * limited, and they share the same essential operational flow.
+     * </p><p>
+     * For full details refer to "S3. Operational Modes" in camera3.h
+     * </p>
+     * @see #INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED
+     * @see #INFO_SUPPORTED_HARDWARE_LEVEL_FULL
+     */
+    public static final Key<Integer> INFO_SUPPORTED_HARDWARE_LEVEL =
+            new Key<Integer>("android.info.supportedHardwareLevel", int.class);
+
+    /*~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~
+     * End generated code
+     *~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~O@*/
 }
diff --git a/core/java/android/hardware/camera2/CaptureRequest.java b/core/java/android/hardware/camera2/CaptureRequest.java
index 15ba12c..1a10bdd 100644
--- a/core/java/android/hardware/camera2/CaptureRequest.java
+++ b/core/java/android/hardware/camera2/CaptureRequest.java
@@ -55,21 +55,6 @@
     private final HashSet<Surface> mSurfaceSet = new HashSet<Surface>();
 
     /**
-     * The exposure time for this capture, in nanoseconds.
-     */
-    public static final Key<Long> SENSOR_EXPOSURE_TIME =
-            new Key<Long>("android.sensor.exposureTime", Long.TYPE);
-
-    /**
-     * The sensor sensitivity (gain) setting for this camera.
-     * This is represented as an ISO sensitivity value
-     */
-    public static final Key<Integer> SENSOR_SENSITIVITY =
-            new Key<Integer>("android.sensor.sensitivity", Integer.TYPE);
-
-    // Many more settings
-
-    /**
      * @hide
      */
     public CaptureRequest() {
@@ -152,4 +137,751 @@
         }
     }
 
-}
\ No newline at end of file
+    /*@O~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~
+     * The key entries below this point are generated from metadata
+     * definitions in /system/media/camera/docs. Do not modify by hand or
+     * modify the comment blocks at the start or end.
+     *~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~*/
+
+    /**
+     * @see #COLOR_CORRECTION_MODE_TRANSFORM_MATRIX
+     * @see #COLOR_CORRECTION_MODE_FAST
+     * @see #COLOR_CORRECTION_MODE_HIGH_QUALITY
+     */
+    public static final Key<Integer> COLOR_CORRECTION_MODE =
+            new Key<Integer>("android.colorCorrection.mode", int.class);
+
+    /**
+     * <p>
+     * A color transform matrix to use to transform
+     * from sensor RGB color space to output linear sRGB color space
+     * </p>
+     * <p>
+     * This matrix is either set by HAL when the request
+     * android.colorCorrection.mode is not TRANSFORM_MATRIX, or
+     * directly by the application in the request when the
+     * androird.colorCorrection.mode is TRANSFORM_MATRIX.
+     * In the latter case, the HAL may round the matrix to account
+     * for precision issues; the final rounded matrix should be
+     * reported back in this matrix result metadata.
+     * </p>
+     */
+    public static final Key<Rational[]> COLOR_CORRECTION_TRANSFORM =
+            new Key<Rational[]>("android.colorCorrection.transform", Rational[].class);
+
+    /**
+     * <p>
+     * Gains applying to Bayer color channels for
+     * white-balance
+     * </p>
+     * <p>
+     * The 4-channel white-balance gains are defined in
+     * the order of [R G_even G_odd B], where G_even is the gain
+     * for green pixels on even rows of the output, and G_odd
+     * is the gain for greenpixels on the odd rows. if a HAL
+     * does not support a separate gain for even/odd green channels,
+     * it should use the G_even value,and write G_odd equal to
+     * G_even in the output result metadata.
+     * </p><p>
+     * The ouput should be the gains actually applied by the HAL to
+     * the current frame.
+     * </p>
+     */
+    public static final Key<float[]> COLOR_CORRECTION_GAINS =
+            new Key<float[]>("android.colorCorrection.gains", float[].class);
+
+    /**
+     * <p>
+     * Enum for controlling
+     * antibanding
+     * </p>
+     * @see #CONTROL_AE_ANTIBANDING_MODE_OFF
+     * @see #CONTROL_AE_ANTIBANDING_MODE_50HZ
+     * @see #CONTROL_AE_ANTIBANDING_MODE_60HZ
+     * @see #CONTROL_AE_ANTIBANDING_MODE_AUTO
+     */
+    public static final Key<Integer> CONTROL_AE_ANTIBANDING_MODE =
+            new Key<Integer>("android.control.aeAntibandingMode", int.class);
+
+    /**
+     * <p>
+     * Adjustment to AE target image
+     * brightness
+     * </p>
+     * <p>
+     * For example, if EV step is 0.333, '6' will mean an
+     * exposure compensation of +2 EV; -3 will mean an exposure
+     * compensation of -1
+     * </p>
+     */
+    public static final Key<Integer> CONTROL_AE_EXPOSURE_COMPENSATION =
+            new Key<Integer>("android.control.aeExposureCompensation", int.class);
+
+    /**
+     * <p>
+     * Whether AE is currently locked to its latest
+     * calculated values
+     * </p>
+     * <p>
+     * Note that even when AE is locked, the flash may be
+     * fired if the AE mode is ON_AUTO_FLASH / ON_ALWAYS_FLASH /
+     * ON_AUTO_FLASH_REDEYE.
+     * </p>
+     */
+    public static final Key<Boolean> CONTROL_AE_LOCK =
+            new Key<Boolean>("android.control.aeLock", boolean.class);
+
+    /**
+     * <p>
+     * Whether AE is currently updating the sensor
+     * exposure and sensitivity fields
+     * </p>
+     * <p>
+     * Only effective if android.control.mode =
+     * AUTO
+     * </p>
+     * @see #CONTROL_AE_MODE_OFF
+     * @see #CONTROL_AE_MODE_ON
+     * @see #CONTROL_AE_MODE_ON_AUTO_FLASH
+     * @see #CONTROL_AE_MODE_ON_ALWAYS_FLASH
+     * @see #CONTROL_AE_MODE_ON_AUTO_FLASH_REDEYE
+     */
+    public static final Key<Integer> CONTROL_AE_MODE =
+            new Key<Integer>("android.control.aeMode", int.class);
+
+    /**
+     * <p>
+     * List of areas to use for
+     * metering
+     * </p>
+     * <p>
+     * Each area is a rectangle plus weight: xmin, ymin,
+     * xmax, ymax, weight.
+     * </p><p>
+     * The coordinate system is based on the active pixel array,
+     * with (0,0) being the top-left of the active pixel array, and
+     * (android.sensor.info.activeArraySize.width,
+     * android.sensor.info.activeArraySize.height) being the
+     * bottom-right point of the active pixel array. The weight
+     * should be nonnegative.
+     * </p><p>
+     * If all regions have 0 weight, then no specific metering area
+     * needs to be used by the HAL. If the metering region is
+     * outside the current android.scaler.cropRegion, the HAL
+     * should ignore the sections outside the region and output the
+     * used sections in the frame metadata
+     * </p>
+     */
+    public static final Key<int[]> CONTROL_AE_REGIONS =
+            new Key<int[]>("android.control.aeRegions", int[].class);
+
+    /**
+     * <p>
+     * Range over which fps can be adjusted to
+     * maintain exposure
+     * </p>
+     * <p>
+     * Only constrains AE algorithm, not manual control
+     * of android.sensor.exposureTime
+     * </p>
+     */
+    public static final Key<int[]> CONTROL_AE_TARGET_FPS_RANGE =
+            new Key<int[]>("android.control.aeTargetFpsRange", int[].class);
+
+    /**
+     * <p>
+     * Whether the HAL must trigger precapture
+     * metering.
+     * </p>
+     * <p>
+     * This entry is normally set to IDLE, or is not
+     * included at all in the request settings. When included and
+     * set to START, the HAL must trigger the autoexposure
+     * precapture metering sequence.
+     * </p><p>
+     * The effect of AE precapture trigger depends on the current
+     * AE mode and state; see the camera HAL device v3 header for
+     * details.
+     * </p>
+     * @see #CONTROL_AE_PRECAPTURE_TRIGGER_IDLE
+     * @see #CONTROL_AE_PRECAPTURE_TRIGGER_START
+     */
+    public static final Key<Integer> CONTROL_AE_PRECAPTURE_TRIGGER =
+            new Key<Integer>("android.control.aePrecaptureTrigger", int.class);
+
+    /**
+     * <p>
+     * Whether AF is currently enabled, and what
+     * mode it is set to
+     * </p>
+     * @see #CONTROL_AF_MODE_OFF
+     * @see #CONTROL_AF_MODE_AUTO
+     * @see #CONTROL_AF_MODE_MACRO
+     * @see #CONTROL_AF_MODE_CONTINUOUS_VIDEO
+     * @see #CONTROL_AF_MODE_CONTINUOUS_PICTURE
+     * @see #CONTROL_AF_MODE_EDOF
+     */
+    public static final Key<Integer> CONTROL_AF_MODE =
+            new Key<Integer>("android.control.afMode", int.class);
+
+    /**
+     * <p>
+     * List of areas to use for focus
+     * estimation
+     * </p>
+     * <p>
+     * Each area is a rectangle plus weight: xmin, ymin,
+     * xmax, ymax, weight.
+     * </p><p>
+     * The coordinate system is based on the active pixel array,
+     * with (0,0) being the top-left of the active pixel array, and
+     * (android.sensor.info.activeArraySize.width,
+     * android.sensor.info.activeArraySize.height) being the
+     * bottom-right point of the active pixel array. The weight
+     * should be nonnegative.
+     * </p><p>
+     * If all regions have 0 weight, then no specific focus area
+     * needs to be used by the HAL. If the focusing region is
+     * outside the current android.scaler.cropRegion, the HAL
+     * should ignore the sections outside the region and output the
+     * used sections in the frame metadata
+     * </p>
+     */
+    public static final Key<int[]> CONTROL_AF_REGIONS =
+            new Key<int[]>("android.control.afRegions", int[].class);
+
+    /**
+     * <p>
+     * Whether the HAL must trigger autofocus.
+     * </p>
+     * <p>
+     * This entry is normally set to IDLE, or is not
+     * included at all in the request settings.
+     * </p><p>
+     * When included and set to START, the HAL must trigger the
+     * autofocus algorithm. The effect of AF trigger depends on the
+     * current AF mode and state; see the camera HAL device v3
+     * header for details. When set to CANCEL, the HAL must cancel
+     * any active trigger, and return to initial AF state.
+     * </p>
+     * @see #CONTROL_AF_TRIGGER_IDLE
+     * @see #CONTROL_AF_TRIGGER_START
+     * @see #CONTROL_AF_TRIGGER_CANCEL
+     */
+    public static final Key<Integer> CONTROL_AF_TRIGGER =
+            new Key<Integer>("android.control.afTrigger", int.class);
+
+    /**
+     * <p>
+     * Whether AWB is currently locked to its
+     * latest calculated values
+     * </p>
+     * <p>
+     * Note that AWB lock is only meaningful for AUTO
+     * mode; in other modes, AWB is already fixed to a specific
+     * setting
+     * </p>
+     */
+    public static final Key<Boolean> CONTROL_AWB_LOCK =
+            new Key<Boolean>("android.control.awbLock", boolean.class);
+
+    /**
+     * <p>
+     * Whether AWB is currently setting the color
+     * transform fields, and what its illumination target
+     * is
+     * </p>
+     * <p>
+     * [BC - AWB lock,AWB modes]
+     * </p>
+     * @see #CONTROL_AWB_MODE_OFF
+     * @see #CONTROL_AWB_MODE_AUTO
+     * @see #CONTROL_AWB_MODE_INCANDESCENT
+     * @see #CONTROL_AWB_MODE_FLUORESCENT
+     * @see #CONTROL_AWB_MODE_WARM_FLUORESCENT
+     * @see #CONTROL_AWB_MODE_DAYLIGHT
+     * @see #CONTROL_AWB_MODE_CLOUDY_DAYLIGHT
+     * @see #CONTROL_AWB_MODE_TWILIGHT
+     * @see #CONTROL_AWB_MODE_SHADE
+     */
+    public static final Key<Integer> CONTROL_AWB_MODE =
+            new Key<Integer>("android.control.awbMode", int.class);
+
+    /**
+     * <p>
+     * List of areas to use for illuminant
+     * estimation
+     * </p>
+     * <p>
+     * Only used in AUTO mode.
+     * </p><p>
+     * Each area is a rectangle plus weight: xmin, ymin, xmax,
+     * ymax, weight. The coordinate system is based on the active
+     * pixel array, with (0,0) being the top-left of the active
+     * pixel array, and (android.sensor.info.activeArraySize.width,
+     * android.sensor.info.activeArraySize.height) being the
+     * bottom-right point of the active pixel array. The weight
+     * should be nonnegative.
+     * </p><p>
+     * If all regions have 0 weight, then no specific metering area
+     * needs to be used by the HAL. If the metering region is
+     * outside the current android.scaler.cropRegion, the HAL
+     * should ignore the sections outside the region and output the
+     * used sections in the frame metadata
+     * </p>
+     */
+    public static final Key<int[]> CONTROL_AWB_REGIONS =
+            new Key<int[]>("android.control.awbRegions", int[].class);
+
+    /**
+     * <p>
+     * Information to 3A routines about the purpose
+     * of this capture, to help decide optimal 3A
+     * strategy
+     * </p>
+     * <p>
+     * Only used if android.control.mode != OFF.
+     * </p>
+     * @see #CONTROL_CAPTURE_INTENT_CUSTOM
+     * @see #CONTROL_CAPTURE_INTENT_PREVIEW
+     * @see #CONTROL_CAPTURE_INTENT_STILL_CAPTURE
+     * @see #CONTROL_CAPTURE_INTENT_VIDEO_RECORD
+     * @see #CONTROL_CAPTURE_INTENT_VIDEO_SNAPSHOT
+     * @see #CONTROL_CAPTURE_INTENT_ZERO_SHUTTER_LAG
+     */
+    public static final Key<Integer> CONTROL_CAPTURE_INTENT =
+            new Key<Integer>("android.control.captureIntent", int.class);
+
+    /**
+     * <p>
+     * Whether any special color effect is in use.
+     * Only used if android.control.mode != OFF
+     * </p>
+     * @see #CONTROL_EFFECT_MODE_OFF
+     * @see #CONTROL_EFFECT_MODE_MONO
+     * @see #CONTROL_EFFECT_MODE_NEGATIVE
+     * @see #CONTROL_EFFECT_MODE_SOLARIZE
+     * @see #CONTROL_EFFECT_MODE_SEPIA
+     * @see #CONTROL_EFFECT_MODE_POSTERIZE
+     * @see #CONTROL_EFFECT_MODE_WHITEBOARD
+     * @see #CONTROL_EFFECT_MODE_BLACKBOARD
+     * @see #CONTROL_EFFECT_MODE_AQUA
+     */
+    public static final Key<Integer> CONTROL_EFFECT_MODE =
+            new Key<Integer>("android.control.effectMode", int.class);
+
+    /**
+     * <p>
+     * Overall mode of 3A control
+     * routines
+     * </p>
+     * @see #CONTROL_MODE_OFF
+     * @see #CONTROL_MODE_AUTO
+     * @see #CONTROL_MODE_USE_SCENE_MODE
+     */
+    public static final Key<Integer> CONTROL_MODE =
+            new Key<Integer>("android.control.mode", int.class);
+
+    /**
+     * <p>
+     * Which scene mode is active when
+     * android.control.mode = SCENE_MODE
+     * </p>
+     * @see #CONTROL_SCENE_MODE_UNSUPPORTED
+     * @see #CONTROL_SCENE_MODE_FACE_PRIORITY
+     * @see #CONTROL_SCENE_MODE_ACTION
+     * @see #CONTROL_SCENE_MODE_PORTRAIT
+     * @see #CONTROL_SCENE_MODE_LANDSCAPE
+     * @see #CONTROL_SCENE_MODE_NIGHT
+     * @see #CONTROL_SCENE_MODE_NIGHT_PORTRAIT
+     * @see #CONTROL_SCENE_MODE_THEATRE
+     * @see #CONTROL_SCENE_MODE_BEACH
+     * @see #CONTROL_SCENE_MODE_SNOW
+     * @see #CONTROL_SCENE_MODE_SUNSET
+     * @see #CONTROL_SCENE_MODE_STEADYPHOTO
+     * @see #CONTROL_SCENE_MODE_FIREWORKS
+     * @see #CONTROL_SCENE_MODE_SPORTS
+     * @see #CONTROL_SCENE_MODE_PARTY
+     * @see #CONTROL_SCENE_MODE_CANDLELIGHT
+     * @see #CONTROL_SCENE_MODE_BARCODE
+     */
+    public static final Key<Integer> CONTROL_SCENE_MODE =
+            new Key<Integer>("android.control.sceneMode", int.class);
+
+    /**
+     * <p>
+     * Whether video stabilization is
+     * active
+     * </p>
+     * <p>
+     * If enabled, video stabilization can modify the
+     * android.scaler.cropRegion to keep the video stream
+     * stabilized
+     * </p>
+     */
+    public static final Key<Boolean> CONTROL_VIDEO_STABILIZATION_MODE =
+            new Key<Boolean>("android.control.videoStabilizationMode", boolean.class);
+
+    /**
+     * <p>
+     * Operation mode for edge
+     * enhancement
+     * </p>
+     * @see #EDGE_MODE_OFF
+     * @see #EDGE_MODE_FAST
+     * @see #EDGE_MODE_HIGH_QUALITY
+     */
+    public static final Key<Integer> EDGE_MODE =
+            new Key<Integer>("android.edge.mode", int.class);
+
+    /**
+     * <p>
+     * Select flash operation mode
+     * </p>
+     * @see #FLASH_MODE_OFF
+     * @see #FLASH_MODE_SINGLE
+     * @see #FLASH_MODE_TORCH
+     */
+    public static final Key<Integer> FLASH_MODE =
+            new Key<Integer>("android.flash.mode", int.class);
+
+    /**
+     * <p>
+     * GPS coordinates to include in output JPEG
+     * EXIF
+     * </p>
+     */
+    public static final Key<double[]> JPEG_GPS_COORDINATES =
+            new Key<double[]>("android.jpeg.gpsCoordinates", double[].class);
+
+    /**
+     * <p>
+     * 32 characters describing GPS algorithm to
+     * include in EXIF
+     * </p>
+     */
+    public static final Key<String> JPEG_GPS_PROCESSING_METHOD =
+            new Key<String>("android.jpeg.gpsProcessingMethod", String.class);
+
+    /**
+     * <p>
+     * Time GPS fix was made to include in
+     * EXIF
+     * </p>
+     */
+    public static final Key<Long> JPEG_GPS_TIMESTAMP =
+            new Key<Long>("android.jpeg.gpsTimestamp", long.class);
+
+    /**
+     * <p>
+     * Orientation of JPEG image to
+     * write
+     * </p>
+     */
+    public static final Key<Integer> JPEG_ORIENTATION =
+            new Key<Integer>("android.jpeg.orientation", int.class);
+
+    /**
+     * <p>
+     * Compression quality of the final JPEG
+     * image
+     * </p>
+     * <p>
+     * 85-95 is typical usage range
+     * </p>
+     */
+    public static final Key<Byte> JPEG_QUALITY =
+            new Key<Byte>("android.jpeg.quality", byte.class);
+
+    /**
+     * <p>
+     * Compression quality of JPEG
+     * thumbnail
+     * </p>
+     */
+    public static final Key<Byte> JPEG_THUMBNAIL_QUALITY =
+            new Key<Byte>("android.jpeg.thumbnailQuality", byte.class);
+
+    /**
+     * <p>
+     * Resolution of embedded JPEG
+     * thumbnail
+     * </p>
+     */
+    public static final Key<android.hardware.camera2.Size> JPEG_THUMBNAIL_SIZE =
+            new Key<android.hardware.camera2.Size>("android.jpeg.thumbnailSize", android.hardware.camera2.Size.class);
+
+    /**
+     * <p>
+     * Size of the lens aperture
+     * </p>
+     * <p>
+     * Will not be supported on most devices. Can only
+     * pick from supported list
+     * </p>
+     */
+    public static final Key<Float> LENS_APERTURE =
+            new Key<Float>("android.lens.aperture", float.class);
+
+    /**
+     * <p>
+     * State of lens neutral density
+     * filter(s)
+     * </p>
+     * <p>
+     * Will not be supported on most devices. Can only
+     * pick from supported list
+     * </p>
+     */
+    public static final Key<Float> LENS_FILTER_DENSITY =
+            new Key<Float>("android.lens.filterDensity", float.class);
+
+    /**
+     * <p>
+     * Lens optical zoom setting
+     * </p>
+     * <p>
+     * Will not be supported on most devices.
+     * </p>
+     */
+    public static final Key<Float> LENS_FOCAL_LENGTH =
+            new Key<Float>("android.lens.focalLength", float.class);
+
+    /**
+     * <p>
+     * Distance to plane of sharpest focus,
+     * measured from frontmost surface of the lens
+     * </p>
+     * <p>
+     * 0 = infinity focus. Used value should be clamped
+     * to (0,minimum focus distance)
+     * </p>
+     */
+    public static final Key<Float> LENS_FOCUS_DISTANCE =
+            new Key<Float>("android.lens.focusDistance", float.class);
+
+    /**
+     * <p>
+     * Whether optical image stabilization is
+     * enabled.
+     * </p>
+     * <p>
+     * Will not be supported on most devices.
+     * </p>
+     * @see #LENS_OPTICAL_STABILIZATION_MODE_OFF
+     * @see #LENS_OPTICAL_STABILIZATION_MODE_ON
+     */
+    public static final Key<Integer> LENS_OPTICAL_STABILIZATION_MODE =
+            new Key<Integer>("android.lens.opticalStabilizationMode", int.class);
+
+    /**
+     * <p>
+     * Mode of operation for the noise reduction
+     * algorithm
+     * </p>
+     * @see #NOISE_REDUCTION_MODE_OFF
+     * @see #NOISE_REDUCTION_MODE_FAST
+     * @see #NOISE_REDUCTION_MODE_HIGH_QUALITY
+     */
+    public static final Key<Integer> NOISE_REDUCTION_MODE =
+            new Key<Integer>("android.noiseReduction.mode", int.class);
+
+    /**
+     * <p>
+     * An application-specified ID for the current
+     * request. Must be maintained unchanged in output
+     * frame
+     * </p>
+     *
+     * @hide
+     */
+    public static final Key<Integer> REQUEST_ID =
+            new Key<Integer>("android.request.id", int.class);
+
+    /**
+     * <p>
+     * (x, y, width, height).
+     * </p><p>
+     * A rectangle with the top-level corner of (x,y) and size
+     * (width, height). The region of the sensor that is used for
+     * output. Each stream must use this rectangle to produce its
+     * output, cropping to a smaller region if necessary to
+     * maintain the stream's aspect ratio.
+     * </p><p>
+     * HAL2.x uses only (x, y, width)
+     * </p>
+     * <p>
+     * Any additional per-stream cropping must be done to
+     * maximize the final pixel area of the stream.
+     * </p><p>
+     * For example, if the crop region is set to a 4:3 aspect
+     * ratio, then 4:3 streams should use the exact crop
+     * region. 16:9 streams should further crop vertically
+     * (letterbox).
+     * </p><p>
+     * Conversely, if the crop region is set to a 16:9, then 4:3
+     * outputs should crop horizontally (pillarbox), and 16:9
+     * streams should match exactly. These additional crops must
+     * be centered within the crop region.
+     * </p><p>
+     * The output streams must maintain square pixels at all
+     * times, no matter what the relative aspect ratios of the
+     * crop region and the stream are.  Negative values for
+     * corner are allowed for raw output if full pixel array is
+     * larger than active pixel array. Width and height may be
+     * rounded to nearest larger supportable width, especially
+     * for raw output, where only a few fixed scales may be
+     * possible. The width and height of the crop region cannot
+     * be set to be smaller than floor( activeArraySize.width /
+     * android.scaler.maxDigitalZoom ) and floor(
+     * activeArraySize.height / android.scaler.maxDigitalZoom),
+     * respectively.
+     * </p>
+     */
+    public static final Key<android.graphics.Rect> SCALER_CROP_REGION =
+            new Key<android.graphics.Rect>("android.scaler.cropRegion", android.graphics.Rect.class);
+
+    /**
+     * <p>
+     * Duration each pixel is exposed to
+     * light
+     * </p>
+     * <p>
+     * 1/10000 - 30 sec range. No bulb mode
+     * </p>
+     */
+    public static final Key<Long> SENSOR_EXPOSURE_TIME =
+            new Key<Long>("android.sensor.exposureTime", long.class);
+
+    /**
+     * <p>
+     * Duration from start of frame exposure to
+     * start of next frame exposure
+     * </p>
+     * <p>
+     * Exposure time has priority, so duration is set to
+     * max(duration, exposure time + overhead)
+     * </p>
+     */
+    public static final Key<Long> SENSOR_FRAME_DURATION =
+            new Key<Long>("android.sensor.frameDuration", long.class);
+
+    /**
+     * <p>
+     * Gain applied to image data. Must be
+     * implemented through analog gain only if set to values
+     * below 'maximum analog sensitivity'.
+     * </p>
+     * <p>
+     * ISO 12232:2006 REI method
+     * </p>
+     */
+    public static final Key<Integer> SENSOR_SENSITIVITY =
+            new Key<Integer>("android.sensor.sensitivity", int.class);
+
+    /**
+     * <p>
+     * State of the face detector
+     * unit
+     * </p>
+     * <p>
+     * Whether face detection is enabled, and whether it
+     * should output just the basic fields or the full set of
+     * fields. Value must be one of the
+     * android.statistics.info.availableFaceDetectModes.
+     * </p>
+     * @see #STATISTICS_FACE_DETECT_MODE_OFF
+     * @see #STATISTICS_FACE_DETECT_MODE_SIMPLE
+     * @see #STATISTICS_FACE_DETECT_MODE_FULL
+     */
+    public static final Key<Integer> STATISTICS_FACE_DETECT_MODE =
+            new Key<Integer>("android.statistics.faceDetectMode", int.class);
+
+    /**
+     * <p>
+     * Table mapping blue input values to output
+     * values
+     * </p>
+     */
+    public static final Key<Float> TONEMAP_CURVE_BLUE =
+            new Key<Float>("android.tonemap.curveBlue", float.class);
+
+    /**
+     * <p>
+     * Table mapping green input values to output
+     * values
+     * </p>
+     */
+    public static final Key<Float> TONEMAP_CURVE_GREEN =
+            new Key<Float>("android.tonemap.curveGreen", float.class);
+
+    /**
+     * <p>
+     * Table mapping red input values to output
+     * values
+     * </p>
+     * <p>
+     * .The input range must be monotonically increasing
+     * with N, and values between entries should be linearly
+     * interpolated. For example, if the array is: [0.0, 0.0,
+     * 0.3, 0.5, 1.0, 1.0], then the input->output mapping
+     * for a few sample points would be: 0 -> 0, 0.15 ->
+     * 0.25, 0.3 -> 0.5, 0.5 -> 0.64
+     * </p>
+     */
+    public static final Key<float[]> TONEMAP_CURVE_RED =
+            new Key<float[]>("android.tonemap.curveRed", float[].class);
+
+    /**
+     * @see #TONEMAP_MODE_CONTRAST_CURVE
+     * @see #TONEMAP_MODE_FAST
+     * @see #TONEMAP_MODE_HIGH_QUALITY
+     */
+    public static final Key<Integer> TONEMAP_MODE =
+            new Key<Integer>("android.tonemap.mode", int.class);
+
+    /**
+     * <p>
+     * This LED is nominally used to indicate to the user
+     * that the camera is powered on and may be streaming images back to the
+     * Application Processor. In certain rare circumstances, the OS may
+     * disable this when video is processed locally and not transmitted to
+     * any untrusted applications.
+     * </p><p>
+     * In particular, the LED *must* always be on when the data could be
+     * transmitted off the device. The LED *should* always be on whenever
+     * data is stored locally on the device.
+     * </p><p>
+     * The LED *may* be off if a trusted application is using the data that
+     * doesn't violate the above rules.
+     * </p>
+     *
+     * @hide
+     */
+    public static final Key<Boolean> LED_TRANSMIT =
+            new Key<Boolean>("android.led.transmit", boolean.class);
+
+    /**
+     * <p>
+     * Whether black-level compensation is locked
+     * to its current values, or is free to vary
+     * </p>
+     * <p>
+     * When set to ON, the values used for black-level
+     * compensation must not change until the lock is set to
+     * OFF
+     * </p><p>
+     * Since changes to certain capture parameters (such as
+     * exposure time) may require resetting of black level
+     * compensation, the HAL must report whether setting the
+     * black level lock was successful in the output result
+     * metadata.
+     * </p>
+     */
+    public static final Key<Boolean> BLACK_LEVEL_LOCK =
+            new Key<Boolean>("android.blackLevel.lock", boolean.class);
+
+    /*~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~
+     * End generated code
+     *~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~O@*/
+}
diff --git a/core/java/android/hardware/camera2/CaptureResult.java b/core/java/android/hardware/camera2/CaptureResult.java
index 11c991a..d5bb8b3 100644
--- a/core/java/android/hardware/camera2/CaptureResult.java
+++ b/core/java/android/hardware/camera2/CaptureResult.java
@@ -34,73 +34,6 @@
  *
  */
 public final class CaptureResult extends CameraMetadata {
-
-    /**
-     * The timestamp representing the start of image capture, in nanoseconds.
-     * This corresponds to the timestamp available through
-     * {@link android.graphics.SurfaceTexture#getTimestamp SurfaceTexture.getTimestamp()}
-     * or {@link android.media.Image#getTimestamp Image.getTimestamp()} for this
-     * capture's image data.
-     */
-    public static final Key<Long> SENSOR_TIMESTAMP =
-            new Key<Long>("android.sensor.timestamp", Long.TYPE);
-
-    /**
-     * The state of the camera device's auto-exposure algorithm. One of the
-     * CONTROL_AE_STATE_* enumerations.
-     */
-    public static final Key<Integer> CONTROL_AE_STATE =
-            new Key<Integer>("android.control.aeState", Integer.TYPE);
-
-    /**
-     * The auto-exposure algorithm is inactive.
-     * @see CONTROL_AE_STATE
-     */
-    public static final int CONTROL_AE_STATE_INACTIVE = 0;
-
-    /**
-     * The auto-exposure algorithm is currently searching for proper exposure.
-     * @see CONTROL_AE_STATE
-     */
-    public static final int CONTROL_AE_STATE_SEARCHING = 1;
-
-    /**
-     * The auto-exposure algorithm has reached proper exposure values for the
-     * current scene.
-     * @see CONTROL_AE_STATE
-     */
-    public static final int CONTROL_AE_STATE_CONVERGED = 2;
-
-    /**
-     * The auto-exposure algorithm has been locked to its current values.
-     * @see CONTROL_AE_STATE
-     */
-    public static final int CONTROL_AE_STATE_LOCKED = 3;
-
-    /**
-     * The auto-exposure algorithm has reached proper exposure values as with
-     * CONTROL_AE_STATE_CONVERGED, but the scene is too dark to take a good
-     * quality image without firing the camera flash.
-     * @see CONTROL_AE_STATE
-     */
-    public static final int CONTROL_AE_STATE_FLASH_REQUIRED = 4;
-
-    /**
-     * The precapture sequence of the auto-exposure algorithm has been triggered,
-     * and is underway.
-     * @see CONTROL_AE_STATE
-     */
-    public static final int CONTROL_AE_STATE_PRECAPTURE =5;
-
-    /**
-     * The list of faces detected in this capture. Available if face detection
-     * was enabled for this capture
-     */
-    public static final Key<Face[]> STATISTICS_DETECTED_FACES =
-            new Key<Face[]>("android.statistics.faces", Face[].class);
-
-    // TODO: Many many more
-
     /**
      * @hide
      */
@@ -114,7 +47,7 @@
 
         /**
          * <p>Bounds of the face. A rectangle relative to the sensor's
-         * {@link CameraProperties#SENSOR_ACTIVE_ARRAY_SIZE}, with (0,0)
+         * {@link CameraProperties#SENSOR_INFO_ACTIVE_ARRAY_SIZE}, with (0,0)
          * representing the top-left corner of the active array rectangle.</p>
          */
         public Rect getBounds() {
@@ -189,4 +122,807 @@
         private Point mRightEye;
         private Point mMouth;
     }
+
+    /*@O~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~
+     * The key entries below this point are generated from metadata
+     * definitions in /system/media/camera/docs. Do not modify by hand or
+     * modify the comment blocks at the start or end.
+     *~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~*/
+
+    /**
+     * <p>
+     * A color transform matrix to use to transform
+     * from sensor RGB color space to output linear sRGB color space
+     * </p>
+     * <p>
+     * This matrix is either set by HAL when the request
+     * android.colorCorrection.mode is not TRANSFORM_MATRIX, or
+     * directly by the application in the request when the
+     * androird.colorCorrection.mode is TRANSFORM_MATRIX.
+     * In the latter case, the HAL may round the matrix to account
+     * for precision issues; the final rounded matrix should be
+     * reported back in this matrix result metadata.
+     * </p>
+     */
+    public static final Key<Rational[]> COLOR_CORRECTION_TRANSFORM =
+            new Key<Rational[]>("android.colorCorrection.transform", Rational[].class);
+
+    /**
+     * <p>
+     * Gains applying to Bayer color channels for
+     * white-balance
+     * </p>
+     * <p>
+     * The 4-channel white-balance gains are defined in
+     * the order of [R G_even G_odd B], where G_even is the gain
+     * for green pixels on even rows of the output, and G_odd
+     * is the gain for greenpixels on the odd rows. if a HAL
+     * does not support a separate gain for even/odd green channels,
+     * it should use the G_even value,and write G_odd equal to
+     * G_even in the output result metadata.
+     * </p><p>
+     * The ouput should be the gains actually applied by the HAL to
+     * the current frame.
+     * </p>
+     */
+    public static final Key<float[]> COLOR_CORRECTION_GAINS =
+            new Key<float[]>("android.colorCorrection.gains", float[].class);
+
+    /**
+     * <p>
+     * The ID sent with the latest
+     * CAMERA2_TRIGGER_PRECAPTURE_METERING call
+     * </p>
+     * <p>
+     * Must be 0 if no
+     * CAMERA2_TRIGGER_PRECAPTURE_METERING trigger received yet
+     * by HAL. Always updated even if AE algorithm ignores the
+     * trigger
+     * </p>
+     *
+     * @hide
+     */
+    public static final Key<Integer> CONTROL_AE_PRECAPTURE_ID =
+            new Key<Integer>("android.control.aePrecaptureId", int.class);
+
+    /**
+     * <p>
+     * List of areas to use for
+     * metering
+     * </p>
+     * <p>
+     * Each area is a rectangle plus weight: xmin, ymin,
+     * xmax, ymax, weight.
+     * </p><p>
+     * The coordinate system is based on the active pixel array,
+     * with (0,0) being the top-left of the active pixel array, and
+     * (android.sensor.info.activeArraySize.width,
+     * android.sensor.info.activeArraySize.height) being the
+     * bottom-right point of the active pixel array. The weight
+     * should be nonnegative.
+     * </p><p>
+     * If all regions have 0 weight, then no specific metering area
+     * needs to be used by the HAL. If the metering region is
+     * outside the current android.scaler.cropRegion, the HAL
+     * should ignore the sections outside the region and output the
+     * used sections in the frame metadata
+     * </p>
+     */
+    public static final Key<int[]> CONTROL_AE_REGIONS =
+            new Key<int[]>("android.control.aeRegions", int[].class);
+
+    /**
+     * <p>
+     * Current state of AE algorithm
+     * </p>
+     * <p>
+     * Whenever the AE algorithm state changes, a
+     * MSG_AUTOEXPOSURE notification must be send if a
+     * notification callback is registered.
+     * </p>
+     * @see #CONTROL_AE_STATE_INACTIVE
+     * @see #CONTROL_AE_STATE_SEARCHING
+     * @see #CONTROL_AE_STATE_CONVERGED
+     * @see #CONTROL_AE_STATE_LOCKED
+     * @see #CONTROL_AE_STATE_FLASH_REQUIRED
+     * @see #CONTROL_AE_STATE_PRECAPTURE
+     */
+    public static final Key<Integer> CONTROL_AE_STATE =
+            new Key<Integer>("android.control.aeState", int.class);
+
+    /**
+     * <p>
+     * Whether AF is currently enabled, and what
+     * mode it is set to
+     * </p>
+     * @see #CONTROL_AF_MODE_OFF
+     * @see #CONTROL_AF_MODE_AUTO
+     * @see #CONTROL_AF_MODE_MACRO
+     * @see #CONTROL_AF_MODE_CONTINUOUS_VIDEO
+     * @see #CONTROL_AF_MODE_CONTINUOUS_PICTURE
+     * @see #CONTROL_AF_MODE_EDOF
+     */
+    public static final Key<Integer> CONTROL_AF_MODE =
+            new Key<Integer>("android.control.afMode", int.class);
+
+    /**
+     * <p>
+     * List of areas to use for focus
+     * estimation
+     * </p>
+     * <p>
+     * Each area is a rectangle plus weight: xmin, ymin,
+     * xmax, ymax, weight.
+     * </p><p>
+     * The coordinate system is based on the active pixel array,
+     * with (0,0) being the top-left of the active pixel array, and
+     * (android.sensor.info.activeArraySize.width,
+     * android.sensor.info.activeArraySize.height) being the
+     * bottom-right point of the active pixel array. The weight
+     * should be nonnegative.
+     * </p><p>
+     * If all regions have 0 weight, then no specific focus area
+     * needs to be used by the HAL. If the focusing region is
+     * outside the current android.scaler.cropRegion, the HAL
+     * should ignore the sections outside the region and output the
+     * used sections in the frame metadata
+     * </p>
+     */
+    public static final Key<int[]> CONTROL_AF_REGIONS =
+            new Key<int[]>("android.control.afRegions", int[].class);
+
+    /**
+     * <p>
+     * Current state of AF algorithm
+     * </p>
+     * <p>
+     * Whenever the AF algorithm state changes, a
+     * MSG_AUTOFOCUS notification must be send if a notification
+     * callback is registered.
+     * </p>
+     * @see #CONTROL_AF_STATE_INACTIVE
+     * @see #CONTROL_AF_STATE_PASSIVE_SCAN
+     * @see #CONTROL_AF_STATE_PASSIVE_FOCUSED
+     * @see #CONTROL_AF_STATE_ACTIVE_SCAN
+     * @see #CONTROL_AF_STATE_FOCUSED_LOCKED
+     * @see #CONTROL_AF_STATE_NOT_FOCUSED_LOCKED
+     */
+    public static final Key<Integer> CONTROL_AF_STATE =
+            new Key<Integer>("android.control.afState", int.class);
+
+    /**
+     * <p>
+     * The ID sent with the latest
+     * CAMERA2_TRIGGER_AUTOFOCUS call
+     * </p>
+     * <p>
+     * Must be 0 if no CAMERA2_TRIGGER_AUTOFOCUS trigger
+     * received yet by HAL. Always updated even if AF algorithm
+     * ignores the trigger
+     * </p>
+     *
+     * @hide
+     */
+    public static final Key<Integer> CONTROL_AF_TRIGGER_ID =
+            new Key<Integer>("android.control.afTriggerId", int.class);
+
+    /**
+     * <p>
+     * Whether AWB is currently setting the color
+     * transform fields, and what its illumination target
+     * is
+     * </p>
+     * <p>
+     * [BC - AWB lock,AWB modes]
+     * </p>
+     * @see #CONTROL_AWB_MODE_OFF
+     * @see #CONTROL_AWB_MODE_AUTO
+     * @see #CONTROL_AWB_MODE_INCANDESCENT
+     * @see #CONTROL_AWB_MODE_FLUORESCENT
+     * @see #CONTROL_AWB_MODE_WARM_FLUORESCENT
+     * @see #CONTROL_AWB_MODE_DAYLIGHT
+     * @see #CONTROL_AWB_MODE_CLOUDY_DAYLIGHT
+     * @see #CONTROL_AWB_MODE_TWILIGHT
+     * @see #CONTROL_AWB_MODE_SHADE
+     */
+    public static final Key<Integer> CONTROL_AWB_MODE =
+            new Key<Integer>("android.control.awbMode", int.class);
+
+    /**
+     * <p>
+     * List of areas to use for illuminant
+     * estimation
+     * </p>
+     * <p>
+     * Only used in AUTO mode.
+     * </p><p>
+     * Each area is a rectangle plus weight: xmin, ymin, xmax,
+     * ymax, weight. The coordinate system is based on the active
+     * pixel array, with (0,0) being the top-left of the active
+     * pixel array, and (android.sensor.info.activeArraySize.width,
+     * android.sensor.info.activeArraySize.height) being the
+     * bottom-right point of the active pixel array. The weight
+     * should be nonnegative.
+     * </p><p>
+     * If all regions have 0 weight, then no specific metering area
+     * needs to be used by the HAL. If the metering region is
+     * outside the current android.scaler.cropRegion, the HAL
+     * should ignore the sections outside the region and output the
+     * used sections in the frame metadata
+     * </p>
+     */
+    public static final Key<int[]> CONTROL_AWB_REGIONS =
+            new Key<int[]>("android.control.awbRegions", int[].class);
+
+    /**
+     * <p>
+     * Current state of AWB algorithm
+     * </p>
+     * <p>
+     * Whenever the AWB algorithm state changes, a
+     * MSG_AUTOWHITEBALANCE notification must be send if a
+     * notification callback is registered.
+     * </p>
+     * @see #CONTROL_AWB_STATE_INACTIVE
+     * @see #CONTROL_AWB_STATE_SEARCHING
+     * @see #CONTROL_AWB_STATE_CONVERGED
+     * @see #CONTROL_AWB_STATE_LOCKED
+     */
+    public static final Key<Integer> CONTROL_AWB_STATE =
+            new Key<Integer>("android.control.awbState", int.class);
+
+    /**
+     * <p>
+     * Overall mode of 3A control
+     * routines
+     * </p>
+     * @see #CONTROL_MODE_OFF
+     * @see #CONTROL_MODE_AUTO
+     * @see #CONTROL_MODE_USE_SCENE_MODE
+     */
+    public static final Key<Integer> CONTROL_MODE =
+            new Key<Integer>("android.control.mode", int.class);
+
+    /**
+     * <p>
+     * Operation mode for edge
+     * enhancement
+     * </p>
+     * @see #EDGE_MODE_OFF
+     * @see #EDGE_MODE_FAST
+     * @see #EDGE_MODE_HIGH_QUALITY
+     */
+    public static final Key<Integer> EDGE_MODE =
+            new Key<Integer>("android.edge.mode", int.class);
+
+    /**
+     * <p>
+     * Select flash operation mode
+     * </p>
+     * @see #FLASH_MODE_OFF
+     * @see #FLASH_MODE_SINGLE
+     * @see #FLASH_MODE_TORCH
+     */
+    public static final Key<Integer> FLASH_MODE =
+            new Key<Integer>("android.flash.mode", int.class);
+
+    /**
+     * <p>
+     * Current state of the flash
+     * unit
+     * </p>
+     * @see #FLASH_STATE_UNAVAILABLE
+     * @see #FLASH_STATE_CHARGING
+     * @see #FLASH_STATE_READY
+     * @see #FLASH_STATE_FIRED
+     */
+    public static final Key<Integer> FLASH_STATE =
+            new Key<Integer>("android.flash.state", int.class);
+
+    /**
+     * <p>
+     * GPS coordinates to include in output JPEG
+     * EXIF
+     * </p>
+     */
+    public static final Key<double[]> JPEG_GPS_COORDINATES =
+            new Key<double[]>("android.jpeg.gpsCoordinates", double[].class);
+
+    /**
+     * <p>
+     * 32 characters describing GPS algorithm to
+     * include in EXIF
+     * </p>
+     */
+    public static final Key<String> JPEG_GPS_PROCESSING_METHOD =
+            new Key<String>("android.jpeg.gpsProcessingMethod", String.class);
+
+    /**
+     * <p>
+     * Time GPS fix was made to include in
+     * EXIF
+     * </p>
+     */
+    public static final Key<Long> JPEG_GPS_TIMESTAMP =
+            new Key<Long>("android.jpeg.gpsTimestamp", long.class);
+
+    /**
+     * <p>
+     * Orientation of JPEG image to
+     * write
+     * </p>
+     */
+    public static final Key<Integer> JPEG_ORIENTATION =
+            new Key<Integer>("android.jpeg.orientation", int.class);
+
+    /**
+     * <p>
+     * Compression quality of the final JPEG
+     * image
+     * </p>
+     * <p>
+     * 85-95 is typical usage range
+     * </p>
+     */
+    public static final Key<Byte> JPEG_QUALITY =
+            new Key<Byte>("android.jpeg.quality", byte.class);
+
+    /**
+     * <p>
+     * Compression quality of JPEG
+     * thumbnail
+     * </p>
+     */
+    public static final Key<Byte> JPEG_THUMBNAIL_QUALITY =
+            new Key<Byte>("android.jpeg.thumbnailQuality", byte.class);
+
+    /**
+     * <p>
+     * Resolution of embedded JPEG
+     * thumbnail
+     * </p>
+     */
+    public static final Key<android.hardware.camera2.Size> JPEG_THUMBNAIL_SIZE =
+            new Key<android.hardware.camera2.Size>("android.jpeg.thumbnailSize", android.hardware.camera2.Size.class);
+
+    /**
+     * <p>
+     * Size of the lens aperture
+     * </p>
+     * <p>
+     * Will not be supported on most devices. Can only
+     * pick from supported list
+     * </p>
+     */
+    public static final Key<Float> LENS_APERTURE =
+            new Key<Float>("android.lens.aperture", float.class);
+
+    /**
+     * <p>
+     * State of lens neutral density
+     * filter(s)
+     * </p>
+     * <p>
+     * Will not be supported on most devices. Can only
+     * pick from supported list
+     * </p>
+     */
+    public static final Key<Float> LENS_FILTER_DENSITY =
+            new Key<Float>("android.lens.filterDensity", float.class);
+
+    /**
+     * <p>
+     * Lens optical zoom setting
+     * </p>
+     * <p>
+     * Will not be supported on most devices.
+     * </p>
+     */
+    public static final Key<Float> LENS_FOCAL_LENGTH =
+            new Key<Float>("android.lens.focalLength", float.class);
+
+    /**
+     * <p>
+     * Distance to plane of sharpest focus,
+     * measured from frontmost surface of the lens
+     * </p>
+     * <p>
+     * Should be zero for fixed-focus cameras
+     * </p>
+     */
+    public static final Key<Float> LENS_FOCUS_DISTANCE =
+            new Key<Float>("android.lens.focusDistance", float.class);
+
+    /**
+     * <p>
+     * The range of scene distances that are in
+     * sharp focus (depth of field)
+     * </p>
+     * <p>
+     * If variable focus not supported, can still report
+     * fixed depth of field range
+     * </p>
+     */
+    public static final Key<Float> LENS_FOCUS_RANGE =
+            new Key<Float>("android.lens.focusRange", float.class);
+
+    /**
+     * <p>
+     * Whether optical image stabilization is
+     * enabled.
+     * </p>
+     * <p>
+     * Will not be supported on most devices.
+     * </p>
+     * @see #LENS_OPTICAL_STABILIZATION_MODE_OFF
+     * @see #LENS_OPTICAL_STABILIZATION_MODE_ON
+     */
+    public static final Key<Integer> LENS_OPTICAL_STABILIZATION_MODE =
+            new Key<Integer>("android.lens.opticalStabilizationMode", int.class);
+
+    /**
+     * <p>
+     * Current lens status
+     * </p>
+     * @see #LENS_STATE_STATIONARY
+     */
+    public static final Key<Integer> LENS_STATE =
+            new Key<Integer>("android.lens.state", int.class);
+
+    /**
+     * <p>
+     * Mode of operation for the noise reduction
+     * algorithm
+     * </p>
+     * @see #NOISE_REDUCTION_MODE_OFF
+     * @see #NOISE_REDUCTION_MODE_FAST
+     * @see #NOISE_REDUCTION_MODE_HIGH_QUALITY
+     */
+    public static final Key<Integer> NOISE_REDUCTION_MODE =
+            new Key<Integer>("android.noiseReduction.mode", int.class);
+
+    /**
+     * <p>
+     * Number of frames captured since
+     * open()
+     * </p>
+     * <p>
+     * Reset on release()
+     * </p>
+     */
+    public static final Key<Integer> REQUEST_FRAME_COUNT =
+            new Key<Integer>("android.request.frameCount", int.class);
+
+    /**
+     * <p>
+     * An application-specified ID for the current
+     * request. Must be maintained unchanged in output
+     * frame
+     * </p>
+     *
+     * @hide
+     */
+    public static final Key<Integer> REQUEST_ID =
+            new Key<Integer>("android.request.id", int.class);
+
+    /**
+     * <p>
+     * (x, y, width, height).
+     * </p><p>
+     * A rectangle with the top-level corner of (x,y) and size
+     * (width, height). The region of the sensor that is used for
+     * output. Each stream must use this rectangle to produce its
+     * output, cropping to a smaller region if necessary to
+     * maintain the stream's aspect ratio.
+     * </p><p>
+     * HAL2.x uses only (x, y, width)
+     * </p>
+     * <p>
+     * Any additional per-stream cropping must be done to
+     * maximize the final pixel area of the stream.
+     * </p><p>
+     * For example, if the crop region is set to a 4:3 aspect
+     * ratio, then 4:3 streams should use the exact crop
+     * region. 16:9 streams should further crop vertically
+     * (letterbox).
+     * </p><p>
+     * Conversely, if the crop region is set to a 16:9, then 4:3
+     * outputs should crop horizontally (pillarbox), and 16:9
+     * streams should match exactly. These additional crops must
+     * be centered within the crop region.
+     * </p><p>
+     * The output streams must maintain square pixels at all
+     * times, no matter what the relative aspect ratios of the
+     * crop region and the stream are.  Negative values for
+     * corner are allowed for raw output if full pixel array is
+     * larger than active pixel array. Width and height may be
+     * rounded to nearest larger supportable width, especially
+     * for raw output, where only a few fixed scales may be
+     * possible. The width and height of the crop region cannot
+     * be set to be smaller than floor( activeArraySize.width /
+     * android.scaler.maxDigitalZoom ) and floor(
+     * activeArraySize.height / android.scaler.maxDigitalZoom),
+     * respectively.
+     * </p>
+     */
+    public static final Key<android.graphics.Rect> SCALER_CROP_REGION =
+            new Key<android.graphics.Rect>("android.scaler.cropRegion", android.graphics.Rect.class);
+
+    /**
+     * <p>
+     * Duration each pixel is exposed to
+     * light
+     * </p>
+     * <p>
+     * 1/10000 - 30 sec range. No bulb mode
+     * </p>
+     */
+    public static final Key<Long> SENSOR_EXPOSURE_TIME =
+            new Key<Long>("android.sensor.exposureTime", long.class);
+
+    /**
+     * <p>
+     * Duration from start of frame exposure to
+     * start of next frame exposure
+     * </p>
+     * <p>
+     * Exposure time has priority, so duration is set to
+     * max(duration, exposure time + overhead)
+     * </p>
+     */
+    public static final Key<Long> SENSOR_FRAME_DURATION =
+            new Key<Long>("android.sensor.frameDuration", long.class);
+
+    /**
+     * <p>
+     * Gain applied to image data. Must be
+     * implemented through analog gain only if set to values
+     * below 'maximum analog sensitivity'.
+     * </p>
+     * <p>
+     * ISO 12232:2006 REI method
+     * </p>
+     */
+    public static final Key<Integer> SENSOR_SENSITIVITY =
+            new Key<Integer>("android.sensor.sensitivity", int.class);
+
+    /**
+     * <p>
+     * Time at start of exposure of first
+     * row
+     * </p>
+     * <p>
+     * Monotonic, should be synced to other timestamps in
+     * system
+     * </p>
+     */
+    public static final Key<Long> SENSOR_TIMESTAMP =
+            new Key<Long>("android.sensor.timestamp", long.class);
+
+    /**
+     * <p>
+     * State of the face detector
+     * unit
+     * </p>
+     * <p>
+     * Whether face detection is enabled, and whether it
+     * should output just the basic fields or the full set of
+     * fields. Value must be one of the
+     * android.statistics.info.availableFaceDetectModes.
+     * </p>
+     * @see #STATISTICS_FACE_DETECT_MODE_OFF
+     * @see #STATISTICS_FACE_DETECT_MODE_SIMPLE
+     * @see #STATISTICS_FACE_DETECT_MODE_FULL
+     */
+    public static final Key<Integer> STATISTICS_FACE_DETECT_MODE =
+            new Key<Integer>("android.statistics.faceDetectMode", int.class);
+
+    /**
+     * <p>
+     * List of unique IDs for detected
+     * faces
+     * </p>
+     * <p>
+     * Only available if faceDetectMode == FULL
+     * </p>
+     */
+    public static final Key<int[]> STATISTICS_FACE_IDS =
+            new Key<int[]>("android.statistics.faceIds", int[].class);
+
+    /**
+     * <p>
+     * List of landmarks for detected
+     * faces
+     * </p>
+     * <p>
+     * Only available if faceDetectMode == FULL
+     * </p>
+     */
+    public static final Key<int[]> STATISTICS_FACE_LANDMARKS =
+            new Key<int[]>("android.statistics.faceLandmarks", int[].class);
+
+    /**
+     * <p>
+     * List of the bounding rectangles for detected
+     * faces
+     * </p>
+     * <p>
+     * Only available if faceDetectMode != OFF
+     * </p>
+     */
+    public static final Key<android.graphics.Rect[]> STATISTICS_FACE_RECTANGLES =
+            new Key<android.graphics.Rect[]>("android.statistics.faceRectangles", android.graphics.Rect[].class);
+
+    /**
+     * <p>
+     * List of the face confidence scores for
+     * detected faces
+     * </p>
+     * <p>
+     * Only available if faceDetectMode != OFF
+     * </p>
+     */
+    public static final Key<byte[]> STATISTICS_FACE_SCORES =
+            new Key<byte[]>("android.statistics.faceScores", byte[].class);
+
+    /**
+     * <p>
+     * A low-resolution map of lens shading, per
+     * color channel
+     * </p>
+     * <p>
+     * Assume bilinear interpolation of map. The least
+     * shaded section of the image should have a gain factor
+     * of 1; all other sections should have gains above 1.
+     * the map should be on the order of 30-40 rows, and
+     * must be smaller than 64x64.
+     * </p>
+     */
+    public static final Key<float[]> STATISTICS_LENS_SHADING_MAP =
+            new Key<float[]>("android.statistics.lensShadingMap", float[].class);
+
+    /**
+     * <p>
+     * The best-fit color channel gains calculated
+     * by the HAL's statistics units for the current output frame
+     * </p>
+     * <p>
+     * This may be different than the gains used for this frame,
+     * since statistics processing on data from a new frame
+     * typically completes after the transform has already been
+     * applied to that frame.
+     * </p><p>
+     * The 4 channel gains are defined in Bayer domain,
+     * see android.colorCorrection.gains for details.
+     * </p>
+     */
+    public static final Key<float[]> STATISTICS_PREDICTED_COLOR_GAINS =
+            new Key<float[]>("android.statistics.predictedColorGains", float[].class);
+
+    /**
+     * <p>
+     * The best-fit color transform matrix estimate
+     * calculated by the HAL's statistics units for the current
+     * output frame
+     * </p>
+     * <p>
+     * The HAL must provide the estimate from its
+     * statistics unit on the white balance transforms to use
+     * for the next frame. These are the values the HAL believes
+     * are the best fit for the current output frame. This may
+     * be different than the transform used for this frame, since
+     * statistics processing on data from a new frame typically
+     * completes after the transform has already been applied to
+     * that frame.
+     * </p><p>
+     * These estimates must be provided for all frames, even if
+     * capture settings and color transforms are set by the application.
+     * </p>
+     */
+    public static final Key<Rational[]> STATISTICS_PREDICTED_COLOR_TRANSFORM =
+            new Key<Rational[]>("android.statistics.predictedColorTransform", Rational[].class);
+
+    /**
+     * <p>
+     * The HAL estimated scene illumination lighting
+     * frequency
+     * </p>
+     * <p>
+     * Report NONE if there doesn't appear to be flickering
+     * illumination
+     * </p>
+     * @see #STATISTICS_SCENE_FLICKER_NONE
+     * @see #STATISTICS_SCENE_FLICKER_50HZ
+     * @see #STATISTICS_SCENE_FLICKER_60HZ
+     */
+    public static final Key<Integer> STATISTICS_SCENE_FLICKER =
+            new Key<Integer>("android.statistics.sceneFlicker", int.class);
+
+    /**
+     * <p>
+     * Table mapping blue input values to output
+     * values
+     * </p>
+     */
+    public static final Key<Float> TONEMAP_CURVE_BLUE =
+            new Key<Float>("android.tonemap.curveBlue", float.class);
+
+    /**
+     * <p>
+     * Table mapping green input values to output
+     * values
+     * </p>
+     */
+    public static final Key<Float> TONEMAP_CURVE_GREEN =
+            new Key<Float>("android.tonemap.curveGreen", float.class);
+
+    /**
+     * <p>
+     * Table mapping red input values to output
+     * values
+     * </p>
+     * <p>
+     * .The input range must be monotonically increasing
+     * with N, and values between entries should be linearly
+     * interpolated. For example, if the array is: [0.0, 0.0,
+     * 0.3, 0.5, 1.0, 1.0], then the input->output mapping
+     * for a few sample points would be: 0 -> 0, 0.15 ->
+     * 0.25, 0.3 -> 0.5, 0.5 -> 0.64
+     * </p>
+     */
+    public static final Key<float[]> TONEMAP_CURVE_RED =
+            new Key<float[]>("android.tonemap.curveRed", float[].class);
+
+    /**
+     * @see #TONEMAP_MODE_CONTRAST_CURVE
+     * @see #TONEMAP_MODE_FAST
+     * @see #TONEMAP_MODE_HIGH_QUALITY
+     */
+    public static final Key<Integer> TONEMAP_MODE =
+            new Key<Integer>("android.tonemap.mode", int.class);
+
+    /**
+     * <p>
+     * This LED is nominally used to indicate to the user
+     * that the camera is powered on and may be streaming images back to the
+     * Application Processor. In certain rare circumstances, the OS may
+     * disable this when video is processed locally and not transmitted to
+     * any untrusted applications.
+     * </p><p>
+     * In particular, the LED *must* always be on when the data could be
+     * transmitted off the device. The LED *should* always be on whenever
+     * data is stored locally on the device.
+     * </p><p>
+     * The LED *may* be off if a trusted application is using the data that
+     * doesn't violate the above rules.
+     * </p>
+     *
+     * @hide
+     */
+    public static final Key<Boolean> LED_TRANSMIT =
+            new Key<Boolean>("android.led.transmit", boolean.class);
+
+    /**
+     * <p>
+     * Whether black-level compensation is locked
+     * to its current values, or is free to vary
+     * </p>
+     * <p>
+     * When set to ON, the values used for black-level
+     * compensation must not change until the lock is set to
+     * OFF
+     * </p><p>
+     * Since changes to certain capture parameters (such as
+     * exposure time) may require resetting of black level
+     * compensation, the HAL must report whether setting the
+     * black level lock was successful in the output result
+     * metadata.
+     * </p>
+     */
+    public static final Key<Boolean> BLACK_LEVEL_LOCK =
+            new Key<Boolean>("android.blackLevel.lock", boolean.class);
+
+    /*~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~
+     * End generated code
+     *~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~O@*/
 }
diff --git a/core/java/android/hardware/location/GeofenceHardware.java b/core/java/android/hardware/location/GeofenceHardware.java
index e67d0d7..21de9f5 100644
--- a/core/java/android/hardware/location/GeofenceHardware.java
+++ b/core/java/android/hardware/location/GeofenceHardware.java
@@ -15,16 +15,11 @@
  */
 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
@@ -52,7 +47,7 @@
     private IGeofenceHardware mService;
 
     // Hardware systems that do geofence monitoring.
-    static final int NUM_MONITORS = 1;
+    static final int NUM_MONITORS = 2;
 
     /**
      * Constant for geofence monitoring done by the GPS hardware.
@@ -60,6 +55,13 @@
     public static final int MONITORING_TYPE_GPS_HARDWARE = 0;
 
     /**
+     * Constant for geofence monitoring done by the Fused hardware.
+     *
+     * @hide
+     */
+    public static final int MONITORING_TYPE_FUSED_HARDWARE = 1;
+
+    /**
      * Constant to indiciate that the monitoring system is currently
      * available for monitoring geofences.
      */
@@ -124,8 +126,12 @@
      */
     public static final int GEOFENCE_FAILURE = 5;
 
-    static final int GPS_GEOFENCE_UNAVAILABLE = 1<<0L;
-    static final int GPS_GEOFENCE_AVAILABLE = 1<<1L;
+    /**
+     * The constant used to indicate that the operation failed due to insufficient memory.
+     *
+     * @hide
+     */
+    public static final int GEOFENCE_ERROR_INSUFFICIENT_MEMORY = 6;
 
     private HashMap<GeofenceHardwareCallback, GeofenceHardwareCallbackWrapper>
             mCallbacks = new HashMap<GeofenceHardwareCallback, GeofenceHardwareCallbackWrapper>();
diff --git a/core/java/android/hardware/location/GeofenceHardwareImpl.java b/core/java/android/hardware/location/GeofenceHardwareImpl.java
index 77e3143..eac6620 100644
--- a/core/java/android/hardware/location/GeofenceHardwareImpl.java
+++ b/core/java/android/hardware/location/GeofenceHardwareImpl.java
@@ -18,23 +18,21 @@
 
 import android.content.Context;
 import android.content.pm.PackageManager;
+import android.location.FusedBatchOptions;
+import android.location.IFusedGeofenceHardware;
 import android.location.IGpsGeofenceHardware;
 import android.location.Location;
 import android.location.LocationManager;
-import android.os.Binder;
-import android.os.Bundle;
 import android.os.Handler;
 import android.os.IBinder;
 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.
@@ -54,6 +52,7 @@
             new ArrayList[GeofenceHardware.NUM_MONITORS];
     private final ArrayList<Reaper> mReapers = new ArrayList<Reaper>();
 
+    private IFusedGeofenceHardware mFusedService;
     private IGpsGeofenceHardware mGpsService;
 
     private int[] mSupportedMonitorTypes = new int[GeofenceHardware.NUM_MONITORS];
@@ -67,7 +66,7 @@
     private static final int GEOFENCE_CALLBACK_BINDER_DIED = 6;
 
     // mCallbacksHandler message types
-    private static final int GPS_GEOFENCE_STATUS = 1;
+    private static final int GEOFENCE_STATUS = 1;
     private static final int CALLBACK_ADD = 2;
     private static final int CALLBACK_REMOVE = 3;
     private static final int MONITOR_CALLBACK_BINDER_DIED = 4;
@@ -91,16 +90,6 @@
     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);
@@ -113,6 +102,9 @@
         // Init everything to unsupported.
         setMonitorAvailability(GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE,
                 GeofenceHardware.MONITOR_UNSUPPORTED);
+        setMonitorAvailability(
+                GeofenceHardware.MONITORING_TYPE_FUSED_HARDWARE,
+                GeofenceHardware.MONITOR_UNSUPPORTED);
 
     }
 
@@ -147,6 +139,22 @@
         }
     }
 
+    private void updateFusedHardwareAvailability() {
+        boolean fusedSupported;
+        try {
+            fusedSupported = mFusedService.isSupported();
+        } catch(RemoteException e) {
+            Log.e(TAG, "RemoteException calling LocationManagerService");
+            fusedSupported = false;
+        }
+
+        if(fusedSupported) {
+            setMonitorAvailability(
+                    GeofenceHardware.MONITORING_TYPE_FUSED_HARDWARE,
+                    GeofenceHardware.MONITOR_CURRENTLY_AVAILABLE);
+        }
+    }
+
     public void setGpsHardwareGeofence(IGpsGeofenceHardware service) {
         if (mGpsService == null) {
             mGpsService = service;
@@ -159,12 +167,39 @@
         }
     }
 
+    public void setFusedGeofenceHardware(IFusedGeofenceHardware service) {
+        if(mFusedService == null) {
+            mFusedService = service;
+            updateFusedHardwareAvailability();
+        } else if(service == null) {
+            mFusedService = null;
+            Log.w(TAG, "Fused Geofence Hardware service seems to have crashed");
+        } else {
+            Log.e(TAG, "Error: FusedService being set again");
+        }
+    }
+
     public int[] getMonitoringTypes() {
+        boolean gpsSupported;
+        boolean fusedSupported;
         synchronized (mSupportedMonitorTypes) {
-            if (mSupportedMonitorTypes[GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE] !=
-                        GeofenceHardware.MONITOR_UNSUPPORTED) {
-                return new int[] {GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE};
+            gpsSupported = mSupportedMonitorTypes[GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE]
+                    != GeofenceHardware.MONITOR_UNSUPPORTED;
+            fusedSupported = mSupportedMonitorTypes[GeofenceHardware.MONITORING_TYPE_FUSED_HARDWARE]
+                    != GeofenceHardware.MONITOR_UNSUPPORTED;
+        }
+
+        if(gpsSupported) {
+            if(fusedSupported) {
+                return new int[] {
+                        GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE,
+                        GeofenceHardware.MONITORING_TYPE_FUSED_HARDWARE };
+            } else {
+                return new int[] { GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE };
             }
+        } else if (fusedSupported) {
+            return new int[] { GeofenceHardware.MONITORING_TYPE_FUSED_HARDWARE };
+        } else {
             return new int[0];
         }
     }
@@ -213,6 +248,30 @@
                     result = false;
                 }
                 break;
+            case GeofenceHardware.MONITORING_TYPE_FUSED_HARDWARE:
+                if(mFusedService == null) {
+                    return false;
+                }
+                GeofenceHardwareRequest request = GeofenceHardwareRequest.createCircularGeofence(
+                        latitude,
+                        longitude,
+                        radius);
+                request.setUnknownTimer(unknownTimer);
+                request.setNotificationResponsiveness(notificationResponsivenes);
+                request.setMonitorTransitions(monitorTransitions);
+                request.setLastTransition(lastTransition);
+
+                GeofenceHardwareRequestParcelable parcelableRequest =
+                        new GeofenceHardwareRequestParcelable(geofenceId, request);
+                try {
+                    mFusedService.addGeofences(
+                            new GeofenceHardwareRequestParcelable[] { parcelableRequest });
+                    result = true;
+                } catch(RemoteException e) {
+                    Log.e(TAG, "AddGeofence: RemoteException calling LocationManagerService");
+                    result = false;
+                }
+                break;
             default:
                 result = false;
         }
@@ -251,6 +310,18 @@
                     result = false;
                 }
                 break;
+            case GeofenceHardware.MONITORING_TYPE_FUSED_HARDWARE:
+                if(mFusedService == null) {
+                    return false;
+                }
+                try {
+                    mFusedService.removeGeofences(new int[] { geofenceId });
+                    result = true;
+                } catch(RemoteException e) {
+                    Log.e(TAG, "RemoveGeofence: RemoteException calling LocationManagerService");
+                    result = false;
+                }
+                break;
             default:
                 result = false;
         }
@@ -278,6 +349,18 @@
                     result = false;
                 }
                 break;
+            case GeofenceHardware.MONITORING_TYPE_FUSED_HARDWARE:
+                if(mFusedService == null) {
+                    return false;
+                }
+                try {
+                    mFusedService.pauseMonitoringGeofence(geofenceId);
+                    result = true;
+                } catch(RemoteException e) {
+                    Log.e(TAG, "PauseGeofence: RemoteException calling LocationManagerService");
+                    result = false;
+                }
+                break;
             default:
                 result = false;
         }
@@ -306,6 +389,18 @@
                     result = false;
                 }
                 break;
+            case GeofenceHardware.MONITORING_TYPE_FUSED_HARDWARE:
+                if(mFusedService == null) {
+                    return false;
+                }
+                try {
+                    mFusedService.resumeMonitoringGeofence(geofenceId, monitorTransition);
+                    result = true;
+                } catch(RemoteException e) {
+                    Log.e(TAG, "ResumeGeofence: RemoteException calling LocationManagerService");
+                    result = false;
+                }
+                break;
             default:
                 result = false;
         }
@@ -334,127 +429,106 @@
         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());
+    /**
+     * Used to report geofence transitions
+     */
+    public void reportGeofenceTransition(
+            int geofenceId,
+            Location location,
+            int transition,
+            long transitionTimestamp,
+            int monitoringType,
+            int sourcesUsed) {
+        if(location == null) {
+            Log.e(TAG, String.format("Invalid Geofence Transition: location=%p", location));
+            return;
         }
-        if ((flags & LOCATION_HAS_ALTITUDE) == LOCATION_HAS_ALTITUDE) {
-            location.setAltitude(altitude);
-        } else {
-            location.removeAltitude();
+        if(DEBUG) {
+            Log.d(
+                    TAG,
+                    "GeofenceTransition| " + location + ", transition:" + transition +
+                    ", transitionTimestamp:" + transitionTimestamp + ", monitoringType:" +
+                    monitoringType + ", sourcesUsed:" + sourcesUsed);
         }
-        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;
+
+        GeofenceTransition geofenceTransition = new GeofenceTransition(
+                geofenceId,
+                transition,
+                transitionTimestamp,
+                location,
+                monitoringType,
+                sourcesUsed);
+        acquireWakeLock();
+
+        Message message = mGeofenceHandler.obtainMessage(
+                GEOFENCE_TRANSITION_CALLBACK,
+                geofenceTransition);
+        message.sendToTarget();
     }
 
     /**
-     * called from GpsLocationProvider to report geofence transition
+     * Used to report Monitor status changes.
      */
-    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);
+    public void reportGeofenceMonitorStatus(
+            int monitoringType,
+            int monitoringStatus,
+            Location location,
+            int source) {
+        // TODO: use the source if needed in the future
+        setMonitorAvailability(monitoringType, monitoringStatus);
         acquireWakeLock();
-        Message m = mGeofenceHandler.obtainMessage(GEOFENCE_TRANSITION_CALLBACK, t);
-        mGeofenceHandler.sendMessage(m);
+        Message message = mCallbacksHandler.obtainMessage(GEOFENCE_STATUS, location);
+        message.arg1 = monitoringStatus;
+        message.arg2 = monitoringType;
+        message.sendToTarget();
     }
 
     /**
-     * called from GpsLocationProvider to report GPS status change.
+     * Internal generic status report function for Geofence operations.
+     *
+     * @param operation The operation to be reported as defined internally.
+     * @param geofenceId The id of the geofence the operation is related to.
+     * @param operationStatus The status of the operation as defined in GeofenceHardware class. This
+     *                        status is independent of the statuses reported by different HALs.
      */
-    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_AVAILABLE :
-                GeofenceHardware.MONITOR_CURRENTLY_UNAVAILABLE);
-        setMonitorAvailability(GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE, val);
-
+    private void reportGeofenceOperationStatus(int operation, int geofenceId, int operationStatus) {
         acquireWakeLock();
-        Message m = mCallbacksHandler.obtainMessage(GPS_GEOFENCE_STATUS, location);
-        m.arg1 = val;
-        mCallbacksHandler.sendMessage(m);
+        Message message = mGeofenceHandler.obtainMessage(operation);
+        message.arg1 = geofenceId;
+        message.arg2 = operationStatus;
+        message.sendToTarget();
     }
 
     /**
-     * called from GpsLocationProvider add geofence callback.
+     * Used to report the status of a Geofence Add operation.
      */
-    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);
+    public void reportGeofenceAddStatus(int geofenceId, int status) {
+        if(DEBUG) Log.d(TAG, "AddCallback| id:" + geofenceId + ", status:" + status);
+        reportGeofenceOperationStatus(ADD_GEOFENCE_CALLBACK, geofenceId, status);
     }
 
     /**
-     * called from GpsLocationProvider remove geofence callback.
+     * Used to report the status of a Geofence Remove operation.
      */
-    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);
+    public void reportGeofenceRemoveStatus(int geofenceId, int status) {
+        if(DEBUG) Log.d(TAG, "RemoveCallback| id:" + geofenceId + ", status:" + status);
+        reportGeofenceOperationStatus(REMOVE_GEOFENCE_CALLBACK, geofenceId, status);
     }
 
     /**
-     * called from GpsLocationProvider pause geofence callback.
+     * Used to report the status of a Geofence Pause operation.
      */
-    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);
+    public void reportGeofencePauseStatus(int geofenceId, int status) {
+        if(DEBUG) Log.d(TAG, "PauseCallbac| id:" + geofenceId + ", status" + status);
+        reportGeofenceOperationStatus(PAUSE_GEOFENCE_CALLBACK, geofenceId, status);
     }
 
     /**
-     * called from GpsLocationProvider resume geofence callback.
+     * Used to report the status of a Geofence Resume operation.
      */
-    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);
+    public void reportGeofenceResumeStatus(int geofenceId, int status) {
+        if(DEBUG) Log.d(TAG, "ResumeCallback| id:" + geofenceId + ", status:" + status);
+        reportGeofenceOperationStatus(RESUME_GEOFENCE_CALLBACK, geofenceId, status);
     }
 
     // All operations on mGeofences
@@ -539,7 +613,7 @@
                             callback.onGeofenceTransition(
                                     geofenceTransition.mGeofenceId, geofenceTransition.mTransition,
                                     geofenceTransition.mLocation, geofenceTransition.mTimestamp,
-                                    GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE);
+                                    geofenceTransition.mMonitoringType);
                         } catch (RemoteException e) {}
                     }
                     releaseWakeLock();
@@ -571,21 +645,20 @@
             IGeofenceHardwareMonitorCallback callback;
 
             switch (msg.what) {
-                case GPS_GEOFENCE_STATUS:
+                case GEOFENCE_STATUS:
                     Location location = (Location) msg.obj;
                     int val = msg.arg1;
+                    monitoringType = msg.arg2;
                     boolean available;
                     available = (val == GeofenceHardware.MONITOR_CURRENTLY_AVAILABLE ?
                             true : false);
-                    callbackList = mCallbacks[GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE];
+                    callbackList = mCallbacks[monitoringType];
                     if (callbackList != null) {
                         if (DEBUG) Log.d(TAG, "MonitoringSystemChangeCallback: GPS : " + available);
 
                         for (IGeofenceHardwareMonitorCallback c: callbackList) {
                             try {
-                                c.onMonitoringSystemChange(
-                                        GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE, available,
-                                        location);
+                                c.onMonitoringSystemChange(monitoringType, available, location);
                             } catch (RemoteException e) {}
                         }
                     }
@@ -666,12 +739,22 @@
         private int mGeofenceId, mTransition;
         private long mTimestamp;
         private Location mLocation;
+        private int mMonitoringType;
+        private int mSourcesUsed;
 
-        GeofenceTransition(int geofenceId, int transition, long timestamp, Location location) {
+        GeofenceTransition(
+                int geofenceId,
+                int transition,
+                long timestamp,
+                Location location,
+                int monitoringType,
+                int sourcesUsed) {
             mGeofenceId = geofenceId;
             mTransition = transition;
             mTimestamp = timestamp;
             mLocation = location;
+            mMonitoringType = monitoringType;
+            mSourcesUsed = sourcesUsed;
         }
     }
 
@@ -686,6 +769,8 @@
         switch (monitoringType) {
             case GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE:
                 return RESOLUTION_LEVEL_FINE;
+            case GeofenceHardware.MONITORING_TYPE_FUSED_HARDWARE:
+                return RESOLUTION_LEVEL_FINE;
         }
         return RESOLUTION_LEVEL_NONE;
     }
@@ -752,22 +837,4 @@
             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/GeofenceHardwareRequestParcelable.aidl b/core/java/android/hardware/location/GeofenceHardwareRequestParcelable.aidl
new file mode 100644
index 0000000..b599d44
--- /dev/null
+++ b/core/java/android/hardware/location/GeofenceHardwareRequestParcelable.aidl
@@ -0,0 +1,19 @@
+/*
+ * 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;
+
+parcelable GeofenceHardwareRequestParcelable;
diff --git a/core/java/android/hardware/location/GeofenceHardwareRequestParcelable.java b/core/java/android/hardware/location/GeofenceHardwareRequestParcelable.java
new file mode 100644
index 0000000..40e7fc4
--- /dev/null
+++ b/core/java/android/hardware/location/GeofenceHardwareRequestParcelable.java
@@ -0,0 +1,151 @@
+/*
+ * 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.os.Parcel;
+import android.os.Parcelable;
+import android.util.Log;
+
+/**
+ * Geofence Hardware Request used for internal location services communication.
+ *
+ * @hide
+ */
+public final class GeofenceHardwareRequestParcelable implements Parcelable {
+    private GeofenceHardwareRequest mRequest;
+    private int mId;
+
+    public GeofenceHardwareRequestParcelable(int id, GeofenceHardwareRequest request) {
+        mId = id;
+        mRequest = request;
+    }
+
+    /**
+     * Returns the id of this request.
+     */
+    public int getId() {
+        return mId;
+    }
+
+    /**
+     * Returns the latitude of this geofence.
+     */
+    public double getLatitude() {
+        return mRequest.getLatitude();
+    }
+
+    /**
+     * Returns the longitude of this geofence.
+     */
+    public double getLongitude() {
+        return mRequest.getLongitude();
+    }
+
+    /**
+     * Returns the radius of this geofence.
+     */
+    public double getRadius() {
+        return mRequest.getRadius();
+    }
+
+    /**
+     * Returns transitions monitored for this geofence.
+     */
+    public int getMonitorTransitions() {
+        return mRequest.getMonitorTransitions();
+    }
+
+    /**
+     * Returns the unknownTimer of this geofence.
+     */
+    public int getUnknownTimer() {
+        return mRequest.getUnknownTimer();
+    }
+
+    /**
+     * Returns the notification responsiveness of this geofence.
+     */
+    public int getNotificationResponsiveness() {
+        return mRequest.getNotificationResponsiveness();
+    }
+
+    /**
+     * Returns the last transition of this geofence.
+     */
+    public int getLastTransition() {
+        return mRequest.getLastTransition();
+    }
+
+    /**
+     * Returns the type of the geofence for the current request.
+     */
+    int getType() {
+        return mRequest.getType();
+    }
+
+    /**
+     * Method definitions to support Parcelable operations.
+     */
+    public static final Parcelable.Creator<GeofenceHardwareRequestParcelable> CREATOR = 
+            new Parcelable.Creator<GeofenceHardwareRequestParcelable>() {
+        @Override
+        public GeofenceHardwareRequestParcelable createFromParcel(Parcel parcel) {
+            int geofenceType = parcel.readInt();
+            if(geofenceType != GeofenceHardwareRequest.GEOFENCE_TYPE_CIRCLE) {
+                Log.e(
+                        "GeofenceHardwareRequest",
+                        String.format("Invalid Geofence type: %d", geofenceType));
+                return null;
+            }
+
+            GeofenceHardwareRequest request = GeofenceHardwareRequest.createCircularGeofence(
+                    parcel.readDouble(),
+                    parcel.readDouble(),
+                    parcel.readDouble());
+            request.setLastTransition(parcel.readInt());
+            request.setMonitorTransitions(parcel.readInt());
+            request.setUnknownTimer(parcel.readInt());
+            request.setNotificationResponsiveness(parcel.readInt());
+            
+            int id = parcel.readInt();
+            return new GeofenceHardwareRequestParcelable(id, request);
+        }
+
+        @Override
+        public GeofenceHardwareRequestParcelable[] newArray(int size) {
+            return new GeofenceHardwareRequestParcelable[size];
+        }
+    };
+
+    @Override
+    public int describeContents() {
+        return 0;
+    }
+
+    @Override
+    public void writeToParcel(Parcel parcel, int flags) {
+        parcel.writeInt(getType());
+        parcel.writeDouble(getLatitude());
+        parcel.writeDouble(getLongitude());
+        parcel.writeDouble(getRadius());
+        parcel.writeInt(getLastTransition());
+        parcel.writeInt(getMonitorTransitions());
+        parcel.writeInt(getUnknownTimer());
+        parcel.writeInt(getNotificationResponsiveness());
+        parcel.writeInt(getId());
+    }
+}
diff --git a/core/java/android/hardware/location/GeofenceHardwareService.java b/core/java/android/hardware/location/GeofenceHardwareService.java
index 3bc70ee..fb238bd 100644
--- a/core/java/android/hardware/location/GeofenceHardwareService.java
+++ b/core/java/android/hardware/location/GeofenceHardwareService.java
@@ -20,6 +20,7 @@
 import android.app.Service;
 import android.content.Context;
 import android.content.Intent;
+import android.location.IFusedGeofenceHardware;
 import android.location.IGpsGeofenceHardware;
 import android.os.Binder;
 import android.os.IBinder;
@@ -68,6 +69,10 @@
             mGeofenceHardwareImpl.setGpsHardwareGeofence(service);
         }
 
+        public void setFusedGeofenceHardware(IFusedGeofenceHardware service) {
+            mGeofenceHardwareImpl.setFusedGeofenceHardware(service);
+        }
+
         public int[] getMonitoringTypes() {
             mContext.enforceCallingPermission(Manifest.permission.LOCATION_HARDWARE,
                     "Location Hardware permission not granted to access hardware geofence");
diff --git a/core/java/android/hardware/location/IGeofenceHardware.aidl b/core/java/android/hardware/location/IGeofenceHardware.aidl
index 6900070..8900166 100644
--- a/core/java/android/hardware/location/IGeofenceHardware.aidl
+++ b/core/java/android/hardware/location/IGeofenceHardware.aidl
@@ -16,6 +16,7 @@
 
 package android.hardware.location;
 
+import android.location.IFusedGeofenceHardware;
 import android.location.IGpsGeofenceHardware;
 import android.hardware.location.IGeofenceHardwareCallback;
 import android.hardware.location.IGeofenceHardwareMonitorCallback;
@@ -23,6 +24,7 @@
 /** @hide */
 interface IGeofenceHardware {
     void setGpsGeofenceHardware(in IGpsGeofenceHardware service);
+    void setFusedGeofenceHardware(in IFusedGeofenceHardware service);
     int[] getMonitoringTypes();
     int getStatusOfMonitoringType(int monitoringType);
     boolean addCircularFence(int id,  int monitoringType, double lat, double longitude,
diff --git a/core/java/android/text/format/DateUtils.java b/core/java/android/text/format/DateUtils.java
index cba350f..2b805a9 100644
--- a/core/java/android/text/format/DateUtils.java
+++ b/core/java/android/text/format/DateUtils.java
@@ -815,7 +815,13 @@
      * @return the formatter with the formatted date/time range appended to the string buffer.
      */
     public static Formatter formatDateRange(Context context, Formatter formatter, long startMillis,
-            long endMillis, int flags, String timeZone) {
+                                            long endMillis, int flags, String timeZone) {
+        // icu4c will fall back to the locale's preferred 12/24 format,
+        // but we want to fall back to the user's preference.
+        if ((flags & (FORMAT_12HOUR | FORMAT_24HOUR)) == 0) {
+            flags |= DateFormat.is24HourFormat(context) ? FORMAT_24HOUR : FORMAT_12HOUR;
+        }
+
         String range = DateIntervalFormat.formatDateRange(startMillis, endMillis, flags, timeZone);
         try {
             formatter.out().append(range);
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index d22a468..747e8ea 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -2379,7 +2379,7 @@
      * when hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the
      * navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} instead of having the system
      * clear these flags upon interaction.  The system may compensate by temporarily overlaying
-     * transparent system bars while also delivering the event.
+     * semi-transparent system bars while also delivering the event.
      */
     public static final int SYSTEM_UI_FLAG_ALLOW_TRANSIENT = 0x00000800;
 
@@ -15444,6 +15444,90 @@
     }
 
     /**
+     * Transforms a motion event from view-local coordinates to on-screen
+     * coordinates.
+     *
+     * @param ev the view-local motion event
+     * @return false if the transformation could not be applied
+     * @hide
+     */
+    public boolean toGlobalMotionEvent(MotionEvent ev) {
+        final AttachInfo info = mAttachInfo;
+        if (info == null) {
+            return false;
+        }
+
+        transformMotionEventToGlobal(ev);
+        ev.offsetLocation(info.mWindowLeft, info.mWindowTop);
+        return true;
+    }
+
+    /**
+     * Transforms a motion event from on-screen coordinates to view-local
+     * coordinates.
+     *
+     * @param ev the on-screen motion event
+     * @return false if the transformation could not be applied
+     * @hide
+     */
+    public boolean toLocalMotionEvent(MotionEvent ev) {
+        final AttachInfo info = mAttachInfo;
+        if (info == null) {
+            return false;
+        }
+
+        ev.offsetLocation(-info.mWindowLeft, -info.mWindowTop);
+        transformMotionEventToLocal(ev);
+        return true;
+    }
+
+    /**
+     * Recursive helper method that applies transformations in post-order.
+     *
+     * @param ev the on-screen motion event
+     */
+    private void transformMotionEventToLocal(MotionEvent ev) {
+        final ViewParent parent = mParent;
+        if (parent instanceof View) {
+            final View vp = (View) parent;
+            vp.transformMotionEventToLocal(ev);
+            ev.offsetLocation(vp.mScrollX, vp.mScrollY);
+        } else if (parent instanceof ViewRootImpl) {
+            final ViewRootImpl vr = (ViewRootImpl) parent;
+            ev.offsetLocation(0, vr.mCurScrollY);
+        }
+
+        ev.offsetLocation(-mLeft, -mTop);
+
+        if (!hasIdentityMatrix()) {
+            ev.transform(getInverseMatrix());
+        }
+    }
+
+    /**
+     * Recursive helper method that applies transformations in pre-order.
+     *
+     * @param ev the on-screen motion event
+     */
+    private void transformMotionEventToGlobal(MotionEvent ev) {
+        if (!hasIdentityMatrix()) {
+            ev.transform(getMatrix());
+        }
+
+        ev.offsetLocation(mLeft, mTop);
+
+        final ViewParent parent = mParent;
+        if (parent instanceof View) {
+            final View vp = (View) parent;
+            ev.offsetLocation(-vp.mScrollX, -vp.mScrollY);
+            vp.transformMotionEventToGlobal(ev);
+        } else if (parent instanceof ViewRootImpl) {
+            final ViewRootImpl vr = (ViewRootImpl) parent;
+            ev.offsetLocation(0, -vr.mCurScrollY);
+        }
+    }
+
+    /**
      * <p>Computes the coordinates of this view on the screen. The argument
      * must be an array of two integers. After the method returns, the array
      * contains the x and y location in that order.</p>
@@ -16548,7 +16632,9 @@
      * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
      * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
      * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
-     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
+     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_ALLOW_TRANSIENT},
+     * {@link #SYSTEM_UI_FLAG_TRANSPARENT_STATUS},
+     * and {@link #SYSTEM_UI_FLAG_TRANSPARENT_NAVIGATION}.
      */
     public void setSystemUiVisibility(int visibility) {
         if (visibility != mSystemUiVisibility) {
@@ -16560,11 +16646,13 @@
     }
 
     /**
-     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
+     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
      * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
      * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
      * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
-     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
+     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_ALLOW_TRANSIENT},
+     * {@link #SYSTEM_UI_FLAG_TRANSPARENT_STATUS},
+     * and {@link #SYSTEM_UI_FLAG_TRANSPARENT_NAVIGATION}.
      */
     public int getSystemUiVisibility() {
         return mSystemUiVisibility;
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index 9c21f0d..a315546 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -359,9 +359,7 @@
                             mDrawableRight = mDrawableStart;
                             mDrawableSizeRight = mDrawableSizeStart;
                             mDrawableHeightRight = mDrawableHeightStart;
-                        }
 
-                        if (mOverride) {
                             mDrawableLeft = mDrawableEnd;
                             mDrawableSizeLeft = mDrawableSizeEnd;
                             mDrawableHeightLeft = mDrawableHeightEnd;
@@ -374,9 +372,7 @@
                             mDrawableLeft = mDrawableStart;
                             mDrawableSizeLeft = mDrawableSizeStart;
                             mDrawableHeightLeft = mDrawableHeightStart;
-                        }
 
-                        if (mOverride) {
                             mDrawableRight = mDrawableEnd;
                             mDrawableSizeRight = mDrawableSizeEnd;
                             mDrawableHeightRight = mDrawableHeightEnd;
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index d106cf2..1363e3c 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -1077,15 +1077,15 @@
     <!-- Allows an application to read from external storage.
          <p>Any app that declares the {@link #WRITE_EXTERNAL_STORAGE} permission is implicitly
          granted this permission.</p>
-         <p>Currently, this permission is not enforced and all apps still have access to read from
-         external storage without this permission. That will change in a future release and apps
-         will require this permission to read from external storage. So if your
-         app reads from the external storage, you should add this permission to your app now
-         to ensure that it continues to work on future versions of Android.</p>
-         <p>You can test your app with the permission enforced by either running your app on the
-         Android Emulator when running Android 4.1 or higher, or enabling <em>Protect USB
+         <p>This permission is enforced starting in API level 19.  Before API level 19, this
+         permission is not enforced and all apps still have access to read from external storage.
+         You can test your app with the permission enforced by enabling <em>Protect USB
          storage</em> under Developer options in the Settings app on a device running Android 4.1 or
          higher.</p>
+         <p>Also starting in API level 19, this permission is <em>not</em> required to
+         read/write files in your application-specific directories returned by
+         {@link android.content.Context#getExternalFilesDir} and
+         {@link android.content.Context#getExternalCacheDir}.
          <p class="note"><strong>Note:</strong> If <em>both</em> your <a
          href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min">{@code
          minSdkVersion}</a> and <a
@@ -1108,7 +1108,11 @@
          targetSdkVersion}</a> values are set to 3 or lower, the system implicitly
          grants your app this permission. If you don't need this permission, be sure your <a
          href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#target">{@code
-         targetSdkVersion}</a> is 4 or higher. -->
+         targetSdkVersion}</a> is 4 or higher.
+         <p>Starting in API level 19, this permission is <em>not</em> required to
+         read/write files in your application-specific directories returned by
+         {@link android.content.Context#getExternalFilesDir} and
+         {@link android.content.Context#getExternalCacheDir}. -->
     <permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
         android:permissionGroup="android.permission-group.STORAGE"
         android:label="@string/permlab_sdcardWrite"
diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml
index 721bc3f..03e9045 100644
--- a/core/res/res/values/attrs.xml
+++ b/core/res/res/values/attrs.xml
@@ -5728,6 +5728,25 @@
     <declare-styleable name="SizeAdaptiveLayout" />
 
     <!-- =============================== -->
+    <!-- Location package class attributes -->
+    <!-- =============================== -->
+    <eat-comment />
+
+    <!-- Use <code>injected-location-setting</code> as the root tag of the XML resource that
+         describes an injected "Location services" setting. Note that the status value (subtitle)
+         for the setting is specified dynamically by a subclass of SettingInjectorService.
+     -->
+    <declare-styleable name="InjectedLocationSetting">
+        <!-- The user-visible name (title) of the setting. -->
+        <attr name="label"/>
+        <!-- The icon for the apps covered by the setting. Typically a generic icon for the
+             developer. -->
+        <attr name="icon"/>
+        <!-- The activity to launch when the setting is clicked on. -->
+        <attr name="settingsActivity"/>
+    </declare-styleable>
+
+    <!-- =============================== -->
     <!-- LockPatternView class attributes -->
     <!-- =============================== -->
     <eat-comment />
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index 4a472fc..400e892 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -353,6 +353,9 @@
          Default value is 2 minutes. -->
     <integer translatable="false" name="config_wifi_driver_stop_delay">120000</integer>
 
+    <!-- Wifi driver supports batched scan -->
+    <bool translatable="false" name="config_wifi_batched_scan_supported">false</bool>
+
     <!-- Flag indicating whether the we should enable the automatic brightness in Settings.
          Software implementation will be used if config_hardware_auto_brightness_available is not set -->
     <bool name="config_automatic_brightness_available">false</bool>
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index cd0c872..14ae1e6 100755
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -281,7 +281,8 @@
   <java-symbol type="bool" name="config_speed_up_audio_on_mt_calls" />
   <java-symbol type="bool" name="config_useFixedVolume" />
   <java-symbol type="bool" name="config_forceDefaultOrientation" />
-  
+  <java-symbol type="bool" name="config_wifi_batched_scan_supported" />
+
   <java-symbol type="integer" name="config_cursorWindowSize" />
   <java-symbol type="integer" name="config_extraFreeKbytesAdjust" />
   <java-symbol type="integer" name="config_extraFreeKbytesAbsolute" />
diff --git a/data/etc/platform.xml b/data/etc/platform.xml
index ec8e7ea..1f38ddb 100644
--- a/data/etc/platform.xml
+++ b/data/etc/platform.xml
@@ -63,9 +63,16 @@
     </permission>
 
     <permission name="android.permission.WRITE_EXTERNAL_STORAGE" >
+        <group gid="sdcard_r" />
         <group gid="sdcard_rw" />
     </permission>
 
+    <permission name="android.permission.ACCESS_ALL_EXTERNAL_STORAGE" >
+        <group gid="sdcard_r" />
+        <group gid="sdcard_rw" />
+        <group gid="sdcard_all" />
+    </permission>
+
     <permission name="android.permission.WRITE_MEDIA_STORAGE" >
         <group gid="media_rw" />
     </permission>
diff --git a/docs/downloads/design/Android_Design_Downloads_20130814.zip b/docs/downloads/design/Android_Design_Downloads_20130814.zip
new file mode 100644
index 0000000..bd290003
--- /dev/null
+++ b/docs/downloads/design/Android_Design_Downloads_20130814.zip
Binary files differ
diff --git a/docs/html/design/downloads/index.jd b/docs/html/design/downloads/index.jd
index 00f4467..b13ba62 100644
--- a/docs/html/design/downloads/index.jd
+++ b/docs/html/design/downloads/index.jd
@@ -4,8 +4,10 @@
 <div class="layout-content-row">
   <div class="layout-content-col span-9">
 
-<p>Want everything? We've bundled all the downloads available on Android Design into a single ZIP file.
-You can also download individual files listed below.</p>
+<p>Want everything? We've bundled all the downloads available on Android Design, except for the
+  <a href="#roboto">Roboto</a> font family, into a single ZIP file. You can also download
+  individual files listed below.</p>
+
 <p>You may use these materials without restriction in your apps and to develop your apps.</p>
 
   </div>
@@ -13,7 +15,7 @@
 
 <p>
   <a class="download-button" onClick="_gaq.push(['_trackEvent', 'Design', 'Download', 'All Design Assets']);"
-    href="{@docRoot}downloads/design/Android_Design_Downloads_20120823.zip">Download All</a>
+    href="{@docRoot}downloads/design/Android_Design_Downloads_20130814.zip">Download All</a>
 </p>
 
   </div>
@@ -83,10 +85,12 @@
 <div class="layout-content-row">
   <div class="layout-content-col span-5">
 
-<h4>Roboto</h4>
+<h4 id="roboto">Roboto</h4>
 <p>Ice Cream Sandwich introduced a new type family named Roboto, created specifically for the
 requirements of UI and high-resolution screens.</p>
-<p><a href="{@docRoot}design/style/typography.html#actionbar">More on Roboto</a></p>
+<p><a href="{@docRoot}design/style/typography.html">More on Roboto</a></p>
+<p><a href="http://www.google.com/fonts/specimen/Roboto" class="external-link">Roboto on Google Fonts</a></p>
+<p><a href="http://www.google.com/fonts/specimen/Roboto+Condensed" class="external-link">Roboto Condensed on Google Fonts</a></p>
 
   </div>
   <div class="layout-content-col span-4">
@@ -98,7 +102,7 @@
 
 <p>
   <a class="download-button"  onClick="_gaq.push(['_trackEvent', 'Design', 'Download', 'Roboto ZIP']);"
-    href="{@docRoot}downloads/design/Roboto_Hinted_20120823.zip">Roboto</a>
+    href="https://github.com/google/roboto/archive/latest-hinted.zip">Roboto</a>
   <a class="download-button"  onClick="_gaq.push(['_trackEvent', 'Design', 'Download', 'Roboto Specemin Book']);"
     href="{@docRoot}downloads/design/Roboto_Specimen_Book_20111129.pdf">Specimen Book</a>
 </p>
diff --git a/docs/html/design/media/typography_alphas.png b/docs/html/design/media/typography_alphas.png
deleted file mode 100644
index 4b53bd0..0000000
--- a/docs/html/design/media/typography_alphas.png
+++ /dev/null
Binary files differ
diff --git a/docs/html/design/media/typography_variants.png b/docs/html/design/media/typography_variants.png
new file mode 100644
index 0000000..9b49b20
--- /dev/null
+++ b/docs/html/design/media/typography_variants.png
Binary files differ
diff --git a/docs/html/design/media/typography_variants@2x.png b/docs/html/design/media/typography_variants@2x.png
new file mode 100644
index 0000000..13e7c4f
--- /dev/null
+++ b/docs/html/design/media/typography_variants@2x.png
Binary files differ
diff --git a/docs/html/design/style/typography.jd b/docs/html/design/style/typography.jd
index 114d13b..0d681ab 100644
--- a/docs/html/design/style/typography.jd
+++ b/docs/html/design/style/typography.jd
@@ -10,17 +10,25 @@
   </div>
   <div class="layout-content-col span-5">
 
+<p>
+  <a class="download-button"  onClick="_gaq.push(['_trackEvent', 'Design', 'Download', 'Roboto ZIP']);"
+    href="https://github.com/google/roboto/archive/latest-hinted.zip">Download Roboto</a>
+</p>
+
 <p>The Android design language relies on traditional typographic tools such as scale, space, rhythm,
 and alignment with an underlying grid. Successful deployment of these tools is essential to help
 users quickly understand a screen of information. To support such use of typography, Ice Cream
-Sandwich introduced a new type family named Roboto, created specifically for the requirements of UI
-and high-resolution screens. The current TextView framework supports regular, bold, italic, and bold
-italic weights by default.</p>
+Sandwich introduced a new type family named
+<a href="http://www.google.com/fonts/specimen/Roboto" class="external-link">Roboto</a>, created
+specifically for the requirements of UI and high-resolution screens.</p>
 
-    <img src="{@docRoot}design/media/typography_alphas.png">
+<p>The current {@link android.widget.TextView} framework offers Roboto in thin, light, regular and bold
+weights, along with an italic style for each weight. The framework also offers the
+<a href="http://www.google.com/fonts/specimen/Roboto+Condensed" class="external-link">Roboto Condensed</a>
+variant in regular and bold weights, along with an italic style for each weight.</p>
 
-<p><a onClick="_gaq.push(['_trackEvent', 'Design', 'Download', 'Roboto ZIP (@typography page)']);"
-      href="{@docRoot}downloads/design/Roboto_Hinted_20120823.zip">Download Roboto</a></p>
+    <img src="{@docRoot}design/media/typography_variants@2x.png" width="220">
+
 <p><a onClick="_gaq.push(['_trackEvent', 'Design', 'Download', 'Roboto Specimen Booke (@typography page)']);"
       href="{@docRoot}downloads/design/Roboto_Specimen_Book_20111129.pdf">Specimen Book</a></p>
 
diff --git a/docs/html/google/gcm/adv.jd b/docs/html/google/gcm/adv.jd
index 567b12c..1360624 100644
--- a/docs/html/google/gcm/adv.jd
+++ b/docs/html/google/gcm/adv.jd
@@ -22,12 +22,7 @@
   </ol>
 </li>
 <li><a href="#retry">Automatic Retry Using Exponential Back-Off</a></li>
-<li><a href="#unreg">Unregistration</a>
-  <ol>
-    <li><a href="#unreg-why">Why you should rarely unregister</a></li>
-    <li><a href="#unreg-how">How unregistration works</a></li>
-  </ol>
-</li>
+<li><a href="#unreg">How Unregistration Works</a></li>
 <li><a href="#collapsible">Send-to-Sync vs. Messages with Payload</a>
   <ol>
     <li><a href="#s2s">Send-to-sync messages</a></li>
@@ -36,8 +31,7 @@
     </ol>
 </li>
 <li><a href="#ttl">Setting an Expiration Date for a Message</a> </li>
-<li><a href="#throttling"></a><a href="#multi-senders">Receiving Messages from
-Multiple Senders</a></li>
+<li><a href="#throttling"></a><a href="#multi-senders">Receiving Messages from Multiple Senders</a></li>
 </ol>
 
 </div>
@@ -48,56 +42,17 @@
 
 
 <h2 id="msg-lifetime">Lifetime of a Message</h2>
-<p>When a 3rd-party server posts a message to GCM and receives a message ID back,
-it does not mean that the message was already delivered to the device. Rather, it
-means that it was accepted for delivery. What happens to the message after it is
-accepted depends on many factors.</p>
-
-<p>In the best-case scenario, if the device is connected to GCM, the screen is on,
-and there are no throttling restrictions (see <a href="#throttling">Throttling</a>),
-the message will be delivered right away.</p>
-
+<p>When a 3rd-party server posts a message to GCM and receives a message ID back, it does not mean that the message was already delivered to the device. Rather, it means that it was accepted for delivery. What happens to the message after it is accepted depends on many factors.</p>
+<p>In the best-case scenario, if the device is connected to GCM, the screen is on, and there are no throttling restrictions (see <a href="#throttling">Throttling</a>), the message will be delivered right away.</p>
 <p>If the device is connected but idle, the message will still be
-delivered right away unless the <code>delay_while_idle</code> flag is set to true.
-Otherwise, it will be stored in the GCM servers until the device is awake. And
-that's where the <code>collapse_key</code> flag plays a role: if there is already
-a message with the same collapse key (and registration ID) stored and waiting for
-delivery, the old message will be discarded and the new message will take its place
-(that is, the old message will be collapsed by the new one). However, if the collapse
-key is not set, both the new and old messages are stored for future delivery.
-Collapsible messages are also called <a href="#s2s">send-to-sync messages</a>.</p>
+delivered right away unless the <code>delay_while_idle</code> flag is set to true. Otherwise, it will be stored in the GCM servers until the device is awake. And that's where the <code>collapse_key</code> flag plays a role: if there is already a message with the same collapse key (and registration ID) stored and waiting for delivery, the old message will be discarded and the new message will take its place (that is, the old message will be collapsed by the new one). However, if the collapse key is not set, both the new and old messages are stored for future delivery.</p>
 
-<p class="note"><strong>Note:</strong> There is a limit on how many messages can
-be stored without collapsing. That limit is currently 100. If the limit is reached,
-all stored messages are discarded. Then when the device is back online, it receives
-a special message indicating that the limit was reached. The application can then
-handle the situation properly, typically by requesting a full sync.
-<br><br>
-Likewise, there is a limit on how many <code>collapse_key</code>s you can have for
-a particular device. GCM allows a maximum of 4 different collapse keys to be used
-by the GCM server per device
-any given time. In other words, the GCM server can simultaneously store 4 different
-send-to-sync messages, each with a different collapse key. If you exceed this number
-GCM will only keep 4 collapse keys, with no guarantees about which ones they will be.
-See <a href="#s2s">Send-to-sync messages</a> for more information.
-</p>
+<p class="note"><strong>Note:</strong> There is a limit on how many messages can be stored without collapsing. That limit is currently 100. If the limit is reached, all stored messages are discarded. Then when the device is back online, it receives a special message indicating that the limit was reached. The application can then handle the situation properly, typically by requesting a full sync.</p>
 
-<p>If the device is not connected to GCM, the message will be stored until a
-connection is established (again respecting the collapse key rules). When a connection
-is established, GCM will deliver all pending messages to the device, regardless of
-the <code>delay_while_idle</code> flag. If the device never gets connected again
-(for instance, if it was factory reset), the message will eventually time out and
-be discarded from GCM storage. The default timeout is 4 weeks, unless the
-<code>time_to_live</code> flag is set.</p>
+<p>If the device is not connected to GCM, the message will be stored until a connection is established (again respecting the collapse key rules). When a connection is established, GCM will deliver all pending messages to the device, regardless of the <code>delay_while_idle</code> flag. If the device never gets connected again (for instance, if it was factory reset), the message will eventually time out and be discarded from GCM storage. The default timeout is 4 weeks, unless the <code>time_to_live</code> flag is set.</p>
 
-<p>Finally, when GCM attempts to deliver a message to the device and the
-application was uninstalled, GCM will discard that message right away and
-invalidate the registration ID. Future attempts to send a message to that device
-will get a <code>NotRegistered</code> error. See <a href="#unreg">
-How Unregistration Works</a> for more information.</p>
-<p>Although is not possible to track the status of each individual message, the
-Google APIs Console stats are broken down by messages sent to device, messages
-collapsed, and messages waiting for delivery.</p>
+<p>Finally, when GCM attempts to deliver a message to the device and the application was uninstalled, GCM will discard that message right away and invalidate the registration ID. Future attempts to send a message to that device will get a <code>NotRegistered</code> error. See <a href="#unreg">How Unregistration Works</a> for more information.</p>
+<p>Although is not possible to track the status of each individual message, the Google APIs Console stats are broken down by messages sent to device, messages collapsed, and messages waiting for delivery.</p>
 
 <h2 id="throttling">Throttling</h2>
 <p>To prevent abuse (such as sending a flood of messages to a device) and
@@ -119,112 +74,107 @@
 efficiency reasons.</p>
 
 <h2 id="reg-state">Keeping the Registration State in Sync</h2>
-<p>Whenever the application registers as described in
-<a href="{@docRoot}google/gcm/client.html">Implementing GCM Client</a>,
-it should save the registration ID for future use, pass it to the
-3rd-party server to complete the registration, and keep track of
-whether the server completed the registration. If the server fails
-to complete the registration, it should try again or unregister from GCM.</p>
-
+<p>Whenever the application receives a <code>com.google.android.c2dm.intent.REGISTRATION</code> intent with a <code>registration_id</code> extra, it should save the ID for future use, pass it to the 3rd-party server to complete the registration, and keep track of whether the server completed the registration. If the server fails to complete the registration, it should try again or unregister from GCM.</p>
 <p>There are also two other scenarios that require special care:</p>
 <ul>
   <li>Application update</li>
   <li>Backup and restore
   </li>
 </ul>
-<p>When an application is updated, it should invalidate its existing registration
-ID, as it is not guaranteed to work with the new version.  Because there is no
-lifecycle method called when the application is updated, the best way to achieve
-this validation is by storing the current application version when a registration
-ID is stored. Then when the application is started, compare the stored value with
-the current application version. If they do not match, invalidate the stored data
-and start the registration process again.</p>
+<p>When an application is updated, it should invalidate its existing registration ID, as it is not guaranteed to work with the new version.  Because there is no lifecycle method called when the application is updated, the best way to achieve this validation is by storing the current application version when a registration ID is stored. Then when the application is started, compare the stored value with the current application version. If they do not match, invalidate the stored data and start the registration process again.</p>
 
-<p>Similarly, you should not save the registration ID when an application is
-backed up. This is because the registration ID could become invalid by the time
-the application is restored, which would put the application in an invalid state
-(that is, the application thinks it is registered, but the server and GCM do not
-store that registration ID anymore&mdash;thus the application will not get more
-messages).</p>
+<p>Similarly, you should not save the registration ID when an application is backed up. This is because the registration ID could become invalid by the time the application is restored, which would put the application in an invalid state  (that is, the application thinks it is registered, but the server and GCM do not store that registration ID anymore&mdash;thus the application will not get more messages).</p>
 <h3 id="canonical">Canonical IDs</h3>
-<p>On the server side, as long as the application is behaving well, everything
-should work normally. However, if a bug in the application triggers multiple
-registrations for the same device, it can be hard to reconcile state and you might
-end up with duplicate messages.</p>
-<p>GCM provides a facility called &quot;canonical registration IDs&quot; to easily
-recover from these situations. A canonical registration ID is defined to be the ID
-of the last registration requested by your application. This is the ID that the
-server should use when sending messages to the device.</p>
-<p>If later on you try to send a message using a different registration ID, GCM
-will process the request as usual, but it will include the canonical registration
-ID in the <code>registration_id</code> field of the response. Make sure to replace
-the registration ID stored in your server with this canonical ID, as eventually
-the ID you're using will stop working.</p>
+<p>On the server side, as long as the application is behaving well, everything should work normally. However, if a bug in the application triggers multiple registrations for the same device, it can be hard to reconcile state and you might end up with duplicate messages.</p>
+<p>GCM provides a facility called &quot;canonical registration IDs&quot; to easily recover from these situations. A canonical registration ID is defined to be the ID of the last registration requested by your application. This is the ID that the server should use when sending messages to the device.</p>
+<p>If later on you try to send a message using a different registration ID, GCM will process the request as usual, but it will include the canonical registration ID in the <code>registration_id</code> field of the response. Make sure to replace the registration ID stored in your server with this canonical ID, as eventually the ID you're using will stop working.</p>
 
 <h2 id="retry">Automatic Retry Using Exponential Back-Off</h2>
 
-<p>When registration or unregistration fails, the app should retry the failed operation.</p>
-<p>In the simplest case, if your application attempts to register and GCM is not a
-fundamental part of the application, the application could simply ignore the error
-and try to register again the next time it starts. Otherwise, it should retry the
-previous operation using exponential back-off. In exponential back-off, each time
-there is a failure, it should wait twice the previous amount of time before trying
-again. If the register (or unregister) operation was synchronous, it could be retried
-in a simple loop. However, since it is asynchronous, the best approach is to schedule
-a {@link android.app.PendingIntent} to retry the operation.
+<p>When the application receives a <code>com.google.android.c2dm.intent.REGISTRATION</code> intent with the <code>error</code> extra set as <code>SERVICE_NOT_AVAILABLE</code>, it should retry the failed operation (register or unregister).</p>
+<p>In the simplest case, if your application just calls <code>register</code> and GCM is not a fundamental part of the application, the application could simply ignore the error and try to register again the next time it starts. Otherwise, it should retry the previous operation using exponential back-off. In exponential back-off, each time there is a failure, it should wait twice the previous amount of time before trying again. If the register (or unregister) operation was synchronous, it could be retried in a simple loop. However, since it is asynchronous, the best approach is to schedule a pending intent to retry the operation. The following steps describe how to implement this in the <code>MyIntentService</code> example used above:</p>
+<ol>
+  <li> Create a random token to verify the origin of the retry intent:
 
-<h2 id="unreg">Unregistration</h2>
+<pre class="prettyprint pretty-java">private static final String TOKEN =
+        Long.toBinaryString(new Random().nextLong());
+</pre>
 
-<p>This section explains when you should unregister in GCM and what happens
-when you do.</p>
+  <li> Change the <code>handleRegistration()</code> method so it creates the pending intent when appropriate:</li>
 
-<h3 id="unreg-why">Why you should rarely unregister</h3>
+<pre class="prettyprint pretty-java">...
+if (error != null) {
+ if ("SERVICE_NOT_AVAILABLE".equals(error)) {
+   long backoffTimeMs = // get back-off time from shared preferences
+   long nextAttempt = SystemClock.elapsedRealtime() + backoffTimeMs;
+   Intent retryIntent = new Intent("com.example.gcm.intent.RETRY");
+   retryIntent.putExtra("token", TOKEN);
+   PendingIntent retryPendingIntent =
+       PendingIntent.getBroadcast(context, 0, retryIntent, 0);
+   AlarmManager am = (AlarmManager)   
+       context.getSystemService(Context.ALARM_SERVICE);
+   am.set(AlarmManager.ELAPSED_REALTIME, nextAttempt, retryPendingIntent);
+   backoffTimeMs *= 2; // Next retry should wait longer.
+   // update back-off time on shared preferences
+ } else {
+   // Unrecoverable error, log it
+   Log.i(TAG, "Received error: " + error);
+}
+...</pre>
+<p> The back-off time is stored in a shared preference. This ensures that it is persistent across multiple activity launches. The name of the intent does not matter, as long as the same intent is used in the following steps.</p></li>
 
-<p>A registration ID (regID) represents a particular Android application running
-on a particular device. You should only need to unregister in rare cases, such as
-if you want an app to stop receiving messages, or if you suspect that the regID has
-been compromised. In general, though, once an app has a regID, you shouldn't need
-to change it.</p>
+  <li> Change the <code>onHandleIntent()</code> method adding an <code>else if</code> case for the retry intent:</li>
 
-<p>In particular, you should never unregister your app as a mechanism for
-logout or for switching between users, for the following reasons:</p>
+<pre class="prettyprint pretty-java">...
+} else if (action.equals("com.example.gcm.intent.RETRY")) {
+    String token = intent.getStringExtra("token");
+    // make sure intent was generated by this class, not by a malicious app
+    if (TOKEN.equals(token)) {
+        String registrationId = // get from shared properties
+        if (registrationId != null) {
+        // last operation was attempt to unregister; send UNREGISTER intent again
+    } else {
+        // last operation was attempt to register; send REGISTER intent again
+    }
+}
+...</pre>
 
-<ul>
-  <li>A regID maps an app to a device. It isn't associated with a particular
-  logged in user. If you unregister and then re-register, GCM may return the same
-  ID or a different ID&mdash;there's no guarantee either way.</li>
+  <li> Create a new instance of <code>MyReceiver</code> in your activity:</li>
 
-  <li>Unregistration may take up to 5 minutes to propagate.</li>
-  <li>After unregistration, re-registration may again take up to 5 minutes to
-propagate. During this time messages may be rejected due to the state of being
-unregistered, and after all this, messages may still go to the wrong user.</li>
-</ul>
+<pre class="prettyprint pretty-java">private final MyBroadcastReceiver mRetryReceiver = new MyBroadcastReceiver();
+</pre>
 
+  <li>In the activity's <code>onCreate()</code> method, register the new instance to receive the <code>com.example.gcm.intent.RETRY</code> intent:
+    <pre class="prettyprint pretty-java">...
+IntentFilter filter = new IntentFilter(&quot;com.example.gcm.intent.RETRY&quot;);
+filter.addCategory(getPackageName());
+registerReceiver(mRetryReceiver, filter);
+...</pre>
 
-<p>The solution is to manage your own mapping between users, the regID, and
-individual messages:</p>
+<p class="note"><strong>Note:</strong> You must dynamically create a new instance of the broadcast receiver since the one defined by the manifest can only receive intents with the <code>com.google.android.c2dm.permission.SEND</code> permission. The permission <code>com.google.android.c2dm.permission.SEND</code> is a system permission and as such it cannot be granted to a regular application.</p>
 
-<ul>
-  <li>Your app server should maintain a mapping between the current user
-and the regID. This should include information about which user is supposed to
-receive a particular message.</li>
-  <li>The app running on the device should check to ensure that messages it
-receives match the logged in user.</li>
-</ul>
+</li>
 
+  <li>In the activity's <code>onDestroy()</code> method, unregister the broadcast receiver:</li>
 
-<h3 id="unreg-how">How unregistration works</h3>
-
-<p>An application can be automatically unregistered after it is uninstalled from
-the device. However, this process does not happens right away, as Android does not
-provide an uninstall callback. What happens in this scenario is as follows:</p>
+<pre class="prettyprint pretty-java">unregisterReceiver(mRetryReceiver);</pre>
+</ol>
+<h2 id="unreg">How Unregistration Works</h2>
+<p>There are two ways to unregister a device from GCM: manually and automatically.</p>
+<p>An Android application can manually unregister itself by issuing a <code>com.google.android.c2dm.intent.UNREGISTER</code> intent, which is useful when the application offers a logoff feature (so it can unregister on logoff and register again on logon). See the <a href="gcm.html#unregistering">Architectural Overview</a> for more discussion of this topic. This is the sequence of events when an application unregisters itself:</p>
+<ol>
+  <li> The application issues a <code>com.google.android.c2dm.intent.UNREGISTER</code> intent, passing the package name as an extra.</li>
+  <li>When the GCM server is done with the unregistration, it sends a <code>com.google.android.c2dm.intent.REGISTRATION</code> intent with the <code>unregistered</code> extra set.</li>
+  <li>The application then must contact the 3rd-party server so it can remove the registration ID.</li>
+  <li>The application should also clear its registration ID.
+  </li>
+</ol>
+<p>An application can be automatically unregistered after it is uninstalled from the device. However, this process does not happens right away, as Android does not provide an uninstall callback. What happens in this scenario is as follows:</p>
 <ol>
   <li>The end user uninstalls the application.</li>
   <li>The 3rd-party server sends a message to GCM server.</li>
   <li>The GCM server sends the message to the device.</li>
-  <li>The GCM client receives the message and queries Package Manager about
-whether there are broadcast receivers configured to receive it, which returns
-<code>false</code>.
+  <li>The GCM client receives the message and queries Package Manager about whether there are broadcast receivers configured to receive it, which returns <code>false</code>. 
 </li>
   <li>The GCM client informs the GCM server that the application was uninstalled.</li>
   <li>The GCM server marks the registration ID for deletion.</li>
@@ -234,16 +184,9 @@
   </li>
 </ol>
 
-<p class ="note"><strong>Note:</strong> The GCM client is the Google Cloud
-Messaging framework present on the device.</p>
+<p class ="note"><strong>Note:</strong> The GCM client is the Google Cloud Messaging framework present on the device.</p>
 
-<p>Note that it might take a while for the registration ID be completely removed
-from GCM. Thus it is possible that messages sent during step 7 above gets a valid
-message ID as response, even though the message will not be delivered to the device.
-Eventually, the registration ID will be removed and the server will get a
-<code>NotRegistered</code> error, without any further action being required from
-the 3rd-party server (this scenario happens frequently while an application is
-being developed and tested).</p>
+<p>Note that it might take a while for the registration ID be completely removed from GCM. Thus it is possible that messages sent during step 7 above gets a valid message ID as response, even though the message will not be delivered to the device. Eventually, the registration ID will be removed and the server will get a <code>NotRegistered</code> error, without any further action being required from the 3rd-party server (this scenario happens frequently while an application is being developed and tested).</p>
 
 <h2 id="collapsible">Send-to-Sync  vs. Messages with Payload</h2>
 
@@ -253,45 +196,17 @@
   <li>By default, it is stored by GCM for 4 weeks.</li>
 </ul>
 
-<p>But despite these similarities, messages can behave very differently depending
-on their particular settings. One major distinction between messages is whether
-they are collapsed (where each new message replaces the preceding message) or not
-collapsed (where each individual message is delivered). Every message sent in GCM
-is either a &quot;send-to-sync&quot; (collapsible) message or a &quot;message with
-payload&quot; (non-collapsible message). These concepts are described in more
-detail in the following sections.</p>
+<p>But despite these similarities, messages can behave very differently depending on their particular settings. One major distinction between messages is whether they are collapsed (where each new message replaces the preceding message) or not collapsed (where each individual message is delivered). Every message sent in GCM is either a &quot;send-to-sync&quot; (collapsible) message or a &quot;message with payload&quot; (non-collapsible message). These concepts are described in more detail in the following sections.</p>
 
 <h3 id="s2s"><strong>Send-to-sync messages</strong></h3>
 
-<p>A send-to-sync (collapsible) message is often a &quot;tickle&quot; that tells
-a mobile application to sync data from the server. For example, suppose you have
-an email application. When a user receives new email on the server, the server
-pings the mobile application with a &quot;New mail&quot; message. This tells the
-application to sync to the server to pick up the new email. The server might send
-this message multiple times as new mail continues to accumulate, before the application
-has had a chance to sync. But if the user has received 25 new emails, there's no
-need to preserve every &quot;New mail&quot; message. One is sufficient. Another
-example would be a sports application that updates users with the latest score.
-Only the most recent message is relevant, so it makes sense to have each new
-message replace the preceding message. </p>
+<p>A send-to-sync (collapsible) message is often a &quot;tickle&quot; that tells a mobile application to sync data from the server. For example, suppose you have an email application. When a user receives new email on the server, the server pings the mobile application with a &quot;New mail&quot; message. This tells the application to sync to the server to pick up the new email. The server might send this message multiple times as new mail continues to accumulate, before the application has had a chance to sync. But if the user has received 25 new emails, there's no need to preserve every &quot;New mail&quot; message. One is sufficient. Another example would be a sports application that updates users with the latest score. Only the most recent message is relevant, so it makes sense to have each new message replace the preceding message. </p>
 
-<p>The email and sports applications are cases where you would probably use the
-GCM <code>collapse_key</code> parameter. A <em>collapse key</em> is an arbitrary
-string that is used to collapse a group of like messages when the device is offline,
-so that only the most recent message gets sent to the client. For example,
-&quot;New mail,&quot; &quot;Updates available,&quot; and so on</p>
-<p>GCM allows a maximum of 4 different collapse keys to be used by the GCM server
-at any given time. In other words, the GCM server can simultaneously store 4
-different send-to-sync messages per device, each with a different collapse key.
-For example, Device A can have A1, A2, A3, and A4. Device B can have B1, B2, B3,
-and B4, and so on. If you exceed this number GCM will only keep 4 collapse keys, with no
-guarantees about which ones they will be.</p>
+<p>The email and sports applications are cases where you would probably use the GCM <code>collapse_key</code> parameter. A <em>collapse key</em> is an arbitrary string that is used to collapse a group of like messages when the device is offline, so that only the most recent message gets sent to the client. For example, &quot;New mail,&quot; &quot;Updates available,&quot; and so on</p>
+<p>GCM allows a maximum of 4 different collapse keys to be used by the GCM server at any given time. In other words, the GCM server can simultaneously store 4 different send-to-sync messages, each with a different collapse key. If you exceed this number GCM will only keep 4 collapse keys, with no guarantees about which ones they will be.</p>
 
 <h3 id="payload">Messages with payload</h3>
-<p>Unlike a send-to-sync message, every &quot;message with payload&quot;
-(non-collapsible message) is delivered. The payload the message contains can be
-up to 4kb. For example, here is a JSON-formatted message in an IM application in
-which spectators are discussing a sporting event:</p>
+<p>Unlike a send-to-sync message, every &quot;message with payload&quot; (non-collapsible message) is delivered. The payload the message contains can be up to 4kb. For example, here is a JSON-formatted message in an IM application in which spectators are discussing a sporting event:</p>
 
 <pre class="prettyprint pretty-json">{
   "registration_id" : "APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx...",
@@ -302,42 +217,19 @@
   },
 }</pre>
 
-<p>A &quot;message with payload&quot; is not simply a &quot;ping&quot; to the
-mobile application to contact the server to fetch data. In the aforementioned IM
-application, for example, you would want to deliver every message, because every
-message has different content. To specify a non-collapsible message, you simply
-omit the <code>collapse_key</code> parameter. Thus GCM will send each message
-individually. Note that the order of delivery is not guaranteed.</p>
-
-<p>GCM will store up to 100 non-collapsible messages. After that, all messages
-are discarded from GCM, and a new message is created that tells the client how
-far behind it is. The message is delivered through a regular
-<code>com.google.android.c2dm.intent.RECEIVE</code> intent, with the following
-extras:</p>
+<p>A &quot;message with payload&quot; is not simply a &quot;ping&quot; to the mobile application to contact the server to fetch data. In the aforementioned IM application, for example, you would want to deliver every message, because every message has different content. To specify a non-collapsible message, you simply omit the <code>collapse_key</code> parameter. Thus GCM will send each message individually. Note that the order of delivery is not guaranteed.</p>
+<p>GCM will store up to 100 non-collapsible messages. After that, all messages are discarded from GCM, and a new message is created that tells the client how far behind it is. The message is delivered through a regular <code>com.google.android.c2dm.intent.RECEIVE</code> intent, with the following extras:</p>
 <ul>
-  <li> <code>message_type</code>&mdash;The value is always the string
-&quot;deleted_messages&quot;.</li>
-  <li><code>total_deleted</code>&mdash;The value  is a string with the number of
-deleted messages.</li>
+  <li> <code>message_type</code>&mdash;The value is always the string &quot;deleted_messages&quot;.</li>
+  <li><code>total_deleted</code>&mdash;The value  is a string with the number of deleted messages.</li>
 </ul>
-<p>The application should respond by syncing with the server to recover the
-discarded messages. </p>
+<p>The application should respond by syncing with the server to recover the discarded messages. </p>
 
 <h3 id="which">Which should I use?</h3>
-  <p>If your application does not need to use non-collapsible messages, collapsible
-messages are a better choice from a performance standpoint, because they put less
-of a burden on the device battery. However, if you use collapsible messages, remember that
-<strong>GCM only allows a maximum of 4 different collapse keys to be used by the GCM server
-per device at any given time</strong>. You must not exceed this number, or it could cause
-unpredictable consequences.</p>
+  <p>If your application does not need to use non-collapsible messages, collapsible messages are a better choice from a performance standpoint, because they put less of a burden on the device battery.</p>
 
 <h2 dir="ltr" id="ttl">Setting an Expiration Date for a Message</h2>
-<p>The Time to Live (TTL) feature lets  the sender  specify the maximum lifespan
-of a message using the <code>time_to_live</code> parameter in the send request.
-The value of this parameter must be a duration from 0 to 2,419,200 seconds, and
-it corresponds to the maximum period of time for which GCM will store and try to
-deliver the message. Requests that don't contain this field default to the maximum
-period of 4 weeks.</p>
+<p>The Time to Live (TTL) feature lets  the sender  specify the maximum lifespan of a message using the <code>time_to_live</code> parameter in the send request. The value of this parameter must be a duration from 0 to 2,419,200 seconds, and it corresponds to the maximum period of time for which GCM will store and try to deliver the message. Requests that don't contain this field default to the maximum period of 4 weeks.</p>
 <p>Here are some possible uses for this feature:</p>
 <ul>
   <li>Video chat incoming calls</li>
@@ -345,29 +237,9 @@
   <li>Calendar events</li>
 </ul>
 <h3 id="bg">Background </h3>
-<p>GCM will usually deliver messages immediately after they are sent. However,
-this might not always be possible. For example, the device could be turned off,
-offline, or otherwise unavailable. In other cases, the sender itself might request
-that messages not be delivered until the device becomes active by using the
-<code>delay_while_idle</code> flag. Finally, GCM might intentionally delay messages
-to prevent an application from consuming excessive resources and negatively
-impacting battery life.</p>
-
-<p>When this happens, GCM will store the message and deliver it as soon as it's
-feasible. While this is fine in most cases, there are some applications for which
-a late message might as well never be delivered. For example, if the message is
-an incoming call or video chat notification, it will only be meaningful for a
-small period of time before the call is terminated. Or if the message is an
-invitation to an event, it will be useless if received after the event has ended.</p>
-
-<p>Another advantage of specifying the expiration date for a message is that GCM
-will never throttle messages with a <code>time_to_live</code> value of 0 seconds.
-In other words, GCM will guarantee best effort for messages that must be delivered
-&quot;now or never.&quot; Keep in mind that a <code>time_to_live</code> value of
-0 means messages that can't be delivered immediately will be discarded. However,
-because such messages are never stored, this provides the best latency for
-sending notifications.</p>
-
+<p>GCM will usually deliver messages immediately after they are sent. However, this might not always be possible. For example, the device could be turned off, offline, or otherwise unavailable. In other cases, the sender itself might request that messages not be delivered until the device becomes active by using the <code>delay_while_idle</code> flag. Finally, GCM might intentionally delay messages to prevent an application from consuming excessive resources and negatively impacting battery life.</p>
+<p>When this happens, GCM will store the message and deliver it as soon as it's feasible. While this is fine in most cases, there are some applications for which a late message might as well never be delivered. For example, if the message is an incoming call or video chat notification, it will only be meaningful for a small period of time before the call is terminated. Or if the message is an invitation to an event, it will be useless if received after the event has ended.</p>
+<p>Another advantage of specifying the expiration date for a message is that GCM will never throttle messages with a <code>time_to_live</code> value of 0 seconds. In other words, GCM will guarantee best effort for messages that must be delivered &quot;now or never.&quot; Keep in mind that a <code>time_to_live</code> value of 0 means messages that can't be delivered immediately will be discarded. However, because such messages are never stored, this provides the best latency for sending notifications.</p>
 <p>Here is an example of a JSON-formatted request that includes TTL:</p>
 <pre class="prettyprint pretty-json">
 {
@@ -384,23 +256,9 @@
 
 
 <h2 id="multi-senders">Receiving Messages from Multiple Senders</h2>
-
-<p>GCM allows multiple parties to send messages to the same application. For
-example, suppose your application is an articles aggregator with multiple
-contributors, and you want each of them to be able to send a message when they
-publish a new article. This message might contain a URL so that the application
-can download the article. Instead of having to centralize all sending activity in
-one location, GCM gives you the ability to let each of these contributors send
-its own messages.</p>
-
-<p>To make this possible, all you need to do is have each sender generate its own
-project number. Then include those IDs in the sender field, separated by commas,
-when requesting a registration. Finally, share the registration ID with your
-partners, and they'll be able to send messages to your application using their
-own authentication keys.</p>
-<p>This code snippet illustrates this feature. Senders are passed as an intent
-extra in a comma-separated list:</p>
-
+<p>GCM allows multiple parties to send messages to the same application. For example, suppose your application is an articles aggregator with multiple contributors, and you want each of them to be able to send a message when they publish a new article. This message might contain a URL so that the application can download the article. Instead of having to centralize all sending activity in one location, GCM gives you the ability to let each of these contributors send its own messages.</p>
+<p>To make this possible, all you need to do is have each sender generate its own project number. Then include those IDs in the sender field, separated by commas, when requesting a registration. Finally, share the registration ID with your partners, and they'll be able to send messages to your application using their own authentication keys.</p>
+<p>This code snippet illustrates this feature. Senders are passed as an intent extra in a comma-separated list:</p>
 <pre class="prettyprint pretty-java">Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_REGISTRATION);
 intent.setPackage(GSF_PACKAGE);
 intent.putExtra(GCMConstants.EXTRA_APPLICATION_PENDING_INTENT,
@@ -411,3 +269,4 @@
  </pre>
 
 <p>Note that there is limit of 100 multiple senders.</p>
+ 
diff --git a/docs/html/google/gcm/ccs.jd b/docs/html/google/gcm/ccs.jd
index 244278e..0cadbd2 100644
--- a/docs/html/google/gcm/ccs.jd
+++ b/docs/html/google/gcm/ccs.jd
@@ -1,96 +1,93 @@
-page.title=GCM Cloud Connection Server (XMPP)
+page.title=GCM Cloud Connection Server
 @jd:body
 
 <div id="qv-wrapper">
 <div id="qv">
 
+<h2>Quickview</h2>
+
+<ul>
+<li>Get an introduction to key CCS terms and concepts.</li>
+<li>Learn how to send and receive both upstream and downstream messages in CCS.</li>
+</ul>
+
 
 <h2>In this document</h2>
 
 <ol class="toc">
+  <li><a href="#gcm">CCS vs. GCM HTTP</a> </li>
   <li><a href="#usage">How to Use CCS</a>
-    <ol class="toc">
-      <li><a href="#auth">Authentication</a></li>
-      </ol>
-      </li>
-    <li><a href="#format">Message Format</a>
-      <ol class="toc">
-        <li><a href="#request">Request format</a></li>
-        <li><a href="#response">Response format</a></li>
-      </ol>
-      </li>
-  <li><a href="#upstream">Upstream Messages</a> </li>
-  <li><a href="#flow">Flow Control</a> </li>
-  <li><a href="#implement">Implementing an XMPP-based App Server</a>
-    <ol class="toc">
-      <li><a href="#smack">Java sample using the Smack library</a></li>
-      <li><a href="#python">Python sample</a></li>
+    <ol>
+      <li><a href="#send_msg">Sending Messages</a></li>
+      <li><a href="#format">Message Format</a></li>
+      <li><a href="#msg_examples">Message Examples</a></li>
     </ol>
   </li>
+  <li><a href="#flow">Flow Control</a> </li>
 </ol>
 
 <h2>See Also</h2>
 
 <ol class="toc">
-<li><a href="{@docRoot}google/play-services/gcm/http.html">HTTP</a></li>
 <li><a href="{@docRoot}google/play-services/gcm/gs.html">Getting Started</a></li>
-<li><a href="{@docRoot}google/play-services/gcm/server.html">Implementing GCM Server</a></li>
-<li><a href="{@docRoot}google/play-services/gcm/client.html">Implementing GCM Client</a></li>
-<li><a href="https://services.google.com/fb/forms/gcm/" class="external-link"
-target="_android">CCS and User Notifications Signup Form</a></li>
+<li><a href="https://services.google.com/fb/forms/gcm/" class="external-link" target="_android">CCS and User Notifications Signup Form</a></li>
 </ol>
 
 </div>
 </div>
 
-<p class="note"><strong>Note:</strong> To try out this feature, sign up using
-<a href="https://services.google.com/fb/forms/gcm/">this form</a>.</p>
+<p class="note"><strong>Note:</strong> To try out this feature, sign up using <a href="https://services.google.com/fb/forms/gcm/">this form</a>.</p>
 
-<p>The GCM Cloud Connection Server (CCS) is a connection server based on XMPP.
-CCS allows 3rd-party app servers (which you're
-responsible for implementing) to communicate
-with Android devices by  establishing a persistent TCP connection with Google
-servers using the XMPP protocol. This communication is asynchronous and bidirectional.</p>
-<p>You can continue to use the HTTP request mechanism to send messages to GCM
-servers, side-by-side with CCS which uses XMPP. Some of the benefits of CCS include:</p>
+<p>The GCM Cloud Connection Server (CCS) allows third party servers to communicate with Android devices by  establishing a persistent TCP connection with Google servers using the XMPP protocol. This communication is asynchronous and bidirectional.</p>
+<p>You can continue to use the HTTP request mechanism to send messages to GCM servers, side-by-side with CCS which uses XMPP. Some of the benefits of CCS include:</p>
 <ul>
-  <li>The asynchronous nature of XMPP allows you to send more messages with fewer
-resources.</li>
-  <li>Communication is bidirectional&mdash;not only can the server send messages
-to the device, but the device can send messages back to the server.</li>
-<li>You can send messages back using the same connection used for receiving,
-thereby improving battery life.</li>
+  <li>The asynchronous nature of XMPP allows you to send more messages with fewer resources.</li>
+  <li>Communication is bidirectional&mdash;not only can the server send messages to the device, but the device can send messages back to the server.</li>
+<li>You can send messages back using the same connection used for receiving, thereby improving battery life.</li>
 </ul>
 
-<p>The upstream messaging (device-to-cloud) feature of CCS is part of the Google
-Play services platform. Upstream messaging is available through the
-<a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">
-{@code GoogleCloudMessaging}</a>
-APIs. For examples, see
-<a href="#implement">Implementing an XMPP-based App Server</a>.</p>
+<p>The upstream messaging (device-to-cloud) feature of CCS is part of the Google Play services platform. Upstream messaging is available through the <a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">{@code GoogleCloudMessaging}</a> APIs. To use upstream messaging and the new streamlined registration process, you must <a href="{@docRoot}google/play-services/setup.html">set up</a> the Google Play services SDK.</p>
 
-<p class="note"><strong>Note:</strong> See
-<a href="server.html#params">Implementing GCM Server</a> for a list of all the message
-parameters and which connection server(s) supports them.</p>
+<p class="note"><strong>Note:</strong> For an example of an XMPP server, see <a href="server.html#xmpp">GCM Server</a>.
 
+<h2 id="gcm">CCS vs. GCM HTTP</h2>
+
+<p>CCS messaging differs from GCM HTTP messaging in the following ways:</p>
+<ul>
+  <li>Upstream/Downstream messages
+    <ul>
+      <li>GCM HTTP: Downstream only: cloud-to-device. </li>
+      <li>CCS: Upstream and downstream (device-to-cloud, cloud-to-device). </li>
+    </ul>
+  </li>
+  <li>Asynchronous messaging
+    <ul>
+      <li>GCM HTTP: 3rd-party servers send messages as HTTP POST requests and wait for a response. This mechanism is synchronous and causes the sender to block before sending another message.</li>
+      <li>CCS: 3rd-party servers connect to Google infrastructure using a persistent XMPP connection and send/receive messages to/from all their devices at full line speed. CCS sends acknowledgements or failure notifications (in the form of special ACK and NACK JSON-encoded XMPP messages) asynchronously.</li>
+    </ul>
+  </li>
+
+  <li>JSON
+    <ul>
+      <li>GCM HTTP: JSON messages sent as HTTP POST.</li>
+      <li>CCS: JSON messages encapsulated in XMPP messages.</li>
+    </ul>
+  </li>
+</ul>
+<p>This document describes how to use CCS. For general concepts and information on how to use GCM HTTP, see the <a href="gcm.html">GCM Architectural Overview</a>.</p>
 
 <h2 id="usage">How to Use CCS</h2>
 
-<p>GCM Cloud Connection Server (CCS) is an XMPP endpoint, running on
-{@code http://gcm.googleapis.com} port 5235.</p>
+<p>GCM Cloud Connection Server (CCS) is an XMPP endpoint, running on {@code http://gcm.googleapis.com} port 5235.</p>
 
-<p>CCS requires a Transport Layer Security (TLS) connection. That means the  XMPP
-client must initiate a TLS connection.
-For example in Java, you would call {@code setSocketFactory(SSLSocketFactory)}.</p>
+<p>CCS requires a Transport Layer Security (TLS) connection. That means the  XMPP client must initiate a TLS connection.
+For example in smack, you would call {@code setSocketFactory(SSLSocketFactory)}, similar to “old style SSL” XMPP connections and https.</p>
 
-<p>CCS requires a SASL PLAIN authentication mechanism using
-{@code &lt;your_GCM_Sender_Id&gt;&#64;gcm.googleapis.com} (GCM sender ID) and the
-API key as the password, where the sender ID and API key are the same as described
-in <a href="gs.html">Getting Started</a>.</p>
+<p>CCS requires a SASL PLAIN authentication mechanism using {@code &lt;your_GCM_Sender_Id&gt;&#64;gcm.googleapis.com} (GCM sender ID) and the API key as the password, where the sender ID and API key are the same as described in <a href="gs.html">Getting Started</a>.</p>
 
 <p> You can use most XMPP libraries to interact with CCS.</p>
 
-<h3 id="auth">Authentication</h3>
+<h3 id="send_msg">Sending messages</h3>
 
 <p>The following snippets illustrate how to perform authentication in CCS.</p>
 <h4>Client</h4>
@@ -111,13 +108,13 @@
 <h4>Client</h4>
 <pre>&lt;auth mechanism=&quot;PLAIN&quot;
 xmlns=&quot;urn:ietf:params:xml:ns:xmpp-sasl&quot;&gt;MTI2MjAwMzQ3OTMzQHByb2plY3RzLmdjbS5hb
+mRyb2lkLmNvbQAxMjYyMDAzNDc5FzNAcHJvamVjdHMtZ2EtLmFuZHJvaWQuY29tAEFJe
 mFTeUIzcmNaTmtmbnFLZEZiOW1oekNCaVlwT1JEQTJKV1d0dw==&lt;/auth&gt;
 </pre>
-
 <h4>Server</h4>
 <pre>&lt;success xmlns=&quot;urn:ietf:params:xml:ns:xmpp-sasl&quot;/&gt;</pre>
 
-<h2 id="format">Message Format</h2>
+<h3 id="format">Message Format</h3>
 <p>CCS uses normal XMPP <code>&lt;message&gt;</code> stanzas. The body of the message must be:
 </p>
 <pre>
@@ -126,42 +123,25 @@
 &lt;/gcm&gt;
 </pre>
 
-<p>The JSON payload for server-to-device is similar to what the GCM http endpoint
-uses, with these exceptions:</p>
+<p>The JSON payload for server-to-device is similar to what the GCM http endpoint uses, with these exceptions:</p>
 <ul>
   <li>There is no support for multiple recipients.</li>
   <li>{@code to} is used instead of {@code registration_ids}.</li>
-  <li>CCS adds the field {@code message_id}, which is required. This ID uniquely
-identifies the message in an XMPP connection. The ACK or NACK from CCS uses the
-{@code message_id} to identify a message sent from 3rd-party app servers to CCS.
-Therefore, it's important that this {@code message_id} not only be unique, but
-always present.</li>
+  <li>CCS adds the field {@code message_id}, which is required. This ID uniquely identifies the message in an XMPP connection. The ACK or NACK from CCS uses the {@code message_id} to identify a message sent from 3rd-party servers to CCS. Therefore, it's important that this {@code message_id} not only be unique, but always present.</li>
 
-<li>For ACK/NACK messages that are special control messages, you also need to
-include a {@code message_type} field in the JSON message. The value can be either
-'ack' or 'nack'. For example:
+  <li>For ACK/NACK messages that are special control messages, you also need to include a {@code message_type} field in the JSON message. For example:
 
-<pre>message_type = ('ack');</pre>
+<pre>message_type = ('ack' OR 'nack');</pre>
   </li>
 </ul>
-<p>For each device message your app server receives from CCS, it needs to send
-an ACK message.
-It never needs to send a NACK message. If you don't send an ACK for a message,
-CCS will just resend it.
+<p>For each message a device sends to the server, you need to send an ACK message. You never need to send a NACK message. If you don't send an ACK for a message, CCS will just resend it.
 </p>
-<p>CCS also sends an ACK or NACK for each server-to-device message. If you do not
-receive either, it means that the TCP connection was closed in the middle of the
-operation and your server needs to resend the messages. See
-<a href="#flow">Flow Control</a> for details.
+<p>CCS also sends an ACK or NACK for each server-to-device message. If you do not receive either, it means that the TCP connection was closed in the middle of the operation and your server needs to resend the messages.
 </p>
 
-<p class="note"><strong>Note:</strong> See
-<a href="server.html#params">Implementing GCM Server</a> for a list of all the message
-parameters and which connection server(s) supports them.</p>
+<h3 id="msg_examples">Message Examples</h3>
 
-<h3 id="request">Request format</h3>
-
-<p>Here is an XMPP stanza containing the JSON message from a 3rd-party app server to CCS:
+<p>Here is an XMPP stanza containing the JSON message from a 3rd-party server to CCS:
 
 </p>
 <pre>&lt;message id=&quot;&quot;&gt;
@@ -180,15 +160,7 @@
 &lt;/message&gt;
 </pre>
 
-<h3 id="response">Response format</h3>
-
-<p>A CCS response can have 3 possible forms. The first one is a regular 'ack'
-message. But when the response contains an error, there are 2
-different forms the message can take, described below.</p>
-
-<h4 id="ack">ACK message</h4>
-
-<p>Here is an XMPP stanza containing the ACK/NACK message from CCS to 3rd-party app server:
+<p>Here is an XMPP stanza containing the ACK/NACK message from CCS to 3rd-party server:
 </p>
 <pre>&lt;message id=&quot;&quot;&gt;
   &lt;gcm xmlns=&quot;google:mobile:data&quot;&gt;
@@ -199,138 +171,24 @@
   }
   &lt;/gcm&gt;
 &lt;/message&gt;
-</pre>
 
-<h4 id="nack">NACK message</h4>
-
-<p>A NACK error is a regular XMPP message in which the {@code message_type} status
-message is &quot;nack&quot;. A NACK message contains:</p>
-<ul>
-<li>Nack error code.</li>
-<li>Nack error description.</li>
-</ul>
-
-<p>Below are some examples.</p>
-
-<p>Bad registration:</p>
-<pre>&lt;message&gt;
-  &lt;data:gcm xmlns:data=&quot;google:mobile:data&quot;&gt;
-  {
-    &quot;error&quot;:&quot;BAD_REGISTRATION&quot;,  // error code
-    &quot;message_id&quot;:&quot;msgId1&quot;,
-    &quot;from&quot;:&quot;PA91bHFOtaQGSwupt5l1og&quot;,
-    &quot;message_type&quot;:&quot;nack&quot;
-  }
-  &lt;/data:gcm&gt;
-&lt;/message&gt;</pre>
-
-<p>Invalid "time to live":</p>
-
-<pre>&lt;message&gt;
-  &lt;data:gcm xmlns:data=&quot;google:mobile:data&quot;&gt;
-  {
-     &quot;error&quot;:&quot;InvalidJson : INVALID_TTL : Invalid value (-1) for \&quot;time_to_live\&quot;: must be between 0 and \&quot;2419200\&quot;\n&quot;,
-     &quot;message_id&quot;:&quot;msgId1&quot;,
-     &quot;from&quot;:&quot;APA91bHFOtaQGSwupt5l1og&quot;,
-     &quot;message_type&quot;:&quot;nack&quot;
-  }
-  &lt;/data:gcm&gt;
-&lt;/message&gt;</pre>
-
-<p>JSON type error:</p>
-
-<pre>&lt;message&gt;
-  &lt;data:gcm xmlns:data=&quot;google:mobile:data&quot;&gt;
-  {
-     &quot;error&quot;:&quot;InvalidJson : JSON_TYPE_ERROR : Field \&quot;delay_while_idle\&quot; must be a JSON java.lang.Boolean: not-boolean-user-supplied-value\n&quot;,
-     &quot;message_id&quot;:&quot;msgId1&quot;,
-     &quot;from&quot;:&quot;APA91bHFOtaQGSwupt5l1og&quot;,
-     &quot;message_type&quot;:&quot;nack&quot;
-  }
-  &lt;/data:gcm&gt;
-&lt;/message&gt;</pre>
-
-
-<p>The following table lists some of the more common NACK error codes.</p>
-
-<p class="table-caption" id="table1">
-  <strong>Table 1.</strong> NACK error codes.</p>
-
-<table border="1">
-<tr>
-<th>Error Code</th>
-<th>Description</th>
-</tr>
-<tr>
-<td>{@code BAD_REGISTRATION}</td>
-<td>The device has a registration ID, but it's invalid.</td>
-</tr>
-<tr>
-<td>{@code DEVICE_UNREGISTERED}</td>
-<td>The device is not registered.</td>
-</tr>
-<tr>
-<td>{@code INTERNAL_SERVER_ERROR}</td>
-<td>The server encountered an error while trying to process the request.</td>
-</tr>
-<tr>
-<td>{@code SERVICE_UNAVAILABLE}</td>
-<td>The CCS connection server is temporarily unavailable, try again later
-(using exponential backoff, etc.).</td>
-</tr>
-<tr>
-<td>{@code BAD_ACK}</td>
-<td>The ACK message is improperly formed.</td>
-</tr>
-<tr>
-<td>{@code AUTHENTICATION_FAILED}</td>
-<td>This is a 401 error indicating that there was an error authenticating the sender account.</td>
-</tr>
-<tr>
-<td>{@code INVALID_TTL}</td>
-<td>There was an error in the supplied "time to live" value.</td>
-</tr>
-<tr>
-<td>{@code JSON_TYPE_ERROR}</td>
-<td>There was an error in the supplied JSON data type.</td>
-</tr>
-</table>
-
-<h4 id="stanza">Stanza error</h4>
-
-<p>You can also get a stanza error in certain cases.
-A stanza error contains:</p>
-<ul>
-<li>Stanza error code.</li>
-<li>Stanza error description (free text).</li>
-</ul>
-<p>For example:</p>
-
-<pre>&lt;message id=&quot;3&quot; type=&quot;error&quot; to=&quot;123456789@gcm.googleapis.com/ABC&quot;&gt;
+&lt;message id=&quot;&quot;&gt;
   &lt;gcm xmlns=&quot;google:mobile:data&quot;&gt;
-     {&quot;random&quot;: &quot;text&quot;}
+  {
+      &quot;from&quot;:&quot;REGID&quot;,
+      &quot;message_id&quot;:&quot;m-1366082849205&quot;
+      &quot;error&quot;: ERROR_CODE,
+      &quot;message_type&quot;:&quot;nack&quot;
+  }
   &lt;/gcm&gt;
-  &lt;error code=&quot;400&quot; type=&quot;modify&quot;&gt;
-    &lt;bad-request xmlns=&quot;urn:ietf:params:xml:ns:xmpp-stanzas&quot;/&gt;
-    &lt;text xmlns=&quot;urn:ietf:params:xml:ns:xmpp-stanzas&quot;&gt;
-      InvalidJson: JSON_PARSING_ERROR : Missing Required Field: message_id\n
-    &lt;/text&gt;
-  &lt;/error&gt;
 &lt;/message&gt;
 </pre>
 
+<h4>Upstream Messages</h4>
 
-<h2 id="upstream">Upstream Messages</h2>
+<p>Using CCS and the <a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">GoogleCloudMessaging</a> API, you can send messages from a user's device to the cloud.</p>
 
-<p>Using CCS and the
-<a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">
-{@code GoogleCloudMessaging}</a>
-API, you can send messages from a user's device to the cloud.</p>
-
-<p>Here is how you send an upstream message using the
-<a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">
-{@code GoogleCloudMessaging}</a>
-API. For a complete example, see <a href="client.html">Implementing GCM Client</a>:</p>
+<p>Here is how you send an upstream message using the <a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">GoogleCloudMessaging</a> API. For a complete example, see <a href="gs.html#gs_example">Getting Started</a>:</p>
 
 <pre>GoogleCloudMessaging gcm = GoogleCloudMessaging.get(context);
 String GCM_SENDER_ID = "Your-Sender-ID";
@@ -340,15 +198,12 @@
 // Bundle data consists of a key-value pair
 data.putString("hello", "world");
 // "time to live" parameter
-// This is optional. It specifies a value in seconds up to 4 weeks.
 int ttl = [0 seconds, 4 weeks]
 
 gcm.send(GCM_SENDER_ID + "&#64;gcm.googleapis.com", id, ttl, data);
 </pre>
 
-<p>This call generates the necessary XMPP stanza for sending the upstream message.
-The message goes from the app on the device to CCS to the 3rd-party app server.
-The stanza has the following format:</p>
+<p>This call generates the necessary XMPP stanza for sending the upstream message. The message goes from the app on the device to CCS to the 3rd-party server. The stanza has the following format:</p>
 
 <pre>&lt;message id=&quot;&quot;&gt;
   &lt;gcm xmlns=&quot;google:mobile:data&quot;&gt;
@@ -364,8 +219,7 @@
   &lt;/gcm&gt;
 &lt;/message&gt;</pre>
 
-<p>Here is the format of the ACK expected by CCS from 3rd-party app servers in
-response to the above message:</p>
+<p>Here is the format of the ACK expected by CCS from 3rd-party servers in response to the above message:</p>
 
 <pre>&lt;message id=&quot;&quot;&gt;
   &lt;gcm xmlns=&quot;google:mobile:data&quot;&gt;
@@ -377,478 +231,13 @@
   &lt;/gcm&gt;
 &lt;/message&gt;</pre>
 
+
 <h2 id="flow">Flow Control</h2>
 
-<p>Every message sent to CCS receives either an ACK or a NACK response. Messages
-that haven't received one of these responses are considered pending. If the pending
-message count reaches 1000, the 3rd-party app server should stop sending new messages
-and wait for CCS to acknowledge some of the existing pending messages as illustrated in
-figure 1:</p>
+<p>Every message sent to CCS receives either an ACK or a NACK response. Messages that haven't received one of these responses are considered pending. If the pending message count reaches 1000, the 3rd-party server should stop sending new messages and wait for CCS to acknowledge some of the existing pending messages.</p>
 
-<img src="{@docRoot}images/gcm/CCS-ack.png">
+<p>Conversely, to avoid overloading the 3rd-party server, CCS will stop sending if there are too many unacknowledged messages. Therefore, the 3rd-party server should "ACK" received messages as soon as possible to maintain a constant flow of incoming messages. The aforementioned pending message limit doesn't apply to these ACKs. Even if the pending message count reaches 1000, the 3rd-party server should continue sending ACKs to avoid blocking delivery of new messages.</p>
 
-<p class="img-caption">
-  <strong>Figure 1.</strong> Message/ack flow.
+<p>ACKs are only valid within the context of one connection. If the connection is closed before a message can be ACKed, the 3rd-party server should wait for CCS to resend the message before ACKing it again.
 </p>
 
-<p>Conversely, to avoid overloading the 3rd-party app server, CCS will stop sending
-if there are too many unacknowledged messages. Therefore, the 3rd-party app server
-should "ACK" upstream messages, received from the client application via CCS, as soon as possible
-to maintain a constant flow of incoming messages. The aforementioned pending message limit doesn't
-apply to these ACKs. Even if the pending message count reaches 1000, the 3rd-party app server
-should continue sending ACKs for messages received from CCS to avoid blocking delivery of new
-upstream messages.</p>
-
-<p>ACKs are only valid within the context of one connection. If the connection is
-closed before a message can be ACKed, the 3rd-party app server should wait for CCS
-to resend the upstream message before ACKing it again. Similarly, all pending messages for which an
-ACK/NACK was not received from CCS before the connection was closed should be sent again.
-</p>
-
-<h2 id="implement">Implementing an XMPP-based App Server</h2>
-
-<p>This section gives examples of implementing an app server that works with CCS.
-Note that a full GCM implementation requires a client-side implementation, in
-addition to the server. For more information, see <a href="client.html">
-Implementing GCM Client</a>.</a>
-
-<h3 id="smack">Java sample using the Smack library</h3>
-
-<p>Here is a sample app server written in Java, using the
-<a href="http://www.igniterealtime.org/projects/smack/">Smack</a> library.</p>
-
-<pre>import org.jivesoftware.smack.ConnectionConfiguration;
-import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
-import org.jivesoftware.smack.ConnectionListener;
-import org.jivesoftware.smack.PacketInterceptor;
-import org.jivesoftware.smack.PacketListener;
-import org.jivesoftware.smack.XMPPConnection;
-import org.jivesoftware.smack.XMPPException;
-import org.jivesoftware.smack.filter.PacketTypeFilter;
-import org.jivesoftware.smack.packet.DefaultPacketExtension;
-import org.jivesoftware.smack.packet.Message;
-import org.jivesoftware.smack.packet.Packet;
-import org.jivesoftware.smack.packet.PacketExtension;
-import org.jivesoftware.smack.provider.PacketExtensionProvider;
-import org.jivesoftware.smack.provider.ProviderManager;
-import org.jivesoftware.smack.util.StringUtils;
-import org.json.simple.JSONValue;
-import org.json.simple.parser.ParseException;
-import org.xmlpull.v1.XmlPullParser;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Random;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import javax.net.ssl.SSLSocketFactory;
-/**
- * Sample Smack implementation of a client for GCM Cloud Connection Server.
- *
- * &lt;p&gt;For illustration purposes only.
- */
-public class SmackCcsClient {
-
-  Logger logger = Logger.getLogger(&quot;SmackCcsClient&quot;);
-
-  public static final String GCM_SERVER = &quot;gcm.googleapis.com&quot;;
-  public static final int GCM_PORT = 5235;
-
-  public static final String GCM_ELEMENT_NAME = &quot;gcm&quot;;
-  public static final String GCM_NAMESPACE = &quot;google:mobile:data&quot;;
-
-  static Random random = new Random();
-  XMPPConnection connection;
-  ConnectionConfiguration config;
-
-  /**
-   * XMPP Packet Extension for GCM Cloud Connection Server.
-   */
-  class GcmPacketExtension extends DefaultPacketExtension {
-    String json;
-
-    public GcmPacketExtension(String json) {
-      super(GCM_ELEMENT_NAME, GCM_NAMESPACE);
-      this.json = json;
-    }
-
-    public String getJson() {
-      return json;
-    }
-
-    &#64;Override
-    public String toXML() {
-      return String.format(&quot;&lt;%s xmlns=\&quot;%s\&quot;&gt;%s&lt;/%s&gt;&quot;, GCM_ELEMENT_NAME,
-          GCM_NAMESPACE, json, GCM_ELEMENT_NAME);
-    }
-
-    &#64;SuppressWarnings(&quot;unused&quot;)
-    public Packet toPacket() {
-      return new Message() {
-        // Must override toXML() because it includes a &lt;body&gt;
-        &#64;Override
-        public String toXML() {
-
-          StringBuilder buf = new StringBuilder();
-          buf.append(&quot;&lt;message&quot;);
-          if (getXmlns() != null) {
-            buf.append(&quot; xmlns=\&quot;&quot;).append(getXmlns()).append(&quot;\&quot;&quot;);
-          }
-          if (getLanguage() != null) {
-            buf.append(&quot; xml:lang=\&quot;&quot;).append(getLanguage()).append(&quot;\&quot;&quot;);
-          }
-          if (getPacketID() != null) {
-            buf.append(&quot; id=\&quot;&quot;).append(getPacketID()).append(&quot;\&quot;&quot;);
-          }
-          if (getTo() != null) {
-            buf.append(&quot; to=\&quot;&quot;).append(StringUtils.escapeForXML(getTo())).append(&quot;\&quot;&quot;);
-          }
-          if (getFrom() != null) {
-            buf.append(&quot; from=\&quot;&quot;).append(StringUtils.escapeForXML(getFrom())).append(&quot;\&quot;&quot;);
-          }
-          buf.append(&quot;&gt;&quot;);
-          buf.append(GcmPacketExtension.this.toXML());
-          buf.append(&quot;&lt;/message&gt;&quot;);
-          return buf.toString();
-        }
-      };
-    }
-  }
-
-  public SmackCcsClient() {
-    // Add GcmPacketExtension
-    ProviderManager.getInstance().addExtensionProvider(GCM_ELEMENT_NAME,
-        GCM_NAMESPACE, new PacketExtensionProvider() {
-
-      &#64;Override
-      public PacketExtension parseExtension(XmlPullParser parser)
-          throws Exception {
-        String json = parser.nextText();
-        GcmPacketExtension packet = new GcmPacketExtension(json);
-        return packet;
-      }
-    });
-  }
-
-  /**
-   * Returns a random message id to uniquely identify a message.
-   *
-   * &lt;p&gt;Note:
-   * This is generated by a pseudo random number generator for illustration purpose,
-   * and is not guaranteed to be unique.
-   *
-   */
-  public String getRandomMessageId() {
-    return &quot;m-&quot; + Long.toString(random.nextLong());
-  }
-
-  /**
-   * Sends a downstream GCM message.
-   */
-  public void send(String jsonRequest) {
-    Packet request = new GcmPacketExtension(jsonRequest).toPacket();
-    connection.sendPacket(request);
-  }
-
-  /**
-   * Handles an upstream data message from a device application.
-   *
-   * &lt;p&gt;This sample echo server sends an echo message back to the device.
-   * Subclasses should override this method to process an upstream message.
-   */
-  public void handleIncomingDataMessage(Map&lt;String, Object&gt; jsonObject) {
-    String from = jsonObject.get(&quot;from&quot;).toString();
-
-    // PackageName of the application that sent this message.
-    String category = jsonObject.get(&quot;category&quot;).toString();
-
-    // Use the packageName as the collapseKey in the echo packet
-    String collapseKey = &quot;echo:CollapseKey&quot;;
-    &#64;SuppressWarnings(&quot;unchecked&quot;)
-    Map&lt;String, String&gt; payload = (Map&lt;String, String&gt;) jsonObject.get(&quot;data&quot;);
-    payload.put(&quot;ECHO&quot;, &quot;Application: &quot; + category);
-
-    // Send an ECHO response back
-    String echo = createJsonMessage(from, getRandomMessageId(), payload, collapseKey, null, false);
-    send(echo);
-  }
-
-  /**
-   * Handles an ACK.
-   *
-   * &lt;p&gt;By default, it only logs a {@code INFO} message, but subclasses could override it to
-   * properly handle ACKS.
-   */
-  public void handleAckReceipt(Map&lt;String, Object&gt; jsonObject) {
-    String messageId = jsonObject.get(&quot;message_id&quot;).toString();
-    String from = jsonObject.get(&quot;from&quot;).toString();
-    logger.log(Level.INFO, &quot;handleAckReceipt() from: &quot; + from + &quot;, messageId: &quot; + messageId);
-  }
-
-  /**
-   * Handles a NACK.
-   *
-   * &lt;p&gt;By default, it only logs a {@code INFO} message, but subclasses could override it to
-   * properly handle NACKS.
-   */
-  public void handleNackReceipt(Map&lt;String, Object&gt; jsonObject) {
-    String messageId = jsonObject.get(&quot;message_id&quot;).toString();
-    String from = jsonObject.get(&quot;from&quot;).toString();
-    logger.log(Level.INFO, &quot;handleNackReceipt() from: &quot; + from + &quot;, messageId: &quot; + messageId);
-  }
-
-  /**
-   * Creates a JSON encoded GCM message.
-   *
-   * &#64;param to RegistrationId of the target device (Required).
-   * &#64;param messageId Unique messageId for which CCS will send an &quot;ack/nack&quot; (Required).
-   * &#64;param payload Message content intended for the application. (Optional).
-   * &#64;param collapseKey GCM collapse_key parameter (Optional).
-   * &#64;param timeToLive GCM time_to_live parameter (Optional).
-   * &#64;param delayWhileIdle GCM delay_while_idle parameter (Optional).
-   * &#64;return JSON encoded GCM message.
-   */
-  public static String createJsonMessage(String to, String messageId, Map&lt;String, String&gt; payload,
-      String collapseKey, Long timeToLive, Boolean delayWhileIdle) {
-    Map&lt;String, Object&gt; message = new HashMap&lt;String, Object&gt;();
-    message.put(&quot;to&quot;, to);
-    if (collapseKey != null) {
-      message.put(&quot;collapse_key&quot;, collapseKey);
-    }
-    if (timeToLive != null) {
-      message.put(&quot;time_to_live&quot;, timeToLive);
-    }
-    if (delayWhileIdle != null &amp;&amp; delayWhileIdle) {
-      message.put(&quot;delay_while_idle&quot;, true);
-    }
-    message.put(&quot;message_id&quot;, messageId);
-    message.put(&quot;data&quot;, payload);
-    return JSONValue.toJSONString(message);
-  }
-
-  /**
-   * Creates a JSON encoded ACK message for an upstream message received from an application.
-   *
-   * &#64;param to RegistrationId of the device who sent the upstream message.
-   * &#64;param messageId messageId of the upstream message to be acknowledged to CCS.
-   * &#64;return JSON encoded ack.
-   */
-  public static String createJsonAck(String to, String messageId) {
-    Map&lt;String, Object&gt; message = new HashMap&lt;String, Object&gt;();
-    message.put(&quot;message_type&quot;, &quot;ack&quot;);
-    message.put(&quot;to&quot;, to);
-    message.put(&quot;message_id&quot;, messageId);
-    return JSONValue.toJSONString(message);
-  }
-
-  /**
-   * Connects to GCM Cloud Connection Server using the supplied credentials.
-   *
-   * &#64;param username GCM_SENDER_ID&#64;gcm.googleapis.com
-   * &#64;param password API Key
-   * &#64;throws XMPPException
-   */
-  public void connect(String username, String password) throws XMPPException {
-    config = new ConnectionConfiguration(GCM_SERVER, GCM_PORT);
-    config.setSecurityMode(SecurityMode.enabled);
-    config.setReconnectionAllowed(true);
-    config.setRosterLoadedAtLogin(false);
-    config.setSendPresence(false);
-    config.setSocketFactory(SSLSocketFactory.getDefault());
-
-    // NOTE: Set to true to launch a window with information about packets sent and received
-    config.setDebuggerEnabled(true);
-
-    // -Dsmack.debugEnabled=true
-    XMPPConnection.DEBUG_ENABLED = true;
-
-    connection = new XMPPConnection(config);
-    connection.connect();
-
-    connection.addConnectionListener(new ConnectionListener() {
-
-      &#64;Override
-      public void reconnectionSuccessful() {
-        logger.info(&quot;Reconnecting..&quot;);
-      }
-
-      &#64;Override
-      public void reconnectionFailed(Exception e) {
-        logger.log(Level.INFO, &quot;Reconnection failed.. &quot;, e);
-      }
-
-      &#64;Override
-      public void reconnectingIn(int seconds) {
-        logger.log(Level.INFO, &quot;Reconnecting in %d secs&quot;, seconds);
-      }
-
-      &#64;Override
-      public void connectionClosedOnError(Exception e) {
-        logger.log(Level.INFO, &quot;Connection closed on error.&quot;);
-      }
-
-      &#64;Override
-      public void connectionClosed() {
-        logger.info(&quot;Connection closed.&quot;);
-      }
-    });
-
-    // Handle incoming packets
-    connection.addPacketListener(new PacketListener() {
-
-      &#64;Override
-      public void processPacket(Packet packet) {
-        logger.log(Level.INFO, &quot;Received: &quot; + packet.toXML());
-        Message incomingMessage = (Message) packet;
-        GcmPacketExtension gcmPacket =
-            (GcmPacketExtension) incomingMessage.getExtension(GCM_NAMESPACE);
-        String json = gcmPacket.getJson();
-        try {
-          &#64;SuppressWarnings(&quot;unchecked&quot;)
-          Map&lt;String, Object&gt; jsonObject =
-              (Map&lt;String, Object&gt;) JSONValue.parseWithException(json);
-
-          // present for &quot;ack&quot;/&quot;nack&quot;, null otherwise
-          Object messageType = jsonObject.get(&quot;message_type&quot;);
-
-          if (messageType == null) {
-            // Normal upstream data message
-            handleIncomingDataMessage(jsonObject);
-
-            // Send ACK to CCS
-            String messageId = jsonObject.get(&quot;message_id&quot;).toString();
-            String from = jsonObject.get(&quot;from&quot;).toString();
-            String ack = createJsonAck(from, messageId);
-            send(ack);
-          } else if (&quot;ack&quot;.equals(messageType.toString())) {
-            // Process Ack
-            handleAckReceipt(jsonObject);
-          } else if (&quot;nack&quot;.equals(messageType.toString())) {
-            // Process Nack
-            handleNackReceipt(jsonObject);
-          } else {
-            logger.log(Level.WARNING, &quot;Unrecognized message type (%s)&quot;,
-                messageType.toString());
-          }
-        } catch (ParseException e) {
-          logger.log(Level.SEVERE, &quot;Error parsing JSON &quot; + json, e);
-        } catch (Exception e) {
-          logger.log(Level.SEVERE, &quot;Couldn't send echo.&quot;, e);
-        }
-      }
-    }, new PacketTypeFilter(Message.class));
-
-
-    // Log all outgoing packets
-    connection.addPacketInterceptor(new PacketInterceptor() {
-      &#64;Override
-      public void interceptPacket(Packet packet) {
-        logger.log(Level.INFO, &quot;Sent: {0}&quot;,  packet.toXML());
-      }
-    }, new PacketTypeFilter(Message.class));
-
-    connection.login(username, password);
-  }
-
-  public static void main(String [] args) {
-    final String userName = &quot;Your GCM Sender Id&quot; + &quot;&#64;gcm.googleapis.com&quot;;
-    final String password = &quot;API Key&quot;;
-
-    SmackCcsClient ccsClient = new SmackCcsClient();
-
-    try {
-      ccsClient.connect(userName, password);
-    } catch (XMPPException e) {
-      e.printStackTrace();
-    }
-
-    // Send a sample hello downstream message to a device.
-    String toRegId = &quot;RegistrationIdOfTheTargetDevice&quot;;
-    String messageId = ccsClient.getRandomMessageId();
-    Map&lt;String, String&gt; payload = new HashMap&lt;String, String&gt;();
-    payload.put(&quot;Hello&quot;, &quot;World&quot;);
-    payload.put(&quot;CCS&quot;, &quot;Dummy Message&quot;);
-    payload.put(&quot;EmbeddedMessageId&quot;, messageId);
-    String collapseKey = &quot;sample&quot;;
-    Long timeToLive = 10000L;
-    Boolean delayWhileIdle = true;
-    ccsClient.send(createJsonMessage(toRegId, messageId, payload, collapseKey,
-        timeToLive, delayWhileIdle));
-  }
-}</pre>
-<h3 id="python">Python sample</h3>
-
-<p>Here is an example of a CCS app server written in Python. This sample echo
-server sends an initial message, and for every upstream message received, it sends
-a dummy response back to the application that sent the upstream message. This
-example illustrates how to connect, send, and receive GCM messages using XMPP. It
-shouldn't be used as-is on a production deployment.</p>
-
-<pre>
-#!/usr/bin/python
-import sys, json, xmpp, random, string
-
-SERVER = 'gcm.googleapis.com'
-PORT = 5235
-USERNAME = "Your GCM Sender Id"
-PASSWORD = "API Key"
-REGISTRATION_ID = "Registration Id of the target device"
-
-unacked_messages_quota = 1000
-send_queue = []
-
-# Return a random alphanumerical id
-def random_id():
-  rid = ''
-  for x in range(8): rid += random.choice(string.ascii_letters + string.digits)
-  return rid
-
-def message_callback(session, message):
-  global unacked_messages_quota
-  gcm = message.getTags('gcm')
-  if gcm:
-    gcm_json = gcm[0].getData()
-    msg = json.loads(gcm_json)
-    if not msg.has_key('message_type'):
-      # Acknowledge the incoming message immediately.
-      send({'to': msg['from'],
-            'message_type': 'ack',
-            'message_id': msg['message_id']})
-      # Queue a response back to the server.
-      if msg.has_key('from'):
-        # Send a dummy echo response back to the app that sent the upstream message.
-        send_queue.append({'to': msg['from'],
-                           'message_id': random_id(),
-                           'data': {'pong': 1}})
-    elif msg['message_type'] == 'ack' or msg['message_type'] == 'nack':
-      unacked_messages_quota += 1
-
-def send(json_dict):
-  template = (&quot;&lt;message&gt;&lt;gcm xmlns='google:mobile:data'&gt;{1}&lt;/gcm&gt;&lt;/message&gt;&quot;)
-  client.send(xmpp.protocol.Message(
-      node=template.format(client.Bind.bound[0], json.dumps(json_dict))))
-
-def flush_queued_messages():
-  global unacked_messages_quota
-  while len(send_queue) and unacked_messages_quota &gt; 0:
-    send(send_queue.pop(0))
-    unacked_messages_quota -= 1
-
-client = xmpp.Client('gcm.googleapis.com', debug=['socket'])
-client.connect(server=(SERVER,PORT), secure=1, use_srv=False)
-auth = client.auth(USERNAME, PASSWORD)
-if not auth:
-  print 'Authentication failed!'
-  sys.exit(1)
-
-client.RegisterHandler('message', message_callback)
-
-send_queue.append({'to': REGISTRATION_ID,
-                   'message_id': 'reg_id',
-                   'data': {'message_destination': 'RegId',
-                            'message_id': random_id()}})
-
-while True:
-  client.Process(1)
-  flush_queued_messages()</pre>
diff --git a/docs/html/google/gcm/client.jd b/docs/html/google/gcm/client.jd
index df357a2..7604932 100644
--- a/docs/html/google/gcm/client.jd
+++ b/docs/html/google/gcm/client.jd
@@ -1,663 +1,24 @@
-page.title=Implementing GCM Client
+page.title=GCM Client
 page.tags="cloud","push","messaging"
 @jd:body
 
 <div id="qv-wrapper">
 <div id="qv">
 
-
-<h2>In this document</h2>
-
-<ol class="toc">
-<li><a href="#play-services">Set Up Google Play Services</a></li>
-<li><a href="#manifest">Edit Your Application's Manifest</a></li>
-<li><a href="#app">Write Your Application</a>
-  <ol class="toc">
-    <li><a href="#sample-play">Check for Google Play Services APK</a></li>
-    <li><a href="#sample-register">Register for GCM</a></li>
-    <li><a href="#sample-send">Send a message</a></li>
-    <li><a href="#sample-receive">Receive a message</a></li>
-  </ol>
-  <li><a href="#run">Running the Sample</a></li>
-  <li><a href="#stats">Viewing Statistics</a></li>
-</li>
-
-</ol>
-
 <h2>See Also</h2>
 
 <ol class="toc">
 <li><a href="gs.html">Getting Started</a></li>
-<li><a href="server.html">Implementing GCM Server</a></li>
+<li><a href="server.html">GCM Server</a></li>
 </ol>
 
 </div>
 </div>
 
-<p>A GCM client is a GCM-enabled app that runs on an Android device. To write your
-client code, we recommend that you use the
-<a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">
-{@code GoogleCloudMessaging}</a> APIs.
-The client helper library that was offered in previous versions of GCM still works,
-but it has been superseded by the more efficient
-<a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">
-{@code GoogleCloudMessaging}</a> APIs.</p>
+<p>A GCM client is a GCM-enabled app that runs on an Android device. To write your client code, we recommend that you use the new <a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">{@code GoogleCloudMessaging}</a> APIs. The client helper library that was offered in previous versions of GCM still works, but it has been superseded by the more efficient <a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">{@code GoogleCloudMessaging}</a> APIs.</p>
 
-<p>A full GCM implementation requires both a client implementation and a server
-implementation. For more
-information about implementing the server side, see <a href="server.html">
-Implementing GCM Server</a>.</p>
+<p>A full GCM implementation requires both a client implementation and a server-side implementation. For a step-by-step guide to creating a complete sample implementation that includes both client and server, see <a href="gs.html">Getting Started</a>. </p>
 
-<p>The following sections walk you through the steps involved in writing a GCM
-client-side application. Your client app can be arbitrarily complex, but at bare
-minimum, a GCM client app must include code to register (and thereby get a
-registration ID), and a broadcast receiver to receive messages sent by GCM.
-</p>
-
-<h2 id="play-services">Step 1: Set Up Google Play Services</h2>
-
-<p>To write your client application, use the
-<a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">
-{@code GoogleCloudMessaging}</a> API.
-To use this API, you must set up your project to use the Google Play services SDK,
-as described in <a href="/google/play-services/setup.html">Setup Google Play
-Services SDK</a>.</p>
-
-<p class="note"><strong>Caution:</strong> When you add the Play Services library to
-your project, be sure to add it <em>with resources</em>, as described in
-<a href="{@docRoot}google/play-services/setup.html#Setup">
-Setup Google Play Services SDK</a>. The key point is that you must
-<em>reference</em> the library&mdash;simply adding a {@code .jar} file to
-your Eclipse project will not work. You must follow the directions
-for referencing a library, or your app won't be able to access
-the library's resources, and it won't run properly.
-If you're using Android Studio, this is the string to add to the
-{@code dependency} section of your application's {@code build.gradle} file:</p>
-
-<pre>dependencies {
-   compile: "com.google.android.gms:play-services:3.1.+"
-}
-</pre>
-
-
-<h2 id="manifest">Step 2: Edit Your Application's Manifest</h2>
-
-<p>Add the following to your application's manifest:</p>
-<ul>
-  <li>The <code>com.google.android.c2dm.permission.RECEIVE</code> permission so
-the Android application can register and receive messages.</li>
-  <li>The <code>android.permission.INTERNET</code> permission so the Android
-application can send the registration ID to the 3rd party server.</li>
-  <li>The <code>android.permission.GET_ACCOUNTS</code> permission as GCM requires
-a Google account (necessary only if if the device is running a version lower than
-Android 4.0.4)</li>
-  <li>The <code>android.permission.WAKE_LOCK</code> permission so the application
-can keep the processor from sleeping when a message is received. Optional&mdash;use
-only if the app wants to keep the device from sleeping.</li>
-  <li>An <code>applicationPackage + &quot;.permission.C2D_MESSAGE&quot;</code>
-permission to prevent other Android applications from registering and receiving
-the Android application's messages. The permission name must exactly match this
-pattern&mdash;otherwise the Android application will not receive the messages.</li>
-   <li>A receiver for <code>com.google.android.c2dm.intent.RECEIVE</code>, with
-the category set
-as <code>applicationPackage</code>. The receiver should require the
-<code>com.google.android.c2dm.SEND</code> permission, so that only the GCM
-Framework can send a message to it. If your app uses an {@link android.app.IntentService}
-(not required, but a common pattern), this receiver should be an instance of
-{@link android.support.v4.content.WakefulBroadcastReceiver}.
-A {@link android.support.v4.content.WakefulBroadcastReceiver} takes care of
-creating and managing a
-<a href="{@docRoot}reference/android/os/PowerManager.html#PARTIAL_WAKE_LOCK">
-partial wake lock</a> for your app.</li>
-
-<li>A {@link android.app.Service} (typically an {@link android.app.IntentService})
-to which the {@link android.support.v4.content.WakefulBroadcastReceiver} passes off
-the work of handling the GCM message, while ensuring that the device does not
-go back to sleep in the process. Including an {@link android.app.IntentService} is
-optional&mdash;you could choose to process your messages in a regular
-{@link android.content.BroadcastReceiver} instead, but realistically, most apps will
-use a {@link android.app.IntentService}.
-</li>
-  <li>If the GCM feature is critical to the Android application's function, be sure to
-set <code>android:minSdkVersion=&quot;8&quot;</code> or higher in the manifest. This
-ensures that the Android application cannot be installed in an environment in which it
-could not run properly. </li>
-</ul>
-
-<p>Here are excerpts from a sample manifest that supports GCM:</p>
-
-<pre class="prettyprint pretty-xml">
-&lt;manifest package="com.example.gcm" ...&gt;
-
-    &lt;uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17"/&gt;
-    &lt;uses-permission android:name="android.permission.INTERNET" /&gt;
-    &lt;uses-permission android:name="android.permission.GET_ACCOUNTS" /&gt;
-    &lt;uses-permission android:name="android.permission.WAKE_LOCK" /&gt;
-    &lt;uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /&gt;
-
-    &lt;permission android:name="com.example.gcm.permission.C2D_MESSAGE"
-        android:protectionLevel="signature" /&gt;
-    &lt;uses-permission android:name="com.example.gcm.permission.C2D_MESSAGE" /&gt;
-
-    &lt;application ...&gt;
-        &lt;receiver
-            android:name=".GcmBroadcastReceiver"
-            android:permission="com.google.android.c2dm.permission.SEND" &gt;
-            &lt;intent-filter&gt;
-                &lt;action android:name="com.google.android.c2dm.intent.RECEIVE" /&gt;
-                &lt;category android:name="com.example.gcm" /&gt;
-            &lt;/intent-filter&gt;
-        &lt;/receiver&gt;
-        &lt;service android:name=".GcmIntentService" /&gt;
-    &lt;/application&gt;
-
-&lt;/manifest&gt;
-</pre>
-
-<h2 id="app"> Step 3: Write Your Application</h2>
-
-<p>Finally, write your application. This section features a sample client
-application that illustrates how to use the
-<a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">
-{@code GoogleCloudMessaging}</a> APIs. The sample consists of a main activity
-({@code DemoActivity}), a {@link android.support.v4.content.WakefulBroadcastReceiver}
-({@code GcmBroadcastReceiver}), and an {@link android.app.IntentService}
-({@code GcmIntentService}). You can find the complete source code for this sample at the
-<a href="http://code.google.com/p/gcm">open source site</a>.</p>
-
-<p>Note the following:</p>
-
-<ul>
-  <li>Among other things, the sample illustrates registration and upstream
-(device-to-cloud) messaging. Upstream messaging only applies to apps that are running against a
-<a href="ccs.html">CCS</a> (XMPP) server; HTTP-based servers don't support upstream messaging.</li>
-  <li>The <a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">
-  {@code GoogleCloudMessaging}</a>
-registration APIs replace the old registration process, which was based on the
-now-obsolete client helper library. While the old registration process still works,
-we encourage you to use the newer
-<a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">
-{@code GoogleCloudMessaging}</a>
-registration APIs, regardless of your underlying server.</li>
-</ul>
-
-<h3 id="sample-play">Check for Google Play Services APK</h3>
-
-<p>As described in <a href="{@docRoot}google/play-services/setup.html">
-Setup Google Play Services SDK</a>, apps that rely on the Play Services SDK
-should always check the device for a compatible Google Play services APK before
-accessing Google Play services features. In the sample app this check is done in
-two places: in the main activity's {@code onCreate()} method, and in its
-{@code onResume()} method. The check in {@code onCreate()} ensures that the app
-can't be used without a successful check. The check in {@code onResume()} ensures
-that if the user returns to the running app through some other means, such as
-through the back button, the check is still performed. If the
-device doesn't have a compatible Google Play services APK, your app can call
-{@code GooglePlayServicesUtil.getErrorDialog()} to allow users to download the
-APK from the Google Play Store or enable it in the device's system settings.
-For example:</p>
-
-<pre>private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
-...
-&#64;Override
-public void onCreate(Bundle savedInstanceState) {
-    super.onCreate(savedInstanceState);
-
-    setContentView(R.layout.main);
-    mDisplay = (TextView) findViewById(R.id.display);
-
-    context = getApplicationContext();
-
-    // Check device for Play Services APK.
-    if (checkPlayServices()) {
-        // If this check succeeds, proceed with normal processing.
-        // Otherwise, prompt user to get valid Play Services APK.
-        ...
-    }
-}
-
-// You need to do the Play Services APK check here too.
-&#64;Override
-protected void onResume() {
-    super.onResume();
-    checkPlayServices();
-}
-
-/**
- * Check the device to make sure it has the Google Play Services APK. If
- * it doesn't, display a dialog that allows users to download the APK from
- * the Google Play Store or enable it in the device's system settings.
- */
-private boolean checkPlayServices() {
-    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
-    if (resultCode != ConnectionResult.SUCCESS) {
-        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
-            GooglePlayServicesUtil.getErrorDialog(resultCode, this,
-                    PLAY_SERVICES_RESOLUTION_REQUEST).show();
-        } else {
-            Log.i(TAG, "This device is not supported.");
-            finish();
-        }
-        return false;
-    }
-    return true;
-}</pre>
-
-<h3 id="sample-register">Register for GCM</h3>
-<p>An Android application needs to register with GCM servers before it can receive
-messages. When an app registers, it receives a registration ID, which it can then
-store for future use. In the following snippet the {@code onCreate()} method in the sample app's
-main activity checks to see if the app is already registered with GCM and with
-the server:</p>
-
-<pre>/**
- * Main UI for the demo app.
- */
-public class DemoActivity extends Activity {
-
-    public static final String EXTRA_MESSAGE = "message";
-    public static final String PROPERTY_REG_ID = "registration_id";
-    private static final String PROPERTY_APP_VERSION = "appVersion";
-    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
-
-    /**
-     * Substitute you own sender ID here. This is the project number you got
-     * from the API Console, as described in "Getting Started."
-     */
-    String SENDER_ID = "Your-Sender-ID";
-
-    /**
-     * Tag used on log messages.
-     */
-    static final String TAG = "GCMDemo";
-
-    TextView mDisplay;
-    GoogleCloudMessaging gcm;
-    AtomicInteger msgId = new AtomicInteger();
-    SharedPreferences prefs;
-    Context context;
-
-    String regid;
-
-    &#64;Override
-    public void onCreate(Bundle savedInstanceState) {
-        super.onCreate(savedInstanceState);
-
-        setContentView(R.layout.main);
-        mDisplay = (TextView) findViewById(R.id.display);
-
-        context = getApplicationContext();
-
-        // Check device for Play Services APK. If check succeeds, proceed with
-        //  GCM registration.
-        if (checkPlayServices()) {
-            gcm = GoogleCloudMessaging.getInstance(this);
-            regid = getRegistrationId(context);
-
-            if (regid.isEmpty()) {
-                registerInBackground();
-            }
-        } else {
-            Log.i(TAG, "No valid Google Play Services APK found.");
-        }
-    }
-...
-}</pre>
-
-<p>The app calls {@code getRegistrationId()} to see whether there is an existing
-registration ID stored in shared preferences:</p>
-
-<pre>/**
- * Gets the current registration ID for application on GCM service.
- * &lt;p&gt;
- * If result is empty, the app needs to register.
- *
- * &#64;return registration ID, or empty string if there is no existing
- *         registration ID.
- */
-private String getRegistrationId(Context context) {
-    final SharedPreferences prefs = getGCMPreferences(context);
-    String registrationId = prefs.getString(PROPERTY_REG_ID, "");
-    if (registrationId.isEmpty()) {
-        Log.i(TAG, "Registration not found.");
-        return "";
-    }
-    // Check if app was updated; if so, it must clear the registration ID
-    // since the existing regID is not guaranteed to work with the new
-    // app version.
-    int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
-    int currentVersion = getAppVersion(context);
-    if (registeredVersion != currentVersion) {
-        Log.i(TAG, "App version changed.");
-        return "";
-    }
-    return registrationId;
-}
-...
-/**
- * &#64;return Application's {&#64;code SharedPreferences}.
- */
-private SharedPreferences getGCMPreferences(Context context) {
-    // This sample app persists the registration ID in shared preferences, but
-    // how you store the regID in your app is up to you.
-    return getSharedPreferences(DemoActivity.class.getSimpleName(),
-            Context.MODE_PRIVATE);
-}</pre>
-
-<p>If the registration ID doesn't exist or the app was updated,
-{@code getRegistrationId()} returns an empty string
-to indicate that the app needs to get a new regID. {@code getRegistrationId()} calls
-the following method to check the app version:</p>
-
-<pre>/**
- * &#64;return Application's version code from the {&#64;code PackageManager}.
- */
-private static int getAppVersion(Context context) {
-    try {
-        PackageInfo packageInfo = context.getPackageManager()
-                .getPackageInfo(context.getPackageName(), 0);
-        return packageInfo.versionCode;
-    } catch (NameNotFoundException e) {
-        // should never happen
-        throw new RuntimeException("Could not get package name: " + e);
-    }
-}</pre>
-
-
-<p>If there isn't a valid existing registration ID, {@code DemoActivity} calls the
-following {@code registerInBackground()} method to register. Note that because the GCM
-methods {@code register()} and {@code unregister()} are blocking, this has to
-take place on a background thread. This sample uses {@link android.os.AsyncTask}
-to accomplish this:</p>
-
-<pre>
-/**
- * Registers the application with GCM servers asynchronously.
- * &lt;p&gt;
- * Stores the registration ID and app versionCode in the application's
- * shared preferences.
- */
-private void registerInBackground() {
-    new AsyncTask<Void, Void, String>() {
-        &#64;Override
-        protected String doInBackground(Void... params) {
-            String msg = "";
-            try {
-                if (gcm == null) {
-                    gcm = GoogleCloudMessaging.getInstance(context);
-                }
-                regid = gcm.register(SENDER_ID);
-                msg = "Device registered, registration ID=" + regid;
-
-                // You should send the registration ID to your server over HTTP,
-                // so it can use GCM/HTTP or CCS to send messages to your app.
-                // The request to your server should be authenticated if your app
-                // is using accounts.
-                sendRegistrationIdToBackend();
-
-                // For this demo: we don't need to send it because the device
-                // will send upstream messages to a server that echo back the
-                // message using the 'from' address in the message.
-
-                // Persist the regID - no need to register again.
-                storeRegistrationId(context, regid);
-            } catch (IOException ex) {
-                msg = "Error :" + ex.getMessage();
-                // If there is an error, don't just keep trying to register.
-                // Require the user to click a button again, or perform
-                // exponential back-off.
-            }
-            return msg;
-        }
-
-        &#64;Override
-        protected void onPostExecute(String msg) {
-            mDisplay.append(msg + "\n");
-        }
-    }.execute(null, null, null);
-    ...
-    /**
-     * Sends the registration ID to your server over HTTP, so it can use GCM/HTTP
-     * or CCS to send messages to your app. Not needed for this demo since the
-     * device sends upstream messages to a server that echoes back the message
-     * using the 'from' address in the message.
-     */
-    private void sendRegistrationIdToBackend() {
-      // Your implementation here.
-    }
-}</pre>
-
-<p>After registering, the app calls {@code storeRegistrationId()} to store the
-registration ID in shared preferences for future use. This is just one way of
-persisting a regID. You might choose to use a different approach in your app:</p>
-
-<pre>/**
- * Stores the registration ID and app versionCode in the application's
- * {&#64;code SharedPreferences}.
- *
- * &#64;param context application's context.
- * &#64;param regId registration ID
- */
-private void storeRegistrationId(Context context, String regId) {
-    final SharedPreferences prefs = getGCMPreferences(context);
-    int appVersion = getAppVersion(context);
-    Log.i(TAG, "Saving regId on app version " + appVersion);
-    SharedPreferences.Editor editor = prefs.edit();
-    editor.putString(PROPERTY_REG_ID, regId);
-    editor.putInt(PROPERTY_APP_VERSION, appVersion);
-    editor.commit();
-}</pre>
-
-<h3 id="sample-send">Send a message</h3>
-<p>When the user clicks the app's <strong>Send</strong> button, the app sends an
-upstream message using the
-<a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">
-{@code GoogleCloudMessaging}</a> APIs. In order to receive the upstream message,
-your server should be connected to CCS. You can use one of the demo servers in
-<a href="ccs.html#implement">Implementing an XMPP-based App Server</a> to run the sample and connect
-to CCS.</p>
-
-<pre>public void onClick(final View view) {
-    if (view == findViewById(R.id.send)) {
-        new AsyncTask<Void, Void, String>() {
-            &#64;Override
-            protected String doInBackground(Void... params) {
-                String msg = "";
-                try {
-                    Bundle data = new Bundle();
-                        data.putString("my_message", "Hello World");
-                        data.putString("my_action",
-                                "com.google.android.gcm.demo.app.ECHO_NOW");
-                        String id = Integer.toString(msgId.incrementAndGet());
-                        gcm.send(SENDER_ID + "@gcm.googleapis.com", id, data);
-                        msg = "Sent message";
-                } catch (IOException ex) {
-                    msg = "Error :" + ex.getMessage();
-                }
-                return msg;
-            }
-
-            &#64;Override
-            protected void onPostExecute(String msg) {
-                mDisplay.append(msg + "\n");
-            }
-        }.execute(null, null, null);
-    } else if (view == findViewById(R.id.clear)) {
-        mDisplay.setText("");
-    }
-}</pre>
-
-<h3 id="sample-receive">Receive a message</h3>
-
-<p>As described above in <a href="#manifest">Step 2</a>, the app includes a
-{@link android.support.v4.content.WakefulBroadcastReceiver} for the <code>com.google.android.c2dm.intent.RECEIVE</code>
-intent. A broadcast receiver is the mechanism GCM uses to deliver messages. When {@code onClick()}
-calls {@code gcm.send()}, it triggers the broadcast receiver's {@code onReceive()}
-method, which has the responsibility of making sure that the GCM message gets handled.</p>
-<p>A {@link android.support.v4.content.WakefulBroadcastReceiver} is a special type of
-broadcast receiver that takes care of
-creating and managing a
-<a href="{@docRoot}reference/android/os/PowerManager.html#PARTIAL_WAKE_LOCK">
-partial wake lock</a> for your app.
-It passes off the work of processing the GCM message to a
-{@link android.app.Service} (typically an
-{@link android.app.IntentService}), while ensuring that the device does not
-go back to sleep in the transition. If you don't hold a wake lock while transitioning
-the work to a service, you are effectively allowing the device to go back to sleep before
-the work completes. The net result is that the app might not finish processing
-the GCM message until some arbitrary point in the future, which is not what you want.</p>
-
-<p class="note"><strong>Note:</strong> Using {@link android.support.v4.content.WakefulBroadcastReceiver}
-is not a requirement. If you have a relatively simple app that doesn't require
-a service, you can intercept the GCM message in a regular {@link android.content.BroadcastReceiver}
-and do your processing there. Once you get the intent that GCM passes into
-your broadcast receiver's {@code onReceive()} method, what you do with it
-is up to you.</p>
-
-<p>This snippet starts {@code GcmIntentService} with the method
-{@link android.support.v4.content.WakefulBroadcastReceiver#startWakefulService startWakefulService()}.
-This method is comparable to {@link android.content.Context#startService startService()}, except that
-the {@link android.support.v4.content.WakefulBroadcastReceiver} is holding a
-wake lock when the service starts. The intent that is passed with
-{@link android.support.v4.content.WakefulBroadcastReceiver#startWakefulService startWakefulService()}
-holds an extra identifying the wake lock:</p>
-
-
-<pre>public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
-    &#64;Override
-    public void onReceive(Context context, Intent intent) {
-        // Explicitly specify that GcmIntentService will handle the intent.
-        ComponentName comp = new ComponentName(context.getPackageName(),
-                GcmIntentService.class.getName());
-        // Start the service, keeping the device awake while it is launching.
-        startWakefulService(context, (intent.setComponent(comp)));
-        setResultCode(Activity.RESULT_OK);
-    }
-}</pre>
-
-<p>The intent service shown below does the actual work of handling the GCM
-message. When the service is finished, it calls
-{@link android.support.v4.content.WakefulBroadcastReceiver#completeWakefulIntent GcmBroadcastReceiver.completeWakefulIntent()}
-to release the wake lock. The
-{@link android.support.v4.content.WakefulBroadcastReceiver#completeWakefulIntent completeWakefulIntent()}
-method has as its parameter the same intent that was
-passed in from the {@link android.support.v4.content.WakefulBroadcastReceiver}.
-</p>
-
-<p>This snippet processes the GCM message based on message type, and posts the
-result in a notification. But what you do with GCM messages in your app is up to
-you&mdash;the possibilities are endless. For example, the message might be a ping,
-telling the app to sync to a server to retrieve new content, or it might be a
-chat message that you display in the UI.</p>
-
-<pre>
-public class GcmIntentService extends IntentService {
-    public static final int NOTIFICATION_ID = 1;
-    private NotificationManager mNotificationManager;
-    NotificationCompat.Builder builder;
-
-    public GcmIntentService() {
-        super("GcmIntentService");
-    }
-
-    &#64;Override
-    protected void onHandleIntent(Intent intent) {
-        Bundle extras = intent.getExtras();
-        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
-        // The getMessageType() intent parameter must be the intent you received
-        // in your BroadcastReceiver.
-        String messageType = gcm.getMessageType(intent);
-
-        if (!extras.isEmpty()) {  // has effect of unparcelling Bundle
-            /*
-             * Filter messages based on message type. Since it is likely that GCM
-             * will be extended in the future with new message types, just ignore
-             * any message types you're not interested in, or that you don't
-             * recognize.
-             */
-            if (GoogleCloudMessaging.
-                    MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
-                sendNotification("Send error: " + extras.toString());
-            } else if (GoogleCloudMessaging.
-                    MESSAGE_TYPE_DELETED.equals(messageType)) {
-                sendNotification("Deleted messages on server: " +
-                        extras.toString());
-            // If it's a regular GCM message, do some work.
-            } else if (GoogleCloudMessaging.
-                    MESSAGE_TYPE_MESSAGE.equals(messageType)) {
-                // This loop represents the service doing some work.
-                for (int i=0; i<5; i++) {
-                    Log.i(TAG, "Working... " + (i+1)
-                            + "/5 @ " + SystemClock.elapsedRealtime());
-                    try {
-                        Thread.sleep(5000);
-                    } catch (InterruptedException e) {
-                    }
-                }
-                Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
-                // Post notification of received message.
-                sendNotification("Received: " + extras.toString());
-                Log.i(TAG, "Received: " + extras.toString());
-            }
-        }
-        // Release the wake lock provided by the WakefulBroadcastReceiver.
-        GcmBroadcastReceiver.completeWakefulIntent(intent);
-    }
-
-    // Put the message into a notification and post it.
-    // This is just one simple example of what you might choose to do with
-    // a GCM message.
-    private void sendNotification(String msg) {
-        mNotificationManager = (NotificationManager)
-                this.getSystemService(Context.NOTIFICATION_SERVICE);
-
-        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
-                new Intent(this, DemoActivity.class), 0);
-
-        NotificationCompat.Builder mBuilder =
-                new NotificationCompat.Builder(this)
-        .setSmallIcon(R.drawable.ic_stat_gcm)
-        .setContentTitle("GCM Notification")
-        .setStyle(new NotificationCompat.BigTextStyle()
-        .bigText(msg))
-        .setContentText(msg);
-
-        mBuilder.setContentIntent(contentIntent);
-        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
-    }
-}</pre>
-
-<h2 id="run">Running the Sample</h2>
-
-<p>To run the sample:</p>
-
-<ol>
-  <li>Follow the instructions in <a href="gs.html">Getting Started</a> to get your sender ID and
-  API key.</li>
-  <li>Implement your client app, as described in this document. You can find the complete source
-  code for the client app at the <a href="http://code.google.com/p/gcm">open source site</a>.</li>
-  <li>Run one of the demo servers (Java or Python) provided in
-<a href="ccs.html#implement">Implementing an XMPP-based App Server</a>. Whichever demo server you
- choose, don't forget to edit its code before running it to supply
-your sender ID and API key.
-</li>
-
-</ol>
-
-<h2 id="stats">Viewing Statistics</h2>
-
-<p>To view  statistics and any error messages for your GCM applications:</p>
-<ol>
-  <li> Go to the <code><a href="http://play.google.com/apps/publish">Developer Console</a></code>.</li>
-  <li>Login with your developer account.
-  <p>You will see a page that has a list of all of your apps.</p></li>
-  <li> Click on the &quot;statistics&quot; link next to the app for which you
-want to view GCM stats.
-  <p>Now you are on the statistics page.</p> </li>
-  <li>Go to the drop-down menu and select the GCM metric you want to view.
-  </li>
-</ol>
-<p class="note"><strong>Note:</strong> Stats on the Google API Console are not
-enabled for GCM. You must use the <a href="http://play.google.com/apps/publish">Developer Console</a>.</p>
+<p>
 
 
diff --git a/docs/html/google/gcm/gcm.jd b/docs/html/google/gcm/gcm.jd
index 3c80b5f..ceb82b0 100644
--- a/docs/html/google/gcm/gcm.jd
+++ b/docs/html/google/gcm/gcm.jd
@@ -1,23 +1,48 @@
-page.title=Overview
+page.title=GCM Architectural Overview
 @jd:body
 
 <div id="qv-wrapper">
 <div id="qv">
 
+<h2>Quickview</h2>
+
+<ul>
+<li>Get an introduction to key GCM terms and concepts.</li>
+<li>Learn the basic features of a GCM application.</li>
+<li>Understand the role of the 3rd-party application server, and how to send messages and process results.</li>
+</ul>
+
+
 <h2>In this document</h2>
 
 <ol class="toc">
-  <li><a href="#key">Key Concepts</a></li>
-  <li><a href="#arch">Architectural Overview</a></li>
-  <li><a href="#lifecycle">Lifecycle Flow</a>
-    <ol class="toc">
-      <li><a href="#register">Enable GCM</a></li>
-      <li><a href="#push-process">Send a message</a></li>
-      <li><a href="#receiving">Receive a message</a></li>
+  <li><a href="#intro">Introduction</a> </li>
+  <li><a href="#arch">Architectural Overview</a>
+    <ol>
+      <li><a href="#lifecycle">Lifecycle Flow</a></li>
+        <ol>
+          <li><a href="#register">Enable GCM</a></li>
+          <li><a href="#push-process">Send a message</a></li>
+          <li><a href="#receiving">Receive a message</a></li>
+        </ol>
+      <li><a href="#user">What Does the User See?</a></li>
     </ol>
   </li>
+  <li><a href="#server">Role of  the 3rd-party Application Server</a>
+    <ol class="toc">
+      <li><a href="#send-msg">Sending Messages</a>
+        <ol>
+          <li><a href="#request">Request format</a></li>
+          <li><a href="#response">Response format</a></li>
+        </ol>
+      </li>
+    </ol>
+    <li><a href="#stats">Viewing Statistics</a>
+  </li>
 </ol>
 
+
+
 </div>
 </div>
 
@@ -25,15 +50,24 @@
 developers  send data from servers to their Android applications on  Android
 devices, and upstream messages from the user's device back to the cloud.
 This could be a lightweight message telling the Android application
-that there is new data to be fetched from the server (for instance, a "new email"
-notification informing the application that it is out of sync with the back end),
-or it could be a message containing up to 4kb of payload
+that there is new data to be fetched from the server (for instance, a movie
+uploaded by a friend), or it could be a message containing up to 4kb of payload
 data (so apps like instant messaging can consume the message directly). The GCM
 service handles all aspects  of queueing of messages and delivery to the target
 Android application running  on the target device.</p>
+
+<p>GCM introduces GCM Cloud Connection Server (CCS), which you can use
+in tandem with GCM HTTP service/endpoint/APIs.
+CCS uses XMPP, and it offers asynchronous, bidirectional
+messaging. For more information, see
+<a href="ccs.html">GCM Cloud Connection Server</a>.
+  
   
 <p class="note"> To jump right into using GCM with your Android
-  applications, see <a href="gs.html">Getting Started</a>.</p>
+  applications, see the instructions in <a href="gs.html">Getting Started</a>.</p>
+
+
+<h2 id="intro">Introduction</h2>
 
 <p>Here are the primary characteristics of Google Cloud 
 Messaging (GCM):</p>
@@ -41,11 +75,9 @@
 <ul>
   <li>It allows 3rd-party application servers to send messages to
 their Android applications.</li>
-  <li>Using the <a href="ccs.html">GCM Cloud Connection Server</a>, you can receive
-upstream messages from the user's device.</li>
+  <li>Using the <a href="ccs.html">GCM Cloud Connection Server</a>, you can receive upstream messages from the user's device.</li>
   <li>An Android application on an Android device doesn't need to be running to receive
-messages. The system will wake up the Android application via Intent broadcast
-when the  message arrives, as long as the application is set up with the proper
+messages. The system will wake up the Android application via Intent broadcast when the  message arrives, as long as the application is set up with the proper
 broadcast receiver and permissions.</li>
   <li>It does not provide any  built-in user interface or other handling for
 message data. GCM  simply passes raw message data received straight to the
@@ -53,67 +85,57 @@
 application might post a notification, display a custom user interface, or 
 silently sync data.</li>
   <li>It requires devices running Android 2.2 or higher that also have the
-Google Play Store application installed, or or an emulator running Android 2.2
-with Google APIs. However, you are not limited to deploying your
+Google Play Store application installed, or or an emulator running Android 2.2 with Google APIs. However, you are not limited to deploying your
 Android applications through Google Play Store.</li>
-  <li>It uses an existing connection for Google services. For pre-3.0 devices,
-this requires users to
-set up their Google account on their mobile devices. A Google account is not a
-requirement on devices running Android 4.0.4 or higher.</li>
+  <li>It uses an existing connection for Google services. For pre-3.0 devices, this requires users to
+set up their Google account on their mobile devices. A Google account is not a requirement on devices running Android 4.0.4 or higher.</li>
 </ul>
-
-<h2 id="key">Key Concepts</h2>
-
+<h2 id="arch">Architectural Overview</h2>
+<p>This section gives an overview of how GCM works. </p>
 <p>This table summarizes the key terms and concepts involved in GCM. It is
 divided into these categories:</p>
 <ul>
-  <li><strong>Components</strong> &mdash; The entities that play a primary role in
+  <li><strong>Components</strong> &mdash; The physical entities that play a role in
 GCM.</li>
   <li><strong>Credentials</strong> &mdash; The IDs and tokens that are used in
 different stages of GCM to ensure that all parties have been authenticated, and
 that the message is going to the correct place.</li>
 </ul>
 
-<p class="table-caption" id="table1">
-  <strong>Table 1.</strong> GCM components and credentials.</p>
-
 <table>
   <tr>
     <th colspan="2">Components</th>
   </tr>
   <tr>
-    <td width="165"><strong>Client App</strong></td>
-    <td width="1176">The GCM-enabled Android application that is running on a
-    device. This must be a 2.2 Android device that has Google Play Store installed, and it must
-have at least one logged in Google account if the device is running a version
-lower than Android 4.0.4. Alternatively, for testing you can use an emulator
-running Android 2.2 with Google APIs.</td>
+    <td width="165"><strong>Mobile Device</strong></td>
+    <td width="1176">The device that is running an Android application that uses
+GCM. This must be a 2.2 Android device that has Google Play Store installed, and it must
+have at least one logged in Google account if the device is running a version lower than Android 4.0.4. Alternatively, for testing you can use an emulator running Android 2.2 with Google APIs.</td>
   </tr>
   <tr>
     <td><strong>3rd-party Application Server</strong></td>
-    <td>An application server that you write as part of implementing
-GCM. The 3rd-party application server sends data to an
-Android application on the device via the GCM connection server.</td>
+    <td>An application server that  developers  set up as part of implementing
+GCM in their applications. The 3rd-party application server sends data to an
+Android application on the device via the GCM server.</td>
   </tr>
   <tr>
-    <td><strong>GCM Connection Servers</strong></td>
-    <td>The Google-provided servers involved in taking messages from the 3rd-party
+    <td><strong>GCM Servers</strong></td>
+    <td>The Google servers involved in taking messages from the 3rd-party
 application server and sending them to the device. </td>
   </tr>
   <tr>
-    <th colspan="2">Credentials</th>
+    <th colspan="2"><strong>Credentials</strong></th>
   </tr>
   <tr>
     <td><strong>Sender ID</strong></td>
-    <td>A project number you acquire from the API console, as described in
-<a href="gs.html#create-proj">Getting Started</a>. The sender
-ID is used in the <a href="#register">registration process</a> to identify a
-3rd-party application server that is permitted to send messages to the device.</td>
+    <td>A project number you acquire from the API console, as described in <a href="gs.html#create-proj">Getting Started</a>. The sender
+ID is used in the <a href="#registering">registration process</a> to identify an
+Android application that is permitted to send messages to the device.</td>
   </tr>
   <tr>
     <td><strong>Application ID</strong></td>
     <td>The Android application that is registering to receive messages. The Android application
-is identified by the package name from the <a href="client.html#manifest">manifest</a>.
+is identified by the package name from the <a href="#manifest">manifest</a>.
 This  ensures that the messages are targeted to the correct Android application.</td>
   </tr>
   <tr>
@@ -136,8 +158,7 @@
   </tr>
   <tr>
     <td><strong>Google User Account</strong></td>
-    <td>For GCM to work, the mobile device must include at least one Google
-account if the device is running a version lower than Android 4.0.4.</td>
+    <td>For GCM to work, the mobile device must include at least one Google account if the device is running a version lower than Android 4.0.4.</td>
   </tr>
   <tr>
     <td><strong>Sender Auth Token</strong></td>
@@ -146,46 +167,25 @@
 The API key is included in the header of POST requests  that send messages.</td>
   </tr>
 
+  <tr>
+    <td><strong>Notification Key</strong></td>
+    <td>Part of the user notifications feature, which provides a mapping between a user and instances of an app running on multiple devices owned by the user. The {@code notification_key} is the token that GCM uses to fan out notifications to all devices whose registration IDs are associated with the key. For more discussion of this topic, see <a href="notifications.html">User Notifications</a>.</td>
+  </tr>
+
+<tr>
+    <td><strong>Notification Key Name</strong></td>
+    <td>Part of the user notifications feature. The {@code notification_key_name} is a name or identifier (can be a username for a 3rd-party app) that is unique to a given user. It is used by third parties to group together registration IDs for a single user. For more discussion of this topic, see <a href="notifications.html">User Notifications</a>.</td>
+  </tr>
+
 </table>
 
-<h2 id="arch">Architectural Overview</h2>
-
-<p>A GCM implementation includes a Google-provided
-connection server, a 3rd-party app server that interacts with the connection
-server, and a GCM-enabled client app running on an Android device:</p>
-
-<img src="{@docRoot}images/gcm/GCM-arch.png">
-
-<p class="img-caption">
-  <strong>Figure 1.</strong> GCM Architecture.
-</p>
-
-<p>This is how these components interact:</p>
-<ul>
-  <li>Google-provided <strong>GCM Connection Servers</strong> take messages from
-a 3rd-party application server and send these messages to a
-GCM-enabled Android application (the &quot;client app&quot;) running on a device.
-Currently Google provides connection servers for <a href="http.html">HTTP</a>
-and <a href="ccs.html">XMPP</a>.</li>
-  <li>The <strong>3rd-Party Application Server</strong> is a component that you
-implement to work with your chosen GCM connection server(s). App servers send
-messages to a GCM connection server; the connection server enqueues and stores the
-message, and then sends it to the device when the device is online.
-For more information, see <a href="server.html">Implementing GCM Server</a>.</li>
-  <li>The <strong>Client App</strong> is a GCM-enabled Android application running
-on a device. To receive GCM messages, this app must register with GCM and get a
-registration ID. If you are using the <a href="ccs.html">XMPP</a> (CCS) connection
-server, the client app can send "upstream" messages back to the connection server.
-For more information on how to implement the client app, see
-<a href="client.html">Implementing GCM Client</a>.</li>
-</ul>
-
-<h2 id="lifecycle">Lifecycle Flow</h2>
+<h3 id="lifecycle">Lifecycle Flow</h3>
 
 <ul>
   <li><a href="#register">Enable GCM</a>. An Android application running on a
 mobile device registers to receive messages.</li>
-
+ <li><a href="notifications.html">User Notifications</a>. A 3rd-party server can optionally group multiple registration IDs
+in a {@code notification_key} to send messages to multiple devices owned by a single user.</li>
   <li><a href="#push-process">Send a message</a>. A 3rd-party application
 server sends messages to the device.</li>
   <li><a href="#receiving">Receive a message</a>. An Android application
@@ -194,18 +194,62 @@
 
 <p>These processes are described in more detail below.</p>
 
-<h3 id="register">Enable GCM</h3>
+<h4 id="register">Enable GCM</h4>
 
-<p>The first time the Android application needs to use the messaging service, it
-calls the <a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">
-{@code GoogleCloudMessaging}</a> method {@code register()}, as discussed in
-<a href="client.html">Implementing GCM Client</a>.
-The {@code register()} method returns a registration ID. The Android
-application should store this ID for later use (for instance,
-to check in <code>onCreate()</code> if it is already registered).
+<p>This is the sequence of events that occurs when an Android application
+running on a mobile device registers to receive messages:<span
+class="red-text"></span></p>
+
+<ol>
+  <li>The first time the Android application needs to use the messaging service, it
+fires off a registration Intent to a GCM server.
+    <p>This registration Intent
+(<code>com.google.android.c2dm.intent.REGISTER</code>) includes the sender ID, and the Android application ID.</p>
+<p class="note"><strong>Note:</strong> Because there is no lifecycle method that is called when the application is run for
+the first time, the registration intent should be sent on <code>onCreate()</code>, but only if the application is not registered yet.
 </p>
+  </li>
+  <li>If the registration is successful, the GCM server broadcasts a <code>com.google.android.c2dm.intent.REGISTRATION</code> intent which gives the Android application  a registration
+ID. 
+    <p>The Android application should store this ID for later use (for instance, to check on <code>onCreate()</code> if it is already registered).
+Note that Google may periodically refresh the registration ID, so you should design your Android application
+with the understanding that the <code>com.google.android.c2dm.intent.REGISTRATION</code> intent may be called
+multiple times. Your Android application needs to be able to respond
+accordingly.</p></li>
+  <li>To complete the registration, the Android application sends the registration ID to
+the application server. The application server typically stores the registration
+ID in a database. </li>
+</ol>
 
-<h3 id="push-process">Send a message</h3>
+<p>The registration ID lasts until the Android application explicitly unregisters
+itself, or until Google refreshes the registration ID for your Android application.</p>
+
+<p class="note"><strong>Note:</strong> When users uninstall an application, it is not automatically unregistered on GCM. It is only  unregistered when the GCM server tries to send a message to the device and the device answers that the application is uninstalled or it does not have a broadcast receiver configured to receive <code>com.google.android.c2dm.intent.RECEIVE</code> intents. At that point, your server should mark the device as unregistered (the server will receive a <code><a href="#unreg_device">NotRegistered</a></code> error).</p>
+  <p>
+Note that it might take a few minutes for the registration ID to be completely removed from the GCM server. So if the 3rd-party server sends a message during this time, it will get a valid message ID, even though the message will not be delivered to the device.</p>
+
+
+
+
+<h4 id="push-process">Send a Message</h4>
+
+<p>For an application server to send a  message to an Android application, the following things must be in
+place:</p>
+
+<ul>
+  <li>The Android application has stored a target that it can specify as the recipient of a message. This can be one of the following:
+  <ul>
+    <li>A single registration ID (or an array of registration IDs) that allows the app to receive messages
+for a particular device.</li>
+    <li>A {@code notification_key} and corresponding {@code notification_key_name}, used to map a single user to multiple registration IDs. For more discussion of this topic, see <a href="notifications.html">User Notifications</a>.</li>
+  </ul>
+    </li>
+
+<li>An API key. This is something that the developer must have already
+set up on the application server for the Android application (for more discussion, see
+<a href="#server">Role of the 3rd-party Application Server</a>). Now it will
+get used to send messages to the device. </li>
+</ul>
 
 <p>Here is the sequence of events that occurs when the application server sends a 
 message:</p>
@@ -220,14 +264,13 @@
 targeted Android application gets the message. This wakes the Android application up. The
 Android application does not need to be running beforehand to receive the message.</li>
   <li>The Android application processes the message. If the Android application is doing
-non-trivial processing, you may want to grab a
-{@link android.os.PowerManager.WakeLock} and do any processing in a service.</li>
+non-trivial processing, you may want to grab a {@link android.os.PowerManager.WakeLock} and do any processing in a Service.</li>
 </ol>
 
 <p> An Android application can  unregister GCM if it no longer wants to receive 
 messages.</p>
 
-<h3 id="receiving">Receive a message</h3>
+<h4 id="receiving">Receive a Message</h4>
 
 <p>This is the sequence of events that occurs when an Android application
 installed on a mobile device receives a message:</p>
@@ -239,8 +282,482 @@
 in a <code>com.google.android.c2dm.intent.RECEIVE</code> Intent as a set of
 extras.</li>
   <li>The Android application extracts the raw data
-from the <code>com.google.android.c2dm.intent.RECEIVE</code><code> </code>Intent
-by key and processes the data.</li>
+from the <code>com.google.android.c2dm.intent.RECEIVE</code><code> </code>Intent by key and processes the data.</li>
 </ol>
 
+<h3 id="user">What Does the User See?</h3>
+
+<p>When mobile device users install Android applications that include GCM, the Google Play Store will inform them that the Android application
+includes GCM. They must approve the use of this feature to install the
+Android application. </p>
+
+
+<h2 id="server">Role of the 3rd-party Application Server</h2>
+
+<p>Before you can write client Android applications that use the GCM feature, you must
+have an  application server that meets the following criteria:</p>
+
+<ul>
+  <li>Able to communicate with your client.</li>
+  <li>Able to  fire off HTTPS requests to the GCM server.</li>
+  <li>Able to handle requests and resend them as needed, using <a href="http://en.wikipedia.org/wiki/Exponential_backoff">exponential back-off.</a></li>
+  <li>Able to store the API key and client registration IDs. The
+API key is included in the header of POST requests that send
+messages.</li>
+</ul>
+
+<h3 id="send-msg">Sending Messages</h3>
+<p>This section describes how the 3rd-party application server sends messages to one or more mobile devices. Note the following:</p>
+<ul>
+  <li>A 3rd-party application server can either send messages to a single device or to multiple devices. A message sent to multiple devices simultaneously is called a <em>multicast message</em>.</li>
+  <li>To send a single message to multiple devices owned by a single user, you can use a {@code notification_key}, as described in <a href="notifications.html">User Notifications</a>.
+  
+  <li>You have 2 choices in how you construct requests and responses: plain text or JSON.</li>
+  <li>However, to send multicast messages, you must use JSON. Plain text will not work.</li>
+</ul>
+<p>Before the 3rd-party application server can send a  message to an
+  Android application, it must have received a registration ID from it.</p>
+<h4 id="request">Request format</h4>
+<p>To send a  message, the application server issues a POST request to <code>https://android.googleapis.com/gcm/send</code>.</p>
+<p>A  message request is made of 2 parts: HTTP header and HTTP body.</p>
+
+<p>The HTTP header must contain the following headers:</p>
+<ul>
+  <li><code>Authorization</code>: key=YOUR_API_KEY</li>
+  <li><code>Content-Type</code>: <code>application/json</code> for JSON; <code>application/x-www-form-urlencoded;charset=UTF-8</code> for plain text.
+  </li>
+</ul>
+
+<p>For example:
+</p>
+<pre>Content-Type:application/json
+Authorization:key=AIzaSyB-1uEai2WiUapxCs2Q0GZYzPu7Udno5aA
+
+{
+  "registration_ids" : ["APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx..."],
+  "data" : {
+    ...
+  },
+}</pre>
+<p class="note">
+  <p><strong>Note:</strong> If <code>Content-Type</code> is omitted, the format is assumed to be plain text.</p>
+</p>
+
+<p>The HTTP body content depends on whether you're using JSON or plain text. For JSON, it must contain a string representing a JSON object with the following fields:</p>
+<table>
+  <tr>
+    <th>Field</th>
+    <th>Description</th>
+  </tr>
+  <tr>
+    <td><code>registration_ids</code></td>
+    <td>A string array with the list of devices (registration IDs) receiving the message. It must contain at least 1 and at most 1000 registration IDs. To send a multicast message, you must use JSON. For sending a single message to a single device, you could use a JSON object with just 1 registration id, or plain text (see below). A request must include a recipient&mdash;this can be either a registration ID, an array of registration IDs, or a {@code notification_key}.</td>
+  </tr>
+ <tr>
+    <td><code>notification_key</code></td>
+    <td>A string that maps a single user to multiple registration IDs associated with that user. This
+allows a 3rd-party server to send a single message to multiple app instances (typically on multiple devices) owned by a single user. A 3rd-party server can use {@code notification_key} as the target for a message instead of an individual registration ID (or array of registration IDs). The maximum number of members allowed for a {@code notification_key} is 10. For more discussion of this topic, see <a href="notifications.html">User Notifications</a>. Optional.</td>
+  </tr>
+
+<tr>
+    <td><code>notification_key_name</code></td>
+    <td>A name or identifier (can be a username for a 3rd-party app) that is unique to a given user. It is used by 3rd parties to group together registration IDs for a single user. The <code>notification_key_name</code> should be uniquely named per app in case you have multiple apps for the same project ID. This ensures that notifications only go to the intended target app. For more discussion of this topic, see <a href="notifications.html">User Notifications</a>.</td>
+  </tr>
+
+  <tr>
+    <td><code>collapse_key</code></td>
+    <td>An arbitrary string (such as &quot;Updates Available&quot;) that is used to collapse a group of like messages
+when the device is offline, so that only the last message gets sent to the
+client. This is intended to avoid sending too many messages to the phone when it
+comes back online. Note that since there is no guarantee of the order in which
+messages get sent, the &quot;last&quot; message may not actually be the last
+message sent by the application server. See <a href="adv.html#collapsible">Advanced Topics</a> for more discussion of this topic. Optional.</td>
+  </tr>
+  <tr>
+    <td><code>data</code></td>
+    <td>A JSON object whose fields represents the key-value pairs of the message's payload data. If present, the payload data it will be
+included in the Intent as application data, with the key being the extra's name. For instance, <code>"data":{"score":"3x1"}</code> would result in an intent extra named <code>score</code> whose value is the string <code>3x1</code>. 
+
+There is no limit on the number of key/value pairs, though there is a limit on the total size of the message (4kb). The values could be any JSON object, but we recommend using strings, since the values will be converted to strings in the GCM server anyway. If you want to include objects or other non-string data types (such as integers or booleans), you have to do the conversion to string yourself. Also note that the key cannot be a reserved word (<code>from</code> or any word starting with <code>google.</code>). To complicate things slightly, there are some reserved words (such as <code>collapse_key</code>) that are technically allowed in payload data. However, if the request also contains the word, the value in the request will overwrite the value in the payload data. Hence using words that are defined as field names in this table is not recommended, even in cases where they are technically allowed. Optional.</td>
+
+
+  </tr>
+  <tr>
+    <td><code>delay_while_idle</code></td>
+    <td>If included, indicates that the message should not be sent immediately
+if the device is idle. The server will wait for the device to become active, and
+then only the last message for each <code>collapse_key</code> value will be
+sent. Optional. The default value is <code>false</code>, and must be a JSON boolean.</td>
+  </tr>
+  <tr>
+    <td><code>time_to_live</code></td>
+    <td>How long (in seconds) the message should be kept on GCM storage if the device is offline. Optional (default time-to-live is 4 weeks, and must be set as a JSON number).</td>
+  </tr>
+<tr>
+  <td><code>restricted_package_name</code></td>
+  <td>A string containing the package name of your application. When set, messages will only be sent to registration IDs that match the package name. Optional.
+  </td>
+</tr>
+<tr>
+  <td><code>dry_run</code></td>
+  <td>If included, allows developers to test their request without actually sending a message. Optional. The default value is <code>false</code>, and must be a JSON boolean.
+  </td>
+</tr>
+</table>
+
+<p>If you are using plain text instead of JSON, the message fields must be set as HTTP parameters sent in the body, and their syntax is slightly different, as described below:
+<table>
+  <tr>
+    <th>Field</th>
+    <th>Description</th>
+  </tr>
+  <tr>
+    <td><code>registration_id</code></td>
+    <td>Must contain the registration ID of the single device receiving the message. Required.</td>
+  </tr>
+  <tr>
+    <td><code>collapse_key</code></td>
+    <td>Same as JSON (see previous table). Optional.</td>
+  </tr>
+  <tr>
+    <td><code>data.&lt;key&gt;</code></td>
+
+    <td>Payload data, expressed as parameters prefixed with <code>data.</code> and suffixed as the key. For instance, a parameter of <code>data.score=3x1</code> would result in an intent extra named <code>score</code> whose value is the string <code>3x1</code>. There is no limit on the number of key/value parameters, though there is a limit on the total size of the  message. Also note that the key cannot be a reserved word (<code>from</code> or any word starting with 
+<code>google.</code>). To complicate things slightly, there are some reserved words (such as <code>collapse_key</code>) that are technically allowed in payload data. However, if the request also contains the word, the value in the request will overwrite the value in the payload data. Hence using words that are defined as field names in this table is not recommended, even in cases where they are technically allowed. Optional.</td>
+
+  </tr>
+  <tr>
+    <td><code>delay_while_idle</code></td>
+    <td>Should be represented as <code>1</code> or <code>true</code> for <code>true</code>, anything else for <code>false</code>. Optional. The default value is <code>false</code>.</td>
+  </tr>
+  <tr>
+    <td><code>time_to_live</code></td>
+    <td>Same as JSON (see previous table). Optional.</td>
+  </tr>
+<tr>
+  <td><code>restricted_package_name</code></td>
+  <td>Same as JSON (see previous table). Optional.
+  </td>
+</tr>
+<tr>
+  <td><code>dry_run</code></td>
+  <td>Same as JSON (see previous table). Optional.
+  </td>
+</tr>
+</table>
+
+<p>If you want to test your request (either JSON or plain text) without delivering the message to the devices, you can set an optional HTTP or JSON parameter called <code>dry_run</code> with the value <code>true</code>. The result will be almost identical to running the request without this parameter, except that the message will not be delivered to the devices. Consequently, the response will contain fake IDs for the message and multicast fields (see <a href="#response">Response format</a>).</p>
+
+  <h4 id="example-requests">Example requests</h4>
+  <p>Here is the smallest possible request (a message without any parameters and just one recipient) using JSON:</p>
+  <pre class="prettyprint pretty-json">{ &quot;registration_ids&quot;: [ &quot;42&quot; ] }</pre>
+  
+  <p>And here the same example using plain text:</p>
+  <pre class="prettyprint">registration_id=42</pre>
+  
+  <p> Here is a message with a payload and 6 recipients:</p>
+  <pre class="prettyprint pretty-HTML">{ "data": {
+    "score": "5x1",
+    "time": "15:10"
+  },
+  "registration_ids": ["4", "8", "15", "16", "23", "42"]
+}</pre>
+  <p>Here is a message with all optional fields set and 6 recipients:</p>
+  <pre class="prettyprint pretty-json">{ "collapse_key": "score_update",
+  "time_to_live": 108,
+  "delay_while_idle": true,
+  "data": {
+    "score": "4x8",
+    "time": "15:16.2342"
+  },
+  "registration_ids":["4", "8", "15", "16", "23", "42"]
+}</pre>
+  <p>And here is the same message using plain-text format (but just 1 recipient):  </p>
+  
+  <pre class="prettyprint">collapse_key=score_update&amp;time_to_live=108&amp;delay_while_idle=1&amp;data.score=4x8&amp;data.time=15:16.2342&amp;registration_id=42
+  </pre>
+
+<p class="note"><strong>Note:</strong> If your organization has a firewall 
+that restricts the traffic to or 
+from the Internet, you need to configure it to allow connectivity with GCM in order for
+your Android devices to receive messages. 
+The ports to open are: 5228, 5229, and 5230. GCM typically only uses 5228, but
+it sometimes uses 5229 and 5230. GCM doesn't provide specific IPs, so you should allow
+your firewall to accept outgoing connections to all IP addresses
+contained in the IP blocks listed in Google's ASN of 15169.</p>
+
+
+<h4 id="response">Response format</h4>
+
+<p>There are two possible outcomes when trying to send a message:</p>
+<ul>
+  <li>The message is processed successfully.</li>
+  <li>The GCM server rejects the request.</li>
+</ul>
+
+<p>When the message is processed successfully, the HTTP response has a 200 status and the body contains more information about the status of the message (including possible errors). When the request is rejected, 
+the HTTP response contains a non-200 status code (such as 400, 401, or 503).</p>
+
+<p>The following table summarizes the statuses that the HTTP response header might contain. Click the troubleshoot link for advice on how to deal with each type of error.</p>
+<table border=1>
+  <tr>
+    <th>Response</th>
+    <th>Description</th>
+  </tr>
+  <tr>
+    <td>200</td>
+    <td>Message was processed successfully. The response body will contain more details about the message status, but its format will depend whether the request was JSON or plain text. See <a href="#success">Interpreting a success response</a> for more details.</td>
+  </tr>
+  <tr>
+    <td>400</td>
+    <td><span id="internal-source-marker_0.2">Only applies for JSON requests. Indicates that the request could not be parsed as JSON, or it contained invalid fields (for instance, passing a string where a number was expected). The exact failure reason is described in the response and the problem should be addressed before the request can be retried.</td>
+  </tr>
+  <tr>
+    <td>401</td>
+    <td>There was an error authenticating the sender account. <a href="#auth_error">Troubleshoot</a></td>
+  </tr>
+  <tr>
+    <td>5xx</td>
+    <td>Errors in the 500-599 range (such as 500 or 503) indicate that there was an internal error in the GCM server while trying to process the request, or that the server is temporarily unavailable (for example, because of timeouts). Sender must retry later, honoring any <code>Retry-After</code> header included in the response. Application servers must implement exponential back-off. <a href="#internal_error">Troubleshoot</a></td>
+  </tr>
+</table>
+
+<h4 id="success">Interpreting a success response</h4>
+<p>When a JSON request is successful (HTTP status code 200), the response body contains a JSON object with the following fields:</p>
+<table>
+  <tr>
+    <th>Field</th>
+    <th>Description</th>
+  </tr>
+  <tr>
+    <td><code>multicast_id</code></td>
+    <td>Unique ID (number) identifying the multicast message.</td>
+  </tr>
+  <tr>
+    <td><code>success</code></td>
+    <td>Number of messages that were processed without an error.</td>
+  </tr>
+  <tr>
+    <td><code>failure</code></td>
+    <td>Number of messages that could not be processed.</td>
+  </tr>
+  <tr>
+    <td><code>canonical_ids</code></td>
+    <td>Number of results that contain a canonical registration ID. See <a href="adv.html#canonical">Advanced Topics</a> for more discussion of this topic.</td>
+  </tr>
+  <tr>
+    <td><code>results</code></td>
+    <td>Array of objects representing the status of the messages processed. The objects are listed in the same order as the request (i.e., for each registration ID in the request, its result is listed in the same index in the response) and they can have these fields:<br>
+      <ul>
+        <li><code>message_id</code>: String representing the message when it was successfully processed.</li>
+        <li><code>registration_id</code>: If set,  means that GCM processed the message but it has another canonical registration ID for that device, so sender should replace the IDs on future requests (otherwise they might be rejected). This field is never set if there is an error in the request.
+        </li>
+        <li><code>error</code>: String describing an error that occurred while processing the message for that recipient. The possible values are the same as documented in the above table, plus &quot;Unavailable&quot;  (meaning GCM servers were busy and could not process the message for that  particular recipient, so it could be retried).</li>
+    </ul></td>
+  </tr>
+</table>
+<p>If the value of <code>failure</code> and <code>canonical_ids</code> is 0, it's not necessary to parse the remainder of the response. Otherwise, we recommend that you iterate through the results field and do the following for each object in that list:</p>
+<ul>
+  <li>If <code>message_id</code> is set, check for <code>registration_id</code>:
+    <ul>
+      <li>If <code>registration_id</code> is set, replace the original ID with the new value (canonical ID) in your server database. Note that the original ID is not part of the result, so you need to obtain it from the list of <code>registration_ids</code> passed in the request (using the same index).</li>
+    </ul>
+  </li>
+  <li>Otherwise, get the value of <code>error</code>:
+    <ul>
+      <li>If it is <code>Unavailable</code>, you could retry to send it in another request.</li>
+      <li>If it is <code>NotRegistered</code>, you should remove the registration ID from your server database because the application was uninstalled from the device or it does not have a broadcast receiver configured to receive <code>com.google.android.c2dm.intent.RECEIVE</code> intents.</li>
+      <li>Otherwise, there is something wrong in the registration ID passed in the request; it is probably a non-recoverable error that will also require removing the registration from the server database. See <a href="#error_codes">Interpreting an error response</a> for all possible error values.</li>
+    </ul>
+  </li>
+</ul>
+
+<p>When a plain-text request is successful (HTTP status code 200), the response body contains 1 or 2 lines in the form of key/value pairs.
+The first line is always available and its content is either <code>id=<em>ID of sent message</em></code> or <code>Error=<em>GCM error code</em></code>. The second line, if available, 
+has the format of <code>registration_id=<em>canonical ID</em></code>. The second line is optional, and it can only be sent if the first line is not an error. We recommend handling the plain-text response in a similar way as handling the JSON response:</p>
+<ul>
+  <li>If first line starts with <code>id</code>, check second line:
+    <ul>
+      <li>If second line starts with <code>registration_id</code>, gets its value and replace the registration IDs in your server database.</li>
+    </ul>
+  </li>
+  <li>Otherwise, get the value of <code>Error</code>:
+    <ul>
+      <li>If it is <code>NotRegistered</code>, remove the registration ID from your server database.</li>
+      <li>Otherwise, there is probably a non-recoverable error (<strong>Note: </strong>Plain-text requests will never return <code>Unavailable</code> as the error code, they would have returned a 500 HTTP status instead).</li>
+    </ul>
+  </li>
+</ul>
+
+<h4 id="error_codes">Interpreting an error response</h4>
+<p>Here are the recommendations for handling the different types of error that might occur when trying to send a message to a device:</p>
+
+<dl>
+<dt id="missing_reg"><strong>Missing Registration ID</strong></dt>
+<dd>Check that the request contains a registration ID (either in the <code>registration_id</code> parameter in a plain text message, or in the <code>registration_ids</code> field in JSON). 
+<br/>Happens when error code is <code>MissingRegistration</code>.</dd>
+
+<dt id="invalid_reg"><strong>Invalid Registration ID</strong></dt>
+<dd>Check the formatting of the registration ID that you pass to the server. Make sure it matches the registration ID the phone receives in the <code>com.google.android.c2dm.intent.REGISTRATION</code> intent and that you're not truncating it or adding additional characters. 
+<br/>Happens when error code is <code>InvalidRegistration</code>.</dd>
+
+<dt id="mismatched_sender"><strong>Mismatched Sender</strong></dt>
+<dd>A registration ID is tied to a certain group of senders. When an application registers for GCM usage, it must specify which senders are allowed to send messages. Make sure you're using one of those when trying to send messages to the device. If you switch to a different sender, the existing registration IDs won't work. 
+Happens when error code is <code>MismatchSenderId</code>.</dd>
+
+<dt id="unreg_device"><strong>Unregistered Device</strong></dt>
+<dd>An existing registration ID may cease to be valid in a number of scenarios, including:
+<ul>
+  <li>If the application manually unregisters by issuing a <span class="prettyprint pretty-java"><code>com.google.android.c2dm.intent.UNREGISTER</code></span><code> </code>intent.</li>
+  <li>If the application is automatically unregistered, which can happen (but is not guaranteed) if the user uninstalls the application.</li>
+  <li>If the registration ID expires. Google might decide to refresh registration IDs. </li>
+  <li>If the application is updated but the new version does not have a broadcast receiver configured to receive <code>com.google.android.c2dm.intent.RECEIVE</code> intents.</li>
+</ul>
+For all these cases, you should remove this registration ID from the 3rd-party server and stop using it to send 
+messages. 
+<br/>Happens when error code is <code>NotRegistered</code>.</dd>
+
+<dt id="big_msg"><strong>Message Too Big</strong></dt>
+  <dd>The total size of the payload data that is included in a message can't exceed 4096 bytes. Note that this includes both the size of the keys as well as the values. 
+<br/>Happens when error code is <code>MessageTooBig</code>.</dd>
+
+<dt id="invalid_datakey"><strong>Invalid Data Key</strong></dt>
+<dd>The payload data contains a key (such as <code>from</code> or any value prefixed by <code>google.</code>) that is used internally by GCM in the  <code>com.google.android.c2dm.intent.RECEIVE</code> Intent and cannot be used. Note that some words (such as <code>collapse_key</code>) are also used by GCM but are allowed in the payload, in which case the payload value will be overridden by the GCM value. 
+<br />
+Happens when the error code is <code>InvalidDataKey</code>.</dd>
+
+<dt id="ttl_error"><strong>Invalid Time To Live</strong></dt>
+  <dd>The value for the Time to Live field must be an integer representing a duration in seconds between 0 and 2,419,200 (4 weeks). Happens when error code is <code>InvalidTtl</code>.
+</dd>
+
+  <dt id="auth_error"><strong>Authentication Error</strong></dt>
+  <dd>The sender account that you're trying to use to send a message couldn't be authenticated. Possible causes are: <ul>
+<li>Authorization header missing or with invalid syntax.</li>
+<li>Invalid project number sent as key.</li>
+<li>Key valid but with GCM service disabled.</li>
+<li>Request originated from a server not whitelisted in the Server Key IPs.</li>
+
+</ul>
+Check that the token you're sending inside the <code>Authorization</code> header is the correct API key associated with your project. You can check the validity of your API key by running the following command:<br/>
+
+<pre># api_key=YOUR_API_KEY
+
+# curl --header "Authorization: key=$api_key" --header Content-Type:"application/json" https://android.googleapis.com/gcm/send  -d "{\"registration_ids\":[\"ABC\"]}"</pre>
+
+
+
+If you receive a 401 HTTP status code, your API key is not valid. Otherwise you should see something like this:<br/>
+
+<pre>
+{"multicast_id":6782339717028231855,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
+</pre>
+If you want to confirm the validity of a registration ID, you can do so by replacing "ABC" with the registration ID.
+<br/>
+Happens when the HTTP status code is 401.
+
+  <dt id="timeout"><strong>Timeout</strong></dt>
+
+<dd>The server couldn't process the request in time. You should retry the
+same request, but you MUST obey the following requirements:
+
+<ul>
+
+<li>Honor the <code>Retry-After</code> header if it's included in the response from the GCM server.</li>
+        
+        
+<li>Implement exponential back-off in your retry mechanism. This means an
+exponentially increasing delay after each failed retry (e.g. if you waited one
+second before the first retry, wait at least two second before the next one,
+then 4 seconds and so on). If you're sending multiple messages, delay each one
+independently by an additional random amount to avoid issuing a new request for
+all messages at the same time.</li>
+    
+
+Senders that cause problems risk being blacklisted. 
+<br />
+Happens when the HTTP status code is between 501 and 599, or when the <code>error</code> field of a JSON object in the results array is <code>Unavailable</code>.
+</dd>
+
+<dt id="internal_error"><strong>Internal Server Error</strong></dt>
+
+<dd>
+The server encountered an error while trying to process the request. You
+could retry the same request (obeying the requirements listed in the <a href="#timeout">Timeout</a>
+section), but if the error persists, please report the problem in the <a href="https://groups.google.com/forum/?fromgroups#!forum/android-gcm">android-gcm group</a>.
+<br />
+Happens when the HTTP status code is 500, or when the <code>error</code> field of a JSON
+object in the results array is <code>InternalServerError</code>.
+</dd>
+
+<dt id="restricted_package_name"><strong>Invalid Package Name</strong></dt>
+
+<dd>
+A message was addressed to a registration ID whose package name did not match the value passed in the request. Happens when error code is 
+<code>InvalidPackageName</code>.
+</dd>
+
+
+</dl>
+<h4>Example responses</h4>
+<p>This section shows a few examples of responses indicating messages that were processed successfully. See <a href="#example-requests">Example requests</a> for the requests these responses are based on.</p>
+<p> Here is a simple case of a JSON message successfully sent to one recipient without canonical IDs in the response:</p>
+<pre class="prettyprint pretty-json">{ "multicast_id": 108,
+  "success": 1,
+  "failure": 0,
+  "canonical_ids": 0,
+  "results": [
+    { "message_id": "1:08" }
+  ]
+}</pre>
+
+<p>Or if the request was in plain-text format:</p>
+<pre class="prettyprint">id=1:08
+</pre>
+
+<p>Here are JSON results for 6 recipients (IDs 4, 8, 15, 16, 23, and 42 respectively) with 3 messages successfully processed, 1 canonical registration ID returned, and 3 errors:</p>
+<pre class="prettyprint pretty-json">{ "multicast_id": 216,
+  "success": 3,
+  "failure": 3,
+  "canonical_ids": 1,
+  "results": [
+    { "message_id": "1:0408" },
+    { "error": "Unavailable" },
+    { "error": "InvalidRegistration" },
+    { "message_id": "1:1516" },
+    { "message_id": "1:2342", "registration_id": "32" },
+    { "error": "NotRegistered"}
+  ]
+}
+</pre>
+<p> In this example:</p>
+<ul>
+  <li>First message: success, not required.</li>
+  <li>Second message: should be resent (to registration ID 8).</li>
+  <li>Third message: had an unrecoverable error (maybe the value got corrupted in the database).</li>
+  <li>Fourth message: success, nothing required.</li>
+  <li>Fifth message: success, but the registration ID should be updated in the server database (from 23 to 32).</li>
+  <li>Sixth message: registration ID (42) should be removed from the server database because the application was uninstalled from the device.</li>
+</ul>
+<p>Or if just the 4th message above was sent using plain-text format:</p>
+<pre class="prettyprint">Error=InvalidRegistration
+</pre>
+<p>If the 5th message above was also sent using plain-text format:</p>
+<pre class="prettyprint">id=1:2342
+registration_id=32
+</pre>
+
+<h3 id="stats">Viewing Statistics</h3>
+
+<p>To view  statistics and any error messages for your GCM applications:</p>
+<ol>
+  <li> Go to the <code><a href="http://play.google.com/apps/publish">Developer Console</a></code>.</li>
+  <li>Login with your developer account. 
+  <p>You will see a page that has a list of all of your apps.</p></li>
+  <li> Click on the &quot;statistics&quot; link next to the app for which you want to view GCM stats. 
+  <p>Now you are on the statistics page.</p> </li>
+  <li>Go to the drop-down menu and select the GCM metric you want to view. 
+  </li>
+</ol>
+<p class="note"><strong>Note:</strong> Stats on the Google API Console are not enabled for GCM. You must use the <a href="http://play.google.com/apps/publish">Developer Console</a>.</p>
+
 
diff --git a/docs/html/google/gcm/gs.jd b/docs/html/google/gcm/gs.jd
index f6b7ebe..8ceea0cc 100644
--- a/docs/html/google/gcm/gs.jd
+++ b/docs/html/google/gcm/gs.jd
@@ -1,4 +1,4 @@
-page.title=Getting Started
+page.title=Getting Started with GCM
 page.tags="cloud","push","messaging"
 @jd:body
 
@@ -12,7 +12,8 @@
 <li><a href="#create-proj">Creating a Google API Project</a></li>
 <li><a href="#gcm-service">Enabling the GCM Service</a></li>
 <li><a href="#access-key">Obtaining an API Key</a></li>
-<li><a href="#next">Next Steps</a></li>
+<li><a href="#client">Writing a Client App</a></li>
+<li><a href="#server">Writing the Server Code</a></li>
 </ol>
 
 <h2>See Also</h2>
@@ -25,12 +26,12 @@
 </div>
 </div>
 
-<p>This document tells you how to get started setting up a GCM
+<p>The sections below guide you through the process of setting up a GCM
 implementation.
-Before you begin, make sure to <a href="/google/play-services/setup.html">set up
-the Google Play Services SDK</a>. You need this SDK to use the
-<a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">
-{@code GoogleCloudMessaging}</a> methods.</p>
+Before you start, make sure to <a href="/google/play-services/setup.html">set up
+the Google Play Services SDK</a>. You need this SDK to use the <a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">{@code GoogleCloudMessaging}</a> methods.</p>
+
+<p>Note that a full GCM implementation requires a server-side implementation, in addition to the client implementation in your app. This document offers a complete example that includes both the client and server.</p>
 
 
 <h2 id="create-proj">Creating a Google API project</h2>
@@ -40,17 +41,13 @@
   </li>
   <li>If you haven't created an API project yet, this page will prompt you to do so:
   <p><img src="{@docRoot}images/gcm/gcm-create-api-proj.png" class="screenshot" /></p>
-<p class="note"><strong>Note:</strong> If you already have existing projects,
-the first page you see will be the <strong>Dashboard</strong> page. From there
-you can create a new project by opening the project drop-down menu (upper left corner)
-and choosing <strong>Other projects > Create</strong>.</p></li>
+<p class="note"><strong>Note:</strong> If you already have existing projects, the first page you see will be the <strong>Dashboard</strong> page. From there you can create a new project by opening the project drop-down menu (upper left corner) and choosing <strong>Other projects > Create</strong>.</p></li>
   <li> Click <strong>Create project</strong>.
     Your browser URL will change to something like:</li>
 
 <pre> https://code.google.com/apis/console/#project:<strong>4815162342</strong></pre>
 
-  <li> Take note of the value after <code>#project:</code> (4815162342 in this
-example). This is your project number, and it will be used later on as the GCM sender ID.</li>
+  <li> Take note of the value after <code>#project:</code> (4815162342 in this example). This is your project number, and it will be used later on as the GCM sender ID.</li>
   
 </ol>
 <h2 id="gcm-service">Enabling the GCM Service</h2>
@@ -64,53 +61,463 @@
 <h2 id="access-key">Obtaining an API Key</h2>
 <p>To obtain an API  key:</p>
 <ol>
-  <li> In the main Google APIs Console page, select <strong>API Access</strong>.
-You will see a screen that resembles the following:</li>
+  <li> In the main Google APIs Console page, select <strong>API Access</strong>. You will see a screen that resembles the following:</li><br />
 
 
-<img src="{@docRoot}images/gcm/gcm-api-access.png" style="width:400px;padding:4px;">
-
-  <li>Click  <strong>Create new Server key</strong>. Either a server key or a
-browser key should work. The advantage to using a server key is that it allows
-you to whitelist IP addresses. The following screen appears:</li>
+<img src="{@docRoot}images/gcm/gcm-api-access.png" style="width:400px;padding:4px;margin-bottom:0em;">
 
 
-<img src="{@docRoot}images/gcm/gcm-config-server-key.png" style="width:400px;padding:4px;">
+  <li>Click  <strong>Create new Server key</strong>. Either a server key or a browser key should work. The advantage to using a server key is that it allows you to whitelist IP addresses. The following screen appears:</li><br />
+
+
+<img src="{@docRoot}images/gcm/gcm-config-server-key.png" style="width:400px;padding:4px;margin-bottom:0em;">
 
   
-  <li>Click <strong>Create</strong>:</li>
+  <li>Click <strong>Create</strong>:</li><br />
   
 
-<img src="{@docRoot}images/gcm/gcm-api-key.png" style="width:400px;padding:4px;">
+<img src="{@docRoot}images/gcm/gcm-api-key.png" style="width:400px;padding:4px;margin-bottom:0em;">
 
 
 
 </ol>
-<p> Take note of the <strong>API key</strong> value (<code>YourKeyWillBeShownHere</code>)
-in this example, as it will be used later on.</p>
-<p class="note"><strong>Note:</strong> If you need to rotate the key, click
-<strong>Generate new key</strong>. A new key  will be created while the old one
-will still be active for up to 24 hours. If you want to get rid of the old key
-immediately (for example, if you feel it was compromised), click <strong>Delete key</strong>.</p>
+<p> Take note of the <strong>API key</strong> value (<code>YourKeyWillBeShownHere</code>) in this example, as it will be used later on.</p>
+<p class="note"><strong>Note:</strong> If you need to rotate the key, click  <strong>Generate new key</strong>. A new key  will be created while the old one will still be active for up to 24 hours. If you want to get rid of the old key immediately (for example, if you feel it was compromised), click <strong>Delete key</strong>.</p>
 
-<h2 id="next">Next Steps</h2>
+<p>The following sections walk you through the steps of creating client and server-side code.</p>
 
-<p>Once you've finished the tasks listed above, you're ready to start
-implementing GCM. Here is an overview of the basic steps:</p>
+<h2 id="client">Writing a Client App</h2>
 
-<ol>
-  <li>Decide which Google-provided GCM connection server you want to use&mdash;
-  <a href="http.html">HTTP</a> or <a href="ccs.html">XMPP</a> (CCS). GCM connection servers
-take messages from a 3rd-party application
-server (written by you) and send them to a GCM-enabled Android application (the
-"client app," also written by you) running on a device. </li>
-  <li>Implement an application server (the "3rd-party application server") to interact
-with your chosen GCM connection server. The app server sends data to a
-GCM-enabled Android client application via the GCM connection server. For more
-information about implementing the server side, see <a href="server.html">
-Implementing GCM Server</a>.</li>
-<li>Write your client app. This is the GCM-enabled Android application that runs
-on a device. See <a href="client.html">Implementing GCM Client</a> for more information.</li>
-</ol>
+<p>This section walks you through the steps involved in writing a client-side application&mdash;that is, the GCM-enabled application that runs on an Android device. This client sample is designed to work in conjunction with the server code shown in <a href="#server">Writing the Server Code</a>, below.</p>
+
+
+
+<h3 id="manifest">Step 1: Edit Your App's Manifest</h3>
+<ul>
+  <li>The <code>com.google.android.c2dm.permission.RECEIVE</code> permission so the Android application can register and receive messages.</li>
+  <li>The <code>android.permission.INTERNET</code> permission so the Android application can send the registration ID to the 3rd party server.</li>
+  <li>The <code>android.permission.GET_ACCOUNTS</code> permission as GCM requires a Google account (necessary only if if the device is running a version lower than Android 4.0.4)</li>
+  <li>The <code>android.permission.WAKE_LOCK</code> permission so the application can keep the processor from sleeping when a message is received. Optional&mdash;use only if the app wants to keep the device from sleeping.</li>
+  <li>An <code>applicationPackage + &quot;.permission.C2D_MESSAGE&quot;</code> permission to prevent other Android applications from registering and receiving the Android application's
+messages. The permission name must exactly match this pattern&mdash;otherwise the Android application will not receive the messages.</li>
+   <li>A receiver for <code>com.google.android.c2dm.intent.RECEIVE</code>, with the category set
+as <code>applicationPackage</code>. The receiver should require the <code>com.google.android.c2dm.SEND</code> permission, so that only the GCM
+Framework can send a message to it. Note that the receiving
+of messages is implemented as an <a href="{@docRoot}guide/components/intents-filters.html">intent</a>.</li>
+  <li>An intent service to handle the intents received by the broadcast receiver. Optional.</li>
+  <li>If the GCM feature is critical to the Android application's function, be sure to
+set <code>android:minSdkVersion=&quot;8&quot;</code> in the manifest. This
+ensures that the Android application cannot be installed in an environment in which it
+could not run properly. </li>
+</ul>
+
+<p>Here are excerpts from a manifest that supports GCM:</p>
+
+<pre class="prettyprint pretty-xml">
+&lt;manifest package="com.example.gcm" ...&gt;
+
+    &lt;uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17"/&gt;
+    &lt;uses-permission android:name="android.permission.INTERNET" /&gt;
+    &lt;uses-permission android:name="android.permission.GET_ACCOUNTS" /&gt;
+    &lt;uses-permission android:name="android.permission.WAKE_LOCK" /&gt;
+    &lt;uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /&gt;
+
+    &lt;permission android:name="com.example.gcm.permission.C2D_MESSAGE" 
+        android:protectionLevel="signature" /&gt;
+    &lt;uses-permission android:name="com.example.gcm.permission.C2D_MESSAGE" /&gt;
+
+    &lt;application ...&gt;
+        &lt;receiver
+            android:name=".MyBroadcastReceiver"
+            android:permission="com.google.android.c2dm.permission.SEND" &gt;
+            &lt;intent-filter&gt;
+                &lt;action android:name="com.google.android.c2dm.intent.RECEIVE" /&gt;
+                &lt;category android:name="com.example.gcm" /&gt;
+            &lt;/intent-filter&gt;
+        &lt;/receiver&gt;
+        &lt;service android:name=".MyIntentService" /&gt;
+    &lt;/application&gt;
+
+&lt;/manifest&gt;
+</pre>
+
+
+<h3 id="register">Step 2: Register for GCM</h3>
+
+<p>An Android application running on a mobile device registers to receive messages by calling 
+the <a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">{@code GoogleCloudMessaging}</a> method 
+<a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html#register">{@code register(senderID...)}</a>.
+This method registers the application for GCM and returns the registration ID. This streamlined approach replaces the previous
+GCM registration process. See the example below for details.</p>
+
+<h3 id="app"> Step 3: Write Your Application</h3>
+
+<p>Finally, write your application. GCM offers a variety of ways to get the job done:</p>
+
+<ul>
+  <li>For your messaging server, you can either use the new <a href="ccs.html">GCM Cloud Connection Server</a> (CCS), the older <a href="gcm.html">GCM HTTP server</a>, or both in tandem. For more discussion, see see <a href="server.html">GCM Server</a>.</li>
+  <li>To write your client application (that is, the GCM-enabled app that runs on an Android device), use the <a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">{@code GoogleCloudMessaging}</a> APIs as shown below. Don't forget to set up your project to use the Google Play services SDK as described in <a href="/google/play-services/setup.html">Setup Google Play Services SDK</a>.</li>
+</ul>
+</li>
+  
+</ul>
+
+<h4 id="example">Example</h4>
+
+<p>Here is a sample client application that illustrates how to use the <a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">{@code GoogleCloudMessaging}</a> APIs. The sample consists of a main activity ({@code DemoActivity}) and a broadcast receiver ({@code GcmBroadcastReceiver}). You can use this client sample code in conjunction with the server code shown in <a href="#server">Writing the Server Code</a>.</p>
+
+<p>Note the following:</p>
+
+<ul>
+  <li>The sample primarily illustrates two things: registration, and upstream messaging. Upstream messaging only applies to apps that are running against a <a href="ccs.html">CCS</a> server; HTTP-based servers don't support upstream messaging.</li>
+  <li>The <a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">{@code GoogleCloudMessaging}</a> registration APIs replace the old registration process, which was based on the now-obsolete client helper library. While the old registration process still works, we encourage you to use the newer <a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">{@code GoogleCloudMessaging}</a> registration APIs, regardless of your underlying server.</li>
+</ul>
+
+<h5>Registering</h5>
+<p>An Android application needs to register with GCM servers before it can receive messages. So in its {@code onCreate()} method, {@code DemoActivity} checks to see whether the app is registered with GCM and with the server:</p>
+
+<pre>/**
+ * Main UI for the demo app.
+ */
+public class DemoActivity extends Activity {
+
+    public static final String EXTRA_MESSAGE = "message";
+    public static final String PROPERTY_REG_ID = "registration_id";
+    private static final String PROPERTY_APP_VERSION = "appVersion";
+    private static final String PROPERTY_ON_SERVER_EXPIRATION_TIME =
+            "onServerExpirationTimeMs";
+    /**
+     * Default lifespan (7 days) of a reservation until it is considered expired.
+     */
+    public static final long REGISTRATION_EXPIRY_TIME_MS = 1000 * 3600 * 24 * 7;
+
+    /**
+     * Substitute you own sender ID here.
+     */
+    String SENDER_ID = "Your-Sender-ID";
+
+    /**
+     * Tag used on log messages.
+     */
+    static final String TAG = "GCMDemo";
+
+    TextView mDisplay;
+    GoogleCloudMessaging gcm;
+    AtomicInteger msgId = new AtomicInteger();
+    SharedPreferences prefs;
+    Context context;
+
+    String regid;
+
+    &#64;Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+
+        setContentView(R.layout.main);
+        mDisplay = (TextView) findViewById(R.id.display);
+
+        context = getApplicationContext();
+        regid = getRegistrationId(context);
+
+        if (regid.length() == 0) {
+            registerBackground();
+        }
+        gcm = GoogleCloudMessaging.getInstance(this);
+    }
+...
+}</pre>
+
+<p>The app calls {@code getRegistrationId()} to see whether there is an existing registration ID stored in shared preferences:</p>
+
+<pre>/**
+ * Gets the current registration id for application on GCM service.
+ * &lt;p&gt;
+ * If result is empty, the registration has failed.
+ *
+ * &#64;return registration id, or empty string if the registration is not
+ *         complete.
+ */
+private String getRegistrationId(Context context) {
+    final SharedPreferences prefs = getGCMPreferences(context);
+    String registrationId = prefs.getString(PROPERTY_REG_ID, "");
+    if (registrationId.length() == 0) {
+        Log.v(TAG, "Registration not found.");
+        return "";
+    }
+    // check if app was updated; if so, it must clear registration id to
+    // avoid a race condition if GCM sends a message
+    int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
+    int currentVersion = getAppVersion(context);
+    if (registeredVersion != currentVersion || isRegistrationExpired()) {
+        Log.v(TAG, "App version changed or registration expired.");
+        return "";
+    }
+    return registrationId;
+}
+
+...
+
+/**
+ * &#64;return Application's {&#64;code SharedPreferences}.
+ */
+private SharedPreferences getGCMPreferences(Context context) {
+    return getSharedPreferences(DemoActivity.class.getSimpleName(), 
+            Context.MODE_PRIVATE);
+}</pre>
+
+<p>If the registration ID doesn't exist, or the app was updated, or the registration ID has expired, {@code getRegistrationId()} returns an empty string to indicate that the app needs to get a new regID. {@code getRegistrationId()} calls the following methods to check the app version and whether the regID has expired:</p>
+
+<pre>/**
+ * &#64;return Application's version code from the {&#64;code PackageManager}.
+ */
+private static int getAppVersion(Context context) {
+    try {
+        PackageInfo packageInfo = context.getPackageManager()
+                .getPackageInfo(context.getPackageName(), 0);
+        return packageInfo.versionCode;
+    } catch (NameNotFoundException e) {
+        // should never happen
+        throw new RuntimeException("Could not get package name: " + e);
+    }
+}
+
+/**
+ * Checks if the registration has expired.
+ *
+ * &lt;p&gt;To avoid the scenario where the device sends the registration to the
+ * server but the server loses it, the app developer may choose to re-register
+ * after REGISTRATION_EXPIRY_TIME_MS.
+ *
+ * &#64;return true if the registration has expired.
+ */
+private boolean isRegistrationExpired() {
+    final SharedPreferences prefs = getGCMPreferences(context);
+    // checks if the information is not stale
+    long expirationTime =
+            prefs.getLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, -1);
+    return System.currentTimeMillis() > expirationTime;
+}</pre>
+
+
+<p>If there isn't a valid existing registration ID, {@code DemoActivity} calls the following {@code registerBackground()} method to register. Note that because GCM methods are blocking, this has to take place on a background thread. This sample uses {@link android.os.AsyncTask} to accomplish this:</p>
+
+<pre>
+/**
+ * Registers the application with GCM servers asynchronously.
+ * &lt;p&gt;
+ * Stores the registration id, app versionCode, and expiration time in the 
+ * application's shared preferences.
+ */
+private void registerBackground() {
+    new AsyncTask<Void, Void, String>() {
+        &#64;Override
+        protected String doInBackground(Void... params) {
+            String msg = "";
+            try {
+                if (gcm == null) {
+                    gcm = GoogleCloudMessaging.getInstance(context);
+                }
+                regid = gcm.register(SENDER_ID);
+                msg = "Device registered, registration id=" + regid;
+
+                // You should send the registration ID to your server over HTTP,
+                // so it can use GCM/HTTP or CCS to send messages to your app.
+
+                // For this demo: we don't need to send it because the device
+                // will send upstream messages to a server that echo back the message
+                // using the 'from' address in the message.
+
+                // Save the regid - no need to register again.
+                setRegistrationId(context, regid);
+            } catch (IOException ex) {
+                msg = "Error :" + ex.getMessage();
+            }
+            return msg;
+        }
+
+        &#64;Override
+        protected void onPostExecute(String msg) {
+            mDisplay.append(msg + "\n");
+        }
+    }.execute(null, null, null);
+}</pre>
+
+<p>After registering, the app calls {@code setRegistrationId()} to store the registration ID in shared preferences for future use:</p>
+
+<pre>/**
+ * Stores the registration id, app versionCode, and expiration time in the
+ * application's {&#64;code SharedPreferences}.
+ *
+ * &#64;param context application's context.
+ * &#64;param regId registration id
+ */
+private void setRegistrationId(Context context, String regId) {
+    final SharedPreferences prefs = getGCMPreferences(context);
+    int appVersion = getAppVersion(context);
+    Log.v(TAG, "Saving regId on app version " + appVersion);
+    SharedPreferences.Editor editor = prefs.edit();
+    editor.putString(PROPERTY_REG_ID, regId);
+    editor.putInt(PROPERTY_APP_VERSION, appVersion);
+    long expirationTime = System.currentTimeMillis() + REGISTRATION_EXPIRY_TIME_MS;
+
+    Log.v(TAG, "Setting registration expiry time to " +
+            new Timestamp(expirationTime));
+    editor.putLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, expirationTime);
+    editor.commit();
+}</pre>
+
+<h5>Sending a message</h5>
+<p>When the user clicks the app's <strong>Send</strong> button, the app sends an upstream message using the new <a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">{@code GoogleCloudMessaging}</a> APIs. In order to receive the upstream message, your server should be connected to CCS. You can use the code shown in <a href="#server">Writing the Server Code</a> as a sample XMPP client to connect to CCS.</p>
+
+<pre>public void onClick(final View view) {
+    if (view == findViewById(R.id.send)) {
+        new AsyncTask<Void, Void, String>() {
+            &#64;Override
+            protected String doInBackground(Void... params) {
+                String msg = "";
+                try {
+                    Bundle data = new Bundle();
+                    data.putString("hello", "World");
+                    String id = Integer.toString(msgId.incrementAndGet());
+                    gcm.send(SENDER_ID + "&#64;gcm.googleapis.com", id, data);
+                    msg = "Sent message";
+                } catch (IOException ex) {
+                    msg = "Error :" + ex.getMessage();
+                }
+                return msg;
+            }
+
+            &#64;Override
+            protected void onPostExecute(String msg) {
+                mDisplay.append(msg + "\n");
+            }
+        }.execute(null, null, null);
+    } else if (view == findViewById(R.id.clear)) {
+        mDisplay.setText("");
+    } 
+}</pre>
+
+<p>As described above in <a href="#manifest">Step 1</a>, the app includes a broadcast receiver for the <code>com.google.android.c2dm.intent.RECEIVE</code> intent. This is the mechanism GCM uses to deliver messages. When {@code onClick()} calls {@code gcm.send()}, it triggers the broadcast receiver's {@code onReceive()} method, which has the responsibility of handling the GCM message. In this sample the receiver's {@code onReceive()} method calls {@code sendNotification()} to put the message into a notification:</p>
+
+<pre>/**
+ * Handling of GCM messages.
+ */
+public class GcmBroadcastReceiver extends BroadcastReceiver {
+    static final String TAG = "GCMDemo";
+    public static final int NOTIFICATION_ID = 1;
+    private NotificationManager mNotificationManager;
+    NotificationCompat.Builder builder;
+    Context ctx;
+    &#64;Override
+    public void onReceive(Context context, Intent intent) {
+        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
+        ctx = context;
+        String messageType = gcm.getMessageType(intent);
+        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
+            sendNotification("Send error: " + intent.getExtras().toString());
+        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
+            sendNotification("Deleted messages on server: " +
+                    intent.getExtras().toString());
+        } else {
+            sendNotification("Received: " + intent.getExtras().toString());
+        }
+        setResultCode(Activity.RESULT_OK);
+    }
+
+    // Put the GCM message into a notification and post it.
+    private void sendNotification(String msg) {
+        mNotificationManager = (NotificationManager)
+                ctx.getSystemService(Context.NOTIFICATION_SERVICE);
+
+        PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,
+                new Intent(ctx, DemoActivity.class), 0);
+
+        NotificationCompat.Builder mBuilder =
+                new NotificationCompat.Builder(ctx)
+        .setSmallIcon(R.drawable.ic_stat_gcm)
+        .setContentTitle("GCM Notification")
+        .setStyle(new NotificationCompat.BigTextStyle()
+        .bigText(msg))
+        .setContentText(msg);
+
+        mBuilder.setContentIntent(contentIntent);
+        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
+    }
+}</pre>
+
+<h2 id="server">Writing the Server Code</h2>
+
+<p>Here is an example of a CCS server written in Python. You can use this in conjunction with the sample client code shown above. This sample echo server sends an initial message, and for every upstream message received, it sends a dummy response back to the application that sent the upstream message. This example illustrates how to connect,
+send, and receive GCM messages using XMPP. It shouldn't be used as-is
+on a production deployment. For examples of HTTP-based servers, see <a href="server.html">GCM Server</a>.</p>
+
+<pre>
+#!/usr/bin/python
+import sys, json, xmpp, random, string
+
+SERVER = 'gcm.googleapis.com'
+PORT = 5235
+USERNAME = ''
+PASSWORD = ''
+REGISTRATION_ID = ''
+
+unacked_messages_quota = 1000
+send_queue = []
+
+# Return a random alphanumerical id
+def random_id():
+  rid = ''
+  for x in range(8): rid += random.choice(string.ascii_letters + string.digits)
+  return rid
+
+def message_callback(session, message):
+  global unacked_messages_quota
+  gcm = message.getTags('gcm')
+  if gcm:
+    gcm_json = gcm[0].getData()
+    msg = json.loads(gcm_json)
+    if not msg.has_key('message_type'):
+      # Acknowledge the incoming message immediately.
+      send({'to': msg['from'],
+            'message_type': 'ack',
+            'message_id': msg['message_id']})
+      # Queue a response back to the server.
+      if msg.has_key('from'):
+        # Send a dummy echo response back to the app that sent the upstream message.
+        send_queue.append({'to': msg['from'],
+                           'message_id': random_id(),
+                           'data': {'pong': 1}})
+    elif msg['message_type'] == 'ack' or msg['message_type'] == 'nack':
+      unacked_messages_quota += 1
+
+def send(json_dict):
+  template = (&quot;&lt;message&gt;&lt;gcm xmlns='google:mobile:data'&gt;{1}&lt;/gcm&gt;&lt;/message&gt;&quot;)
+  client.send(xmpp.protocol.Message(
+      node=template.format(client.Bind.bound[0], json.dumps(json_dict))))
+
+def flush_queued_messages():
+  global unacked_messages_quota
+  while len(send_queue) and unacked_messages_quota &gt; 0:
+    send(send_queue.pop(0))
+    unacked_messages_quota -= 1
+
+client = xmpp.Client('gcm.googleapis.com', debug=['socket'])
+client.connect(server=(SERVER,PORT), secure=1, use_srv=False)
+auth = client.auth(USERNAME, PASSWORD)
+if not auth:
+  print 'Authentication failed!'
+  sys.exit(1)
+
+client.RegisterHandler('message', message_callback)
+
+send_queue.append({'to': REGISTRATION_ID,
+                   'message_id': 'reg_id',
+                   'data': {'message_destination': 'RegId',
+                            'message_id': random_id()}})
+
+while True:
+  client.Process(1)
+  flush_queued_messages()</pre>
+
 
 
diff --git a/docs/html/google/gcm/http.jd b/docs/html/google/gcm/http.jd
deleted file mode 100644
index b8d8659..0000000
--- a/docs/html/google/gcm/http.jd
+++ /dev/null
@@ -1,618 +0,0 @@
-page.title=GCM HTTP Connection Server
-@jd:body
-
-<div id="qv-wrapper">
-<div id="qv">
-
-
-<h2>In this document</h2>
-
-<ol class="toc">
-  <li><a href="#auth">Authentication</a> </li>
-  <li><a href="#request">Request Format</a> </li>
-  <li><a href="#response">Response Format</a>
-  <ol class="toc">
-    <li><a href="#success">Interpreting a success response</a>
-    <li><a href="#error_codes">Interpreting an error response</a>
-    <li><a href="#example-responses">Example responses</a>
-  </ol>
-  </li>
-  <li><a href="#app-server">Implementing an HTTP-Based App Server</a>
-</ol>
-
-<h2>See Also</h2>
-
-<ol class="toc">
-<li><a href="gs.html">Getting Started</a></li>
-<li><a href="client.html">Implementing GCM Client</a></li>
-<li><a href="ccs.html">Cloud Connection Server</a></li>
-
-
-</ol>
-
-</div>
-</div>
-
-<p>This document describes the GCM HTTP connection server. Connection servers
-are the Google-provided servers that take messages from the 3rd-party
-application server and sending them to the device.</p>
-
-
-
-<p class="note"><strong>Note:</strong> See
-<a href="server.html#params">Implementing GCM Server</a> for a list of all the message
-parameters and which connection server(s) supports them.</p>
-
-
-<h2 id="auth">Authentication</h2>
-
-<p>To send a  message, the application server issues a POST request to
-<code>https://android.googleapis.com/gcm/send</code>.</p>
-<p>A  message request is made of 2 parts: HTTP header and HTTP body.</p>
-
-<p>The HTTP header must contain the following headers:</p>
-<ul>
-  <li><code>Authorization</code>: key=YOUR_API_KEY</li>
-  <li><code>Content-Type</code>: <code>application/json</code> for JSON; <code>application/x-www-form-urlencoded;charset=UTF-8</code> for plain text.
-  </li>
-</ul>
-
-<p>For example:
-</p>
-<pre>Content-Type:application/json
-Authorization:key=AIzaSyB-1uEai2WiUapxCs2Q0GZYzPu7Udno5aA
-
-{
-  "registration_ids" : ["APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx..."],
-  "data" : {
-    ...
-  },
-}</pre>
-<p class="note">
-  <p><strong>Note:</strong> If <code>Content-Type</code> is omitted, the format
-is assumed to be plain text.</p>
-</p>
-
-<p>The HTTP body content depends on whether you're using JSON or plain text.
-See
-<a href="server.html#params">Implementing GCM Server</a> for a list of all the
-parameters your JSON or plain text message can contain.</p>
-
-
-  <h2 id="request">Request Format</h2>
-  <p>Here is the smallest possible request (a message without any parameters and
-just one recipient) using JSON:</p>
-  <pre class="prettyprint pretty-json">{ &quot;registration_ids&quot;: [ &quot;42&quot; ] }</pre>
-
-  <p>And here the same example using plain text:</p>
-  <pre class="prettyprint">registration_id=42</pre>
-
-  <p> Here is a message with a payload and 6 recipients:</p>
-  <pre class="prettyprint pretty-HTML">{ "data": {
-    "score": "5x1",
-    "time": "15:10"
-  },
-  "registration_ids": ["4", "8", "15", "16", "23", "42"]
-}</pre>
-  <p>Here is a message with all optional fields set and 6 recipients:</p>
-  <pre class="prettyprint pretty-json">{ "collapse_key": "score_update",
-  "time_to_live": 108,
-  "delay_while_idle": true,
-  "data": {
-    "score": "4x8",
-    "time": "15:16.2342"
-  },
-  "registration_ids":["4", "8", "15", "16", "23", "42"]
-}</pre>
-  <p>And here is the same message using plain-text format (but just 1 recipient):  </p>
-
-  <pre class="prettyprint">collapse_key=score_update&amp;time_to_live=108&amp;delay_while_idle=1&amp;data.score=4x8&amp;data.time=15:16.2342&amp;registration_id=42
-  </pre>
-
-<p class="note"><strong>Note:</strong> If your organization has a firewall
-that restricts the traffic to or
-from the Internet, you need to configure it to allow connectivity with GCM in order for
-your Android devices to receive messages.
-The ports to open are: 5228, 5229, and 5230. GCM typically only uses 5228, but
-it sometimes uses 5229 and 5230. GCM doesn't provide specific IPs, so you should allow
-your firewall to accept outgoing connections to all IP addresses
-contained in the IP blocks listed in Google's ASN of 15169.</p>
-
-
-
-<h2 id="response">Response format</h2>
-
-<p>There are two possible outcomes when trying to send a message:</p>
-<ul>
-  <li>The message is processed successfully.</li>
-  <li>The GCM server rejects the request.</li>
-</ul>
-
-<p>When the message is processed successfully, the HTTP response has a 200 status
-and the body contains more information about the status of the message
-(including possible errors). When the request is rejected,
-the HTTP response contains a non-200 status code (such as 400, 401, or 503).</p>
-
-<p>The following table summarizes the statuses that the HTTP response header might
-contain. Click the troubleshoot link for advice on how to deal with each type of
-error.</p>
-<table border=1>
-  <tr>
-    <th>Response</th>
-    <th>Description</th>
-  </tr>
-  <tr>
-    <td>200</td>
-    <td>Message was processed successfully. The response body will contain more
-details about the message status, but its format will depend whether the request
-was JSON or plain text. See <a href="#success">Interpreting a success response</a>
-for more details.</td>
-  </tr>
-  <tr>
-    <td>400</td>
-    <td><span id="internal-source-marker_0.2">Only applies for JSON requests.
-Indicates that the request could not be parsed as JSON, or it contained invalid
-fields (for instance, passing a string where a number was expected). The exact
-failure reason is described in the response and the problem should be addressed
-before the request can be retried.</td>
-  </tr>
-  <tr>
-    <td>401</td>
-    <td>There was an error authenticating the sender account.
-<a href="#auth_error">Troubleshoot</a></td>
-  </tr>
-  <tr>
-    <td>5xx</td>
-    <td>Errors in the 500-599 range (such as 500 or 503) indicate that there wa
-an internal error in the GCM server while trying to process the request, or that
-the server is temporarily unavailable (for example, because of timeouts). Sender
-must retry later, honoring any <code>Retry-After</code> header included in the
-response. Application servers must implement exponential back-off.
-<a href="#internal_error">Troubleshoot</a></td>
-  </tr>
-</table>
-
-<h3 id="success">Interpreting a success response</h3>
-<p>When a JSON request is successful (HTTP status code 200), the response body
-contains a JSON object with the following fields:</p>
-<table>
-  <tr>
-    <th>Field</th>
-    <th>Description</th>
-  </tr>
-  <tr>
-    <td><code>multicast_id</code></td>
-    <td>Unique ID (number) identifying the multicast message.</td>
-  </tr>
-  <tr>
-    <td><code>success</code></td>
-    <td>Number of messages that were processed without an error.</td>
-  </tr>
-  <tr>
-    <td><code>failure</code></td>
-    <td>Number of messages that could not be processed.</td>
-  </tr>
-  <tr>
-    <td><code>canonical_ids</code></td>
-    <td>Number of results that contain a canonical registration ID. See
-<a href="adv.html#canonical">Advanced Topics</a> for more discussion of this topic.</td>
-  </tr>
-  <tr>
-    <td><code>results</code></td>
-    <td>Array of objects representing the status of the messages processed. The
-objects are listed in the same order as the request (i.e., for each registration
-ID in the request, its result is listed in the same index in the response) and
-they can have these fields:<br>
-      <ul>
-        <li><code>message_id</code>: String representing the message when it was
-successfully processed.</li>
-        <li><code>registration_id</code>: If set,  means that GCM processed the
-message but it has another canonical registration ID for that device, so sender
-should replace the IDs on future requests (otherwise they might be rejected).
-This field is never set if there is an error in the request.
-        </li>
-        <li><code>error</code>: String describing an error that occurred while
-processing the message for that recipient. The possible values are the same as
-documented in the above table, plus &quot;Unavailable&quot;  (meaning GCM servers
-were busy and could not process the message for that  particular recipient, so
-it could be retried).</li>
-    </ul></td>
-  </tr>
-</table>
-<p>If the value of <code>failure</code> and <code>canonical_ids</code> is 0, it's
-not necessary to parse the remainder of the response. Otherwise, we recommend
-that you iterate through the results field and do the following for each object
-in that list:</p>
-<ul>
-  <li>If <code>message_id</code> is set, check for <code>registration_id</code>:
-    <ul>
-      <li>If <code>registration_id</code> is set, replace the original ID with
-the new value (canonical ID) in your server database. Note that the original ID
-is not part of the result, so you need to obtain it from the list of
-code>registration_ids</code> passed in the request (using the same index).</li>
-    </ul>
-  </li>
-  <li>Otherwise, get the value of <code>error</code>:
-    <ul>
-      <li>If it is <code>Unavailable</code>, you could retry to send it in another
-request.</li>
-      <li>If it is <code>NotRegistered</code>, you should remove the registration
-ID from your server database because the application was uninstalled from the
-device or it does not have a broadcast receiver configured to receive
-<code>com.google.android.c2dm.intent.RECEIVE</code> intents.</li>
-      <li>Otherwise, there is something wrong in the registration ID passed in
-the request; it is probably a non-recoverable error that will also require removing
-the registration from the server database. See <a href="#error_codes">Interpreting
-an error response</a> for all possible error values.</li>
-    </ul>
-  </li>
-</ul>
-
-<p>When a plain-text request is successful (HTTP status code 200), the response
-body contains 1 or 2 lines in the form of key/value pairs.
-The first line is always available and its content is either <code>id=<em>ID of
-sent message</em></code> or <code>Error=<em>GCM error code</em></code>. The second
-line, if available,
-has the format of <code>registration_id=<em>canonical ID</em></code>. The second
-line is optional, and it can only be sent if the first line is not an error. We
-recommend handling the plain-text response in a similar way as handling the
-JSON response:</p>
-<ul>
-  <li>If first line starts with <code>id</code>, check second line:
-    <ul>
-      <li>If second line starts with <code>registration_id</code>, gets its value
-and replace the registration IDs in your server database.</li>
-    </ul>
-  </li>
-  <li>Otherwise, get the value of <code>Error</code>:
-    <ul>
-      <li>If it is <code>NotRegistered</code>, remove the registration ID from
-your server database.</li>
-      <li>Otherwise, there is probably a non-recoverable error (<strong>Note:
-</strong>Plain-text requests will never return <code>Unavailable</code> as the
-error code, they would have returned a 500 HTTP status instead).</li>
-    </ul>
-  </li>
-</ul>
-
-<h3 id="error_codes">Interpreting an error response</h3>
-<p>Here are the recommendations for handling the different types of error that
-might occur when trying to send a message to a device:</p>
-
-<dl>
-<dt id="missing_reg"><strong>Missing Registration ID</strong></dt>
-<dd>Check that the request contains a registration ID (either in the
-<code>registration_id</code> parameter in a plain text message, or in the
-<code>registration_ids</code> field in JSON).
-<br/>Happens when error code is <code>MissingRegistration</code>.</dd>
-
-<dt id="invalid_reg"><strong>Invalid Registration ID</strong></dt>
-<dd>Check the formatting of the registration ID that you pass to the server. Make
-sure it matches the registration ID the phone receives in the
-<code>com.google.android.c2dm.intent.REGISTRATION</code> intent and that you're
-not truncating it or adding additional characters.
-<br/>Happens when error code is <code>InvalidRegistration</code>.</dd>
-
-<dt id="mismatched_sender"><strong>Mismatched Sender</strong></dt>
-<dd>A registration ID is tied to a certain group of senders. When an application
-registers for GCM usage, it must specify which senders are allowed to send messages.
-Make sure you're using one of those when trying to send messages to the device.
-If you switch to a different sender, the existing registration IDs won't work.
-Happens when error code is <code>MismatchSenderId</code>.</dd>
-
-<dt id="unreg_device"><strong>Unregistered Device</strong></dt>
-<dd>An existing registration ID may cease to be valid in a number of scenarios, including:
-<ul>
-  <li>If the application manually unregisters by issuing a
-<span class="prettyprint pretty-java">
-<code>com.google.android.c2dm.intent.UNREGISTER</code></span><code>
-</code>intent.</li>
-  <li>If the application is automatically unregistered, which can happen
-(but is not guaranteed) if the user uninstalls the application.</li>
-  <li>If the registration ID expires. Google might decide to refresh registration
-IDs. </li>
-  <li>If the application is updated but the new version does not have a broadcast
-receiver configured to receive <code>com.google.android.c2dm.intent.RECEIVE</code>
-intents.</li>
-</ul>
-For all these cases, you should remove this registration ID from the 3rd-party
-server and stop using it to send
-messages.
-<br/>Happens when error code is <code>NotRegistered</code>.</dd>
-
-<dt id="big_msg"><strong>Message Too Big</strong></dt>
-  <dd>The total size of the payload data that is included in a message can't
-exceed 4096 bytes. Note that this includes both the size of the keys as well
-as the values.
-<br/>Happens when error code is <code>MessageTooBig</code>.</dd>
-
-<dt id="invalid_datakey"><strong>Invalid Data Key</strong></dt>
-<dd>The payload data contains a key (such as <code>from</code> or any value
-prefixed by <code>google.</code>) that is used internally by GCM in the
-<code>com.google.android.c2dm.intent.RECEIVE</code> Intent and cannot be used.
-Note that some words (such as <code>collapse_key</code>) are also used by GCM
-but are allowed in the payload, in which case the payload value will be
-overridden by the GCM value.
-<br />
-Happens when the error code is <code>InvalidDataKey</code>.</dd>
-
-<dt id="ttl_error"><strong>Invalid Time To Live</strong></dt>
-  <dd>The value for the Time to Live field must be an integer representing
-a duration in seconds between 0 and 2,419,200 (4 weeks). Happens when error code
-is <code>InvalidTtl</code>.
-</dd>
-
-  <dt id="auth_error"><strong>Authentication Error</strong></dt>
-  <dd>The sender account that you're trying to use to send a message couldn't be
-authenticated. Possible causes are: <ul>
-<li>Authorization header missing or with invalid syntax.</li>
-<li>Invalid project number sent as key.</li>
-<li>Key valid but with GCM service disabled.</li>
-<li>Request originated from a server not whitelisted in the Server Key IPs.</li>
-
-</ul>
-Check that the token you're sending inside the <code>Authorization</code> header
-is the correct API key associated with your project. You can check the validity
-of your API key by running the following command:<br/>
-
-<pre># api_key=YOUR_API_KEY
-
-# curl --header "Authorization: key=$api_key" --header Content-Type:"application/json" https://android.googleapis.com/gcm/send  -d "{\"registration_ids\":[\"ABC\"]}"</pre>
-
-
-
-If you receive a 401 HTTP status code, your API key is not valid. Otherwise you
-should see something like this:<br/>
-
-<pre>
-{"multicast_id":6782339717028231855,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
-</pre>
-If you want to confirm the validity of a registration ID, you can do so by
-replacing "ABC" with the registration ID.
-<br/>
-Happens when the HTTP status code is 401.
-
-  <dt id="timeout"><strong>Timeout</strong></dt>
-
-<dd>The server couldn't process the request in time. You should retry the
-same request, but you MUST obey the following requirements:
-
-<ul>
-
-<li>Honor the <code>Retry-After</code> header if it's included in the response
-from the GCM server.</li>
-
-
-<li>Implement exponential back-off in your retry mechanism. This means an
-exponentially increasing delay after each failed retry (e.g. if you waited one
-second before the first retry, wait at least two second before the next one,
-then 4 seconds and so on). If you're sending multiple messages, delay each one
-independently by an additional random amount to avoid issuing a new request for
-all messages at the same time.</li>
-
-
-Senders that cause problems risk being blacklisted.
-<br />
-Happens when the HTTP status code is between 501 and 599, or when the
-<code>error</code> field of a JSON object in the results array is <code>Unavailable</code>.
-</dd>
-
-<dt id="internal_error"><strong>Internal Server Error</strong></dt>
-
-<dd>
-The server encountered an error while trying to process the request. You
-could retry the same request (obeying the requirements listed in the <a href="#timeout">Timeout</a>
-section), but if the error persists, please report the problem in the
-<a href="https://groups.google.com/forum/?fromgroups#!forum/android-gcm">android-gcm group</a>.
-<br />
-Happens when the HTTP status code is 500, or when the <code>error</code> field of a JSON
-object in the results array is <code>InternalServerError</code>.
-</dd>
-
-<dt id="restricted_package_name"><strong>Invalid Package Name</strong></dt>
-
-<dd>
-A message was addressed to a registration ID whose package name did not match
-the value passed in the request. Happens when error code is
-<code>InvalidPackageName</code>.
-</dd>
-</dl>
-
-<h3 id="example-responses">Example responses</h3>
-<p>This section shows a few examples of responses indicating messages that were
-processed successfully. See <a href="#request">Request Format</a> for
-the requests these responses are based on.</p>
-<p> Here is a simple case of a JSON message successfully sent to one recipient
-without canonical IDs in the response:</p>
-<pre class="prettyprint pretty-json">{ "multicast_id": 108,
-  "success": 1,
-  "failure": 0,
-  "canonical_ids": 0,
-  "results": [
-    { "message_id": "1:08" }
-  ]
-}</pre>
-
-<p>Or if the request was in plain-text format:</p>
-<pre class="prettyprint">id=1:08
-</pre>
-
-<p>Here are JSON results for 6 recipients (IDs 4, 8, 15, 16, 23, and 42 respectively)
-with 3 messages successfully processed, 1 canonical registration ID returned,
-and 3 errors:</p>
-<pre class="prettyprint pretty-json">{ "multicast_id": 216,
-  "success": 3,
-  "failure": 3,
-  "canonical_ids": 1,
-  "results": [
-    { "message_id": "1:0408" },
-    { "error": "Unavailable" },
-    { "error": "InvalidRegistration" },
-    { "message_id": "1:1516" },
-    { "message_id": "1:2342", "registration_id": "32" },
-    { "error": "NotRegistered"}
-  ]
-}
-</pre>
-<p> In this example:</p>
-<ul>
-  <li>First message: success, not required.</li>
-  <li>Second message: should be resent (to registration ID 8).</li>
-  <li>Third message: had an unrecoverable error (maybe the value got corrupted
-in the database).</li>
-  <li>Fourth message: success, nothing required.</li>
-  <li>Fifth message: success, but the registration ID should be updated in the
-server database (from 23 to 32).</li>
-  <li>Sixth message: registration ID (42) should be removed from the server database
-because the application was uninstalled from the device.</li>
-</ul>
-<p>Or if just the 4th message above was sent using plain-text format:</p>
-<pre class="prettyprint">Error=InvalidRegistration
-</pre>
-<p>If the 5th message above was also sent using plain-text format:</p>
-<pre class="prettyprint">id=1:2342
-registration_id=32
-</pre>
-
-
-<h2 id="app-server">Implementing an HTTP-Based App Server</h2>
-
-<p>This section gives examples of implementing an app server that works with the
-GCM HTTP connection server. Note that a full GCM implementation requires a
-client-side implementation, in addition to the server.</a>
-
-
-<p>Requirements</p>
-<p>For the web server:</p>
-<ul>
-  <li> <a href="http://ant.apache.org/">Ant 1.8</a> (it might work with earlier versions, but it's not guaranteed).</li>
-  <li>One of the following:
-    <ul>
-      <li>A running web server compatible with Servlets API version 2.5, such as
-<a href="http://tomcat.apache.org/">Tomcat 6</a> or <a href="http://jetty.codehaus.org/">Jetty</a>, or</li>
-      <li><a href="http://code.google.com/appengine/">Java App Engine SDK</a>
-version 1.6 or later.</li>
-    </ul>
-  </li>
-  <li>A Google account registered to use GCM.</li>
-  <li>The API  key for that account.</li>
-</ul>
-<p>For the Android application:</p>
-<ul>
-  <li>Emulator (or device) running Android 2.2 with Google APIs.</li>
-  <li>The Google API project number of the account registered to use GCM.</li>
-</ul>
-
-<h3 id="gcm-setup">Setting Up GCM</h3>
-<p>Before proceeding with the server and client setup, it's necessary to register
-a Google account with the Google API Console, enable Google Cloud Messaging in GCM,
-and obtain an API key from the <a href="https://code.google.com/apis/console">
-Google API Console</a>.</p>
-<p>For instructions on how to set up GCM, see <a href="gs.html">Getting Started</a>.</p>
-
-
-<h3 id="server-setup">Setting Up an HTTP Server</h3>
-<p>This section describes the different options for setting up an HTTP server.</p>
-
-<h4 id="webserver-setup">Using a standard web server</h4>
-<p>To set up the server using a standard, servlet-compliant web server:</p>
-<ol>
-  <li>From the <a href="http://code.google.com/p/gcm">open source site</a>,
-download the following directories: <code>gcm-server</code>,
-<code>samples/gcm-demo-server</code>, and <code>samples/gcm-demo-appengine</code>.</p>
-
-
-  <li>In a text editor, edit the <code>samples/gcm-demo-server/WebContent/WEB-INF/classes/api.key</code> and replace the existing text with the API key obtained above.</li>
-  <li>In a shell window, go to the <code>samples/gcm-demo-server</code> directory.</li>
-  <li>Generate the server's WAR file by running <code>ant war</code>:</li>
-
-  <pre class="prettyprint">$ ant war
-
-Buildfile:build.xml
-
-init:
-   [mkdir] Created dir: build/classes
-   [mkdir] Created dir: dist
-
-compile:
-   [javac] Compiling 6 source files to build/classes
-
-war:
-     [war] Building war: <strong>dist/gcm-demo.war</strong>
-
-BUILD SUCCESSFUL
-Total time: 0 seconds
-</pre>
-
-  <li>Deploy the <code>dist/gcm-demo.war</code> to your running server. For instance, if you're using Jetty, copy <code>gcm-demo.war</code> to the <code>webapps</code> directory of the Jetty installation.</li>
-  <li>Open the server's main page in a browser. The URL depends on the server you're using and your machine's IP address, but it will be something like <code>http://192.168.1.10:8080/gcm-demo/home</code>, where <code>gcm-demo</code> is the application context and <code>/home</code> is the path of the main servlet.
-
-  </li>
-</ol>
-<p class="note"><strong>Note:</strong> You can get the IP by running <code>ifconfig</code> on Linux or MacOS, or <code>ipconfig</code> on Windows. </p>
-
-<p> You server is now ready.</p>
-
-<h4 id="appengine-setup">Using App Engine for Java</h4>
-
-<p>To set up the server using a standard App Engine for Java:</p>
-<ol>
-  <li>Get the files from the <a href="http://code.google.com/p/gcm">open source
-site</a>, as described above.</p>
-  </li>
-  <li>In a text editor, edit
-<code>samples/gcm-demo-appengine/src/com/google/android/gcm/demo/server/ApiKeyInitializer.java</code>
-and replace the existing text with the API key obtained above.
-
-  <p class="note"><strong>Note:</strong> The API key value set in that class will
-be used just once to create a persistent entity on App Engine. If you deploy
-the application, you can use App Engine's <code>Datastore Viewer</code> to change
-it later.</p>
-
-  </li>
-  <li>In a shell window, go to the <code>samples/gcm-demo-appengine</code> directory.</li>
-  <li>Start the development App Engine server by <code>ant runserver</code>,
-using the <code>-Dsdk.dir</code> to indicate the location of the App Engine SDK
-and <code>-Dserver.host</code> to set your server's hostname or IP address:</li>
-
-<pre class="prettyprint">
-$ ant -Dsdk.dir=/opt/google/appengine-java-sdk runserver -Dserver.host=192.168.1.10
-Buildfile: gcm-demo-appengine/build.xml
-
-init:
-    [mkdir] Created dir: gcm-demo-appengine/dist
-
-copyjars:
-
-compile:
-
-datanucleusenhance:
-  [enhance] DataNucleus Enhancer (version 1.1.4) : Enhancement of classes
-  [enhance] DataNucleus Enhancer completed with success for 0 classes. Timings : input=28 ms, enhance=0 ms, total=28 ms. Consult the log for full details
-  [enhance] DataNucleus Enhancer completed and no classes were enhanced. Consult the log for full details
-
-runserver:
-     [java] Jun 15, 2012 8:46:06 PM com.google.apphosting.utils.jetty.JettyLogger info
-     [java] INFO: Logging to JettyLogger(null) via com.google.apphosting.utils.jetty.JettyLogger
-     [java] Jun 15, 2012 8:46:06 PM com.google.apphosting.utils.config.AppEngineWebXmlReader readAppEngineWebXml
-     [java] INFO: Successfully processed gcm-demo-appengine/WebContent/WEB-INF/appengine-web.xml
-     [java] Jun 15, 2012 8:46:06 PM com.google.apphosting.utils.config.AbstractConfigXmlReader readConfigXml
-     [java] INFO: Successfully processed gcm-demo-appengine/WebContent/WEB-INF/web.xml
-     [java] Jun 15, 2012 8:46:09 PM com.google.android.gcm.demo.server.ApiKeyInitializer contextInitialized
-     [java] SEVERE: Created fake key. Please go to App Engine admin console, change its value to your API Key (the entity type is 'Settings' and its field to be changed is 'ApiKey'), then restart the server!
-     [java] Jun 15, 2012 8:46:09 PM com.google.appengine.tools.development.DevAppServerImpl start
-     [java] INFO: The server is running at http://192.168.1.10:8080/
-     [java] Jun 15, 2012 8:46:09 PM com.google.appengine.tools.development.DevAppServerImpl start
-     [java] INFO: The admin console is running at http://192.168.1.10:8080/_ah/admin
-</pre>
-
-  <li>Open the server's main page in a browser. The URL depends on the server
-you're using and your machine's IP address, but it will be something like
-<code>http://192.168.1.10:8080/home</code>, where <code>/home</code>
-is the path of the main servlet.</li>
-
-  <p class="note"><strong>Note:</strong> You can get the IP by running <code>ifconfig</code>
-on Linux or MacOS, or <code>ipconfig</code> on Windows.</p>
-
-</ol>
-<p> You server is now ready.</p>
diff --git a/docs/html/google/gcm/notifications.jd b/docs/html/google/gcm/notifications.jd
index 43a7368..5171850 100644
--- a/docs/html/google/gcm/notifications.jd
+++ b/docs/html/google/gcm/notifications.jd
@@ -14,15 +14,14 @@
 <h2>In this document</h2>
 
 <ol class="toc">
-  <li><a href="#request">Request Format</a></li>
-  <li><a href="#create">Generate a Notification Key</a></li>
-  <li><a href="#add">Add Registration IDs</a></li>
-  <li><a href="#remove">Remove Registration IDs</a></li>
-  <li><a href="#upstream">Send Upstream Messages</a></li>
-  <li><a href="#response">Response Formats</a>
-    <ol class="toc">
-      <li><a href="#response-create">Create/add/remove operations</a>
-      <li><a href="#response-send">Send operations</a>
+  <li><a href="#what">What are User Notifications?</a> </li>
+  <li><a href="#examples">Examples</a>
+    <ol>
+      <li><a href="#create">Generate a notification key</a></li>
+      <li><a href="#add">Add registration IDs</a></li>
+      <li><a href="#remove">Remove registration IDs</a></li>
+      <li><a href="#upstream">Send upstream messages</a></li>
+      <li><a href="#response">Response formats</a></li>
     </ol>
   </li>
 </ol>
@@ -39,51 +38,32 @@
 
 <p class="note"><strong>Note:</strong> To try out this feature, sign up using <a href="https://services.google.com/fb/forms/gcm/">this form</a>.</p>
 
+<p>The upstream messaging (device-to-cloud) feature described in this document is part of the Google Play services platform. Upstream messaging is available through the <a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">GoogleCloudMessaging</a> APIs. To use upstream messaging and the new streamlined registration process, you must <a href="{@docRoot}google/play-services/setup.html">set up</a> the Google Play services SDK.</p>
 
-<p>With user notifications, 3rd-party app servers can send a single message to
-multiple instance of an app running on devices owned by a single user. This feature
-is called <em>user notifications</em>. User notifications make it possible for every
-app instance that a user owns to reflect the latest messaging state. For example:</p>
+<h2 id="what">What are User Notifications?</h2>
+
+<p>Third party servers can send a single message to multiple instance of an app running on devices owned by a single user. This feature is called <em>user notifications</em>. User notifications make it possible for every app instance that a user owns to reflect the latest messaging state. For example:</p>
 
   <ul>
-  <li>If a message has been handled on one device, the GCM message on the other
-devices are dismissed. For example, if a user has handled a calendar notification
-on one device, the notification will go away on the user's other devices.</li>
-
-  <li>If a message has not been delivered yet to a device and but it has been handled,
-the GCM server removes it from the unsent queue for the other devices.</li>
-
-  <li>Likewise, a device can send messages to the {@code notification_key}, which
-is the token that GCM uses to fan out notifications to all devices whose
-registration IDs are associated with the key.</li>
+  <li>If a message has been handled on one device, the GCM message on the other devices are dismissed. For example, if a user has handled a calendar notification on one device, the notification will go away on the user's other devices.</li>
+  <li>If a message has not been delivered yet to a device and but it has been handled, the GCM server removes it from the unsent queue for the other devices.</li>
+  <li>Likewise, a device can send messages to the {@code notification_key}, which is the token that GCM uses to fan out notifications to all devices whose registration IDs are associated with the key.</li>
 </ul>
 
-<p>The way this works is that during registration, the 3rd-party server requests
-a {@code notification_key}. The {@code notification_key} maps a particular user
-to all of the user's associated registration IDs (a regID represents a particular
-Android application running on a particular device). Then instead of sending one
-message to one regID at a time, the 3rd-party server can send a message to to the
-{@code notification_key}, which then sends the message to all of the user's regIDs.</p>
+<p>The way this works is that during registration, the 3rd-party server requests a {@code notification_key}. The {@code notification_key} maps a particular user to all of the user's associated registration IDs (a regID represents a particular Android application running on a particular device). Then instead of sending one message to one regID at a time, the 3rd-party server can send a message to to the {@code notification_key}, which then sends the message to all of the user's regIDs.</p>
 
-<p class="note"><strong>Note:</strong> A notification dismissal message is like any
-other upstream message, meaning that it will be delivered to the other devices that
-belong to the specified {@code notification_key}. You should design your app to
-handle cases where the app receives a dismissal message, but has not yet displayed
-the notification that is being dismissed. You can solve this by caching the dismissal
-and then reconciling it with the corresponding notification.
+<p class="note"><strong>Note:</strong> A notification dismissal message is like any other upstream message, meaning that it will be delivered to the other devices that belong to the specified {@code notification_key}. You should design your app to handle cases where the app receives a dismissal message, but has not yet displayed the notification that is being dismissed. You can solve this by caching the dismissal and then reconciling it with the corresponding notification.
 </p>
 
-<p>You can use this feature with either the <a href="ccs.html">XMPP</a> (CCS) or
-<a href="http.html">HTTP</a> connection server.</p>
+<p>You can use this feature with either the new <a href="ccs.html">GCM Cloud Connection Server</a> (CCS), or the older <a href="gcm.html">GCM HTTP server</a>.</p>
 
 
-<p>The examples below show you how to perform generate/add/remove operations,
-and how to send upstream messages. For generate/add/remove operations, the
-message body is JSON.</p>
+<h3 id="examples">Examples</h3>
 
-<h2 id="request">Request Format</h2>
-<p>To send a  message, the application server issues a POST request to
-<code>https://android.googleapis.com/gcm/notification</code>.</p>
+<p>The examples in this section show you how to perform generate/add/remove operations, and how to send upstream messages. For generate/add/remove operations, the message body is JSON.</p>
+
+<h4 id="request">Request format</h4>
+<p>To send a  message, the application server issues a POST request to <code>https://android.googleapis.com/gcm/notification</code>.</p>
 
 <p>Here is the HTTP request header you should use for all create/add/remove operations:</p>
 
@@ -92,22 +72,12 @@
 Header: "Authorization", "key=API_KEY"
 </pre>
 
-<h2 id="create">Generate a Notification Key</h2>
+<h4 id="create">Generate a notification key</h4>
 
-<p>This example shows how to create a new <code>notification_key</code> for a
-<code>notification_key_name</code> called <code>appUser-Chris</code>.
-The {@code notification_key_name} is a name or identifier (can be a username for
-a 3rd-party app) that is unique to a given user. It is used by third parties to
-group together registration IDs for a single user. Note that <code>notification_key_name</code>
-and <code>notification_key</code> are unique to a group of registration IDs. It is also
-important that <code>notification_key_name</code> be uniquely named per app in case
-you have multiple apps for the same project ID. This ensures that notifications
-only go to the intended target app.</p>
+<p>This example shows how to create a new <code>notification_key</code> for a <code>notification_key_name</code> called <code>appUser-Chris</code>. The {@code notification_key_name} is a name or identifier (can be a username for a 3rd-party app) that is unique to a given user. It is used by third parties to group together registration IDs for a single user. Note that <code>notification_key_name</code> and <code>notification_key</code> are unique to a group of registration IDs. It is also important that <code>notification_key_name</code> be uniquely named per app in case you have multiple apps for the same project ID. This ensures that notifications only go to the intended target app.</p>
 
 
-<p>A create operation returns a token (<code>notification_key</code>). Third parties
-must save this token (as well as its mapping to the <code>notification_key_name</code>)
-to use in subsequent operations:</p>
+<p>A create operation returns a token (<code>notification_key</code>). Third parties must save this token (as well as its mapping to the <code>notification_key_name</code>) to use in subsequent operations:</p>
 
 <pre>request:
 { 
@@ -116,14 +86,11 @@
    &quot;registration_ids&quot;: [&quot;4&quot;, &quot;8&quot;, &quot;15&quot;, &quot;16&quot;, &quot;23&quot;, &quot;42&quot;]
 }</pre>
 
-<h2 id="add">Add Registration IDs</h2>
+<h4 id="add">Add registration IDs</h4>
 
-<p>This example shows how to add registration IDs for a given notification key.
-The maximum number of members allowed for a {@code notification_key} is 10.</p>
+<p>This example shows how to add registration IDs for a given notification key. The maximum number of members allowed for a {@code notification_key} is 10.</p>
 
-<p>Note that the <code>notification_key_name</code> is not strictly required for
-adding/removing regIDs. But including it protects you against accidentally using
-the incorrect <code>notification_key</code>.</p>
+<p>Note that the <code>notification_key_name</code> is not strictly required for adding/removing regIDs. But including it protects you against accidentally using the incorrect <code>notification_key</code>.</p>
 
 <pre>request:
 { 
@@ -133,7 +100,7 @@
    &quot;registration_ids&quot;: [&quot;4&quot;, &quot;8&quot;, &quot;15&quot;, &quot;16&quot;, &quot;23&quot;, &quot;42&quot;]
 }</pre>
 
-<h2 id="remove">Remove Registration IDs</h2>
+<h4 id="remove">Remove registration IDs</h4>
 
 <p>This example shows how to remove registration IDs for a given notification key:</p>
 <pre>request:
@@ -144,14 +111,9 @@
    &quot;registration_ids&quot;: [&quot;4&quot;, &quot;8&quot;, &quot;15&quot;, &quot;16&quot;, &quot;23&quot;, &quot;42&quot;]
 }</pre>
 
-<h2 id="upstream">Send Upstream Messages</h2>
+<h4 id="upstream">Send upstream messages</h4>
 
-<p>To send an upstream (device-to-cloud) message, you must use the
-<a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">
-{@code GoogleCloudMessaging}</a> API. Specifying a {@code notification_key} as the target
-for an upstream message allows a user on one device to send a message to other
-devices in the notification group&mdash;for example, to dismiss a notification.
-Here is an example that shows targeting a {@code notification_key}:</p>
+<p>To send an upstream (device-to-cloud) message, you must use the <a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">GoogleCloudMessaging</a> API. Specifying a {@code notification_key} as the target for an upstream message allows a user on one device to send a message to other devices in the notification group&mdash;for example, to dismiss a notification. Here is an example that shows targeting a {@code notification_key}:</p>
 
 <pre>GoogleCloudMessaging gcm = GoogleCloudMessaging.get(context);
 String to = NOTIFICATION_KEY;
@@ -163,21 +125,17 @@
 gcm.send(to, id, data);
 </pre>
 
-<p>This call generates the necessary XMPP stanza for sending the message. The
-Bundle data consists of a key-value pair.</p>
+<p>This call generates the necessary XMPP stanza for sending the message. The Bundle data consists of a key-value pair.</p>
 
-<p>For a complete example, see <a href="client.html">Implementing GCM Client</a>.
+<p>For a complete example, see <a href="gs.html#gs_example">Getting Started</a>. 
 
-<h2 id="response">Response Formats</h2>
+<h4 id="response">Response formats</h4>
 
-<p>This section shows examples of the responses that can be returned for
-notification key operations.</p>
+<p>This section shows examples of the responses that can be returned for notification key operations.</p>
 
-<h3 id="response-create">Create/add/remove operations</h3>
+<h5>Response for create/add/remove operations</h5>
 
-<p>When you make a request to create a {@code notification_key} or to add/remove its
-regIDs, a successful response always returns the <code>notification_key</code>.
-his is the {@code notification_key} you will use for sending messages:</p>
+<p>When you make a request to create a {@code notification_key} or to add/remove its the wayregIDs, a successful response always returns the <code>notification_key</code>. This is the {@code notification_key} you will use for sending messages:</p>
 
 <pre>HTTP status: 200
 { 
@@ -185,23 +143,18 @@
 }</pre>
 
 
-<h3 id="response-send">Send operations</h3>
+<h5>Response for send operations</h5>
 
-<p>For a send operation that has a {@code notification_key} as its target, the
-possible responses are success, partial success, and failure.</p>
+<p>For a send operation that has a {@code notification_key} as its target, the possible responses are success, partial success, and failure.</p>
 
-<p>Here is an example of "success"&mdash;the {@code notification_key} has 2 regIDs
-associated with it, and the message was successfully sent to both of them:</p>
+<p>Here is an example of "success"&mdash;the {@code notification_key} has 2 regIDs associated with it, and the message was successfully sent to both of them:</p>
 
 <pre>{
   "success": 2,
   "failure": 0
 }</pre>
 
-<p>Here is an example of "partial success"&mdash;the {@code notification_key} has
-3 regIDs associated with it. The message was successfully send to 1 of the regIDs,
-but not to the other 2. The response message lists the regIDs that failed to
-receive the message:</p>
+<p>Here is an example of "partial success"&mdash;the {@code notification_key} has 3 regIDs associated with it. The message was successfully send to 1 of the regIDs, but not to the other 2. The response message lists the regIDs that failed to receive the message:</p>
 
 <pre>{
   "success":1,
@@ -212,9 +165,7 @@
   ]
 }</pre>
 
-<p>In the case of failure, the response has HTTP code 503 and no JSON. When a message
-fails to be delivered to one or more of the regIDs associated with a {@code notification_key},
-the 3rd-party server should retry.</p>
+<p>In the case of failure, the response has HTTP code 503 and no JSON. When a message fails to be delivered to one or more of the regIDs associated with a {@code notification_key}, the 3rd-party server should retry.</p>
 
 
 
diff --git a/docs/html/google/gcm/server.jd b/docs/html/google/gcm/server.jd
index b5e6b48..92a1531 100644
--- a/docs/html/google/gcm/server.jd
+++ b/docs/html/google/gcm/server.jd
@@ -1,34 +1,36 @@
-page.title=Implementing GCM Server
+page.title=GCM Server
 @jd:body
 
 <div id="qv-wrapper">
 <div id="qv">
 
+<h2>Quickview</h2>
+
+<ul>
+<li>Understand how to set up the server side of a GCM app.</li>
+<li>Become familiar with the <a href="{@docRoot}reference/com/google/android/gcm/server/package-summary.html">GCM server helper library</a>.</li>
+</ul>
+
+
 <h2>In this document</h2>
 
-<ol class="toc">
-  <li><a href="#choose">Choosing a GCM Connection Server</a></li>
-  <li><a href="#role">Role of the 3rd-party Application Server</a></li>
-    <li><a href="#send-msg">Sending Messages</a>
-    <ol class="toc">
-
-      <li><a href="#target">Target</a></li>
-      <li><a href="#payload">Payload</a></li>
-      <li><a href="#params">Message parameters</a>
+<ol>
+  <li><a href="#requirements">Requirements</a> </li>
+  <li><a href="#gcm-setup">Setting Up GCM</a></li>
+  <li><a href="#server-setup">Setting Up an HTTP Server</a>
+    <ol>
+      <li><a href="#webserver-setup">Using a standard web server</a></li>
+      <li><a href="#appengine-setup">Using App Engine for Java</a></li>
     </ol>
-    </li>
-  <li><a href="#receive">Receiving Messages</a> </li>
   </li>
-
 </ol>
 
 <h2>See Also</h2>
 
 <ol class="toc">
 <li><a href="gs.html">Getting Started</a></li>
-<li><a href="client.html">Implementing GCM Client</a></li>
-<li><a href="ccs.html">Cloud Connection Server (XMPP)</a></li>
-<li><a href="http.html">HTTP Connection Server</a></li>
+<li><a href="client.html">GCM Client</a></li>
+<li><a href="ccs.html">Cloud Connection Server</a></li>
 
 
 </ol>
@@ -37,342 +39,122 @@
 </div>
 
 
-<p>The server side of GCM consists of 2 components:</p>
+
+
+<p>This document gives examples of GCM server-side code for HTTP. For an example of an XMPP server (<a href="ccs.html">Cloud Connection Server</a>), see <a href="gs.html#server">Getting Started</a>. Note that a full GCM implementation requires a client-side implementation, in addition to the server. For a complete working example that includes client and server-side code, see <a href="gs.html">Getting Started</a>.</a>
+
+<h2 id="requirements">Requirements</h2>
+<p>For the web server:</p>
 <ul>
-<li>Google-provided <strong>GCM Connection Servers</strong>
-take messages from a 3rd-party application server and send them to a GCM-enabled
-Android application (the &quot;client app&quot;) running on a device. For example,
-Google provides connection servers for <a href="{@docRoot}google/gcm/http.html">
-HTTP</a> and <a href="{@docRoot}google/gcm/ccs.html">CCS</a> (XMPP).</li>
-<li>A <strong>3rd-party application server</strong> that you must implement. This application
-server sends data to a GCM-enabled Android application via the chosen GCM connection server.</li>
-</ul>
-</p>
-
-<p>Here are the basic steps you follow to implement your 3rd-party app server:</p>
-
-<ul>
-      <li>Decide which GCM connection server(s) you want to use. Note that if you want to use
-      upstream messaging from your client applications, you must use CCS. For a more detailed
-      discussion of this, see <a href="#choose">
-      Choosing a GCM Connection Server</a>.</li>
-      <li>Decide how you want to implement your app server. For example:
-        <ul>
-          <li>If you decide to use the HTTP connection server, you can use the
-GCM server helper library and demo app to help in implementing your app server.</li>
-          <li>If you decide to use the XMPP connection server, you can use
-the provided Python or Java <a href="http://www.igniterealtime.org/projects/smack/">
-Smack</a> demo apps as a starting point.</li>
-        <li>Note that Google AppEngine does not support connections to CCS.</li>
-        </ul>
-      </li>
-    </ul>
-  </li>
-</ul>
-
-<p>A full GCM implementation requires both a client implementation and a server
-implementation. For more
-information about implementing the client side, see <a href="client.html">
-Implementing GCM Client</a>.</p>
-
-<h2 id="choose">Choosing a GCM Connection Server</h2>
-
-<p>Currently GCM provides two connection servers: <a href="{@docRoot}google/gcm/http.html">
-HTTP</a> and <a href="{@docRoot}google/gcm/ccs.html">CCS</a> (XMPP). You can use them
-separately or in tandem. CCS messaging differs from GCM HTTP messaging in the following ways:</p>
-<ul>
-  <li>Upstream/Downstream messages
+  <li> <a href="http://ant.apache.org/">Ant 1.8</a> (it might work with earlier versions, but it's not guaranteed).</li>
+  <li>One of the following:
     <ul>
-      <li>GCM HTTP: Downstream only: cloud-to-device. </li>
-      <li>CCS: Upstream and downstream (device-to-cloud, cloud-to-device). </li>
+      <li>A running web server compatible with Servlets API version 2.5, such as <a href="http://tomcat.apache.org/">Tomcat 6</a> or <a href="http://jetty.codehaus.org/">Jetty</a>, or</li>
+      <li><a href="http://code.google.com/appengine/">Java App Engine SDK</a> version 1.6 or later.</li>
     </ul>
   </li>
-  <li>Asynchronous messaging
-    <ul>
-      <li>GCM HTTP: 3rd-party app servers send messages as HTTP POST requests and
-wait for a response. This mechanism is synchronous and causes the sender to block
-before sending another message.</li>
-      <li>CCS: 3rd-party app servers connect to Google infrastructure using a
-persistent XMPP connection and send/receive messages to/from all their devices
-at full line speed. CCS sends acknowledgment or failure notifications (in the
-form of special ACK and NACK JSON-encoded XMPP messages) asynchronously.</li>
-    </ul>
-  </li>
-
-  <li>JSON
-    <ul>
-      <li>GCM HTTP: JSON messages sent as HTTP POST.</li>
-      <li>CCS: JSON messages encapsulated in XMPP messages.</li>
-    </ul>
-  </li>
+  <li>A Google account registered to use GCM.</li>
+  <li>The API  key for that account.</li>
 </ul>
-
-<h2 id="role">Role of the 3rd-party Application Server</h2>
-
-<p>Before you can write client Android applications that use the GCM feature, you must
-have an  application server that meets the following criteria:</p>
-
+<p>For the Android application:</p>
 <ul>
-  <li>Able to communicate with your client.</li>
-  <li>Able to  fire off properly formatted requests to the GCM server.</li>
-  <li>Able to handle requests and resend them as needed, using
-<a href="http://en.wikipedia.org/wiki/Exponential_backoff">exponential back-off.</a></li>
-  <li>Able to store the API key and client registration IDs. The
-API key is included in the header of POST requests that send
-messages.</li>
- <li>Able to store the API key and client registration IDs.</li>
- <li>Able to generate message IDs to uniquely identify each message it sends.</li>
+  <li>Emulator (or device) running Android 2.2 with Google APIs.</li>
+  <li>The Google API project number of the account registered to use GCM.</li>
 </ul>
+<h2 id="gcm-setup">Setting Up GCM</h2>
+<p>Before proceeding with the server and client setup, it's necessary to register a Google account with the Google API Console, enable Google Cloud Messaging in GCM, and obtain an API key from the <a href="https://code.google.com/apis/console">Google API Console</a>.</p>
+<p>For instructions on how to set up GCM, see <a href="gs.html">Getting Started</a>.</p>
 
-<h2 id="send-msg">Sending Messages</h2>
 
-<p>Here is the general sequence of events that occurs when a 3rd-party application
-server sends a message:</p>
+<h2 id="server-setup">Setting Up an HTTP Server</h2>
+<p>This section describes the different options for setting up an HTTP server.</p>
+<h3 id="webserver-setup">Using a standard web server</h3>
+<p>To set up the server using a standard, servlet-compliant web server:</p>
 <ol>
-  <li>The application server sends a message to GCM servers.</li>
-  <li>Google enqueues and stores the message in case the device is offline.</li>
-  <li>When the device is online, Google sends the message to the device.</li>
-  <li>On the device, the system broadcasts the message to the specified Android
-application via Intent broadcast with proper permissions, so that only the targeted
-ndroid application gets the message. This wakes the Android application up.
-The Android application does not need to be running beforehand to receive the message.</li>
-  <li>The Android application processes the message. </li>
+  <li>From the <a href="http://code.google.com/p/gcm">open source site</a>, download the following directories: <code>gcm-server</code>, <code>samples/gcm-demo-server</code>, and <code>samples/gcm-demo-appengine</code>.</p>
+
+
+  <li>In a text editor, edit the <code>samples/gcm-demo-server/WebContent/WEB-INF/classes/api.key</code> and replace the existing text with the API key obtained above.</li>
+  <li>In a shell window, go to the <code>samples/gcm-demo-server</code> directory.</li>
+  <li>Generate the server's WAR file by running <code>ant war</code>:</li>
+  
+  <pre class="prettyprint">$ ant war
+
+Buildfile:build.xml
+
+init:
+   [mkdir] Created dir: build/classes
+   [mkdir] Created dir: dist
+
+compile:
+   [javac] Compiling 6 source files to build/classes
+
+war:
+     [war] Building war: <strong>dist/gcm-demo.war</strong>
+
+BUILD SUCCESSFUL
+Total time: 0 seconds
+</pre>
+  
+  <li>Deploy the <code>dist/gcm-demo.war</code> to your running server. For instance, if you're using Jetty, copy <code>gcm-demo.war</code> to the <code>webapps</code> directory of the Jetty installation.</li>
+  <li>Open the server's main page in a browser. The URL depends on the server you're using and your machine's IP address, but it will be something like <code>http://192.168.1.10:8080/gcm-demo/home</code>, where <code>gcm-demo</code> is the application context and <code>/home</code> is the path of the main servlet.
+    
+  </li>
 </ol>
+<p class="note"><strong>Note:</strong> You can get the IP by running <code>ifconfig</code> on Linux or MacOS, or <code>ipconfig</code> on Windows. </p>
 
-<p>The following sections describe the basic requirements for
-sending messages.</p>
+<p> You server is now ready.</p>
 
-<h3 id="target">Target</h3>
-<p>Required. When your app server sends a message in GCM, it must specify a target.</p>
-<p>For HTTP you must specify the target as one of:</p>
-<ul>
-<li><code>registration_ids</code>: For sending to 1 more more devices (up to 1000).
-When you send a message to multiple registration IDs, that is called a multicast message.</li>
-<li><code>notification_key</code>: For sending to multiple devices owned by a single user.</li>
-</ul>
-<p>For CCS (XMPP):</p>
-<ul>
-<li>You must specify the target as the &quot;to&quot; field, where the &quot;to&quot;
-field may contain a single registration ID or a notification key.
-CCS does not support multicast messaging.</li>
-</ul>
-<h3 id="payload">Payload</h3>
-<p>Optional. If you are including a payload in the message, you use the <code>data</code>
-parameter to include the payload. This applies for both HTTP and CCS.</p>
+<h3 id="appengine-setup">Using App Engine for Java</h3>
 
-<h3 id="params">Message parameters</h3>
-
-<p>The following table lists the parameters that a 3rd-party app server might
-include in the JSON messages it sends to a connection server. See the "Where Supported"
-column for information about which connection servers support that particular
-parameter.</p>
-
-<p class="table-caption" id="table1">
-  <strong>Table 1.</strong> Message parameters.</p>
-
-<table>
-  <tr>
-    <th>Field</th>
-    <th>Description</th>
-<th>Where Supported</th>
-</tr>
-  <td><code>to</code></td>
-<td>In CCS, used in place of <code>registration_ids</code> to specify the
-recipient of a message. Its value must be a registration ID.
-The value is a string. Required.</td>
-<td>CCS</td>
-</tr>
-<tr>
-<td><code>message_id</code></td>
-<td>In CCS, uniquely identifies a message in an XMPP connection. The value is a
-string that uniquely identifies the associated message. The value is a string. Required.</td>
-<td>CCS</td>
-</tr>
-<tr>
-<td><code>message_type</code></td>
-<td>In CCS, indicates a special status message, typically sent by the system.
-However, your app server also uses this parameter to send an 'ack' or 'nack'
-message back to the CCS connection server. For more discussion of this topic, see
-<a href="ccs.html">Cloud Connection Server</a>. The value is a string. Optional.</td>
-<td>CCS</td>
-<tr>
-  <td><code>registration_ids</code></td>
-  <td>A string array with the list of devices (registration IDs) receiving the
-message. It must contain at least 1 and at most 1000 registration IDs. To send a
-multicast message, you must use JSON. For sending a single message to a single
-device, you could use a JSON object with just 1 registration id, or plain text
-(see below). A request must include a recipient&mdash;this can be either a
-registration ID, an array of registration IDs, or a {@code notification_key}.
-Required.</td>
-<td>HTTP</td>
-</tr>
- <tr>
-    <td><code>notification_key</code></td>
-    <td>A string that maps a single user to multiple registration IDs associated
-with that user. This allows a 3rd-party server to send a single message to
-multiple app instances (typically on multiple devices) owned by a single user.
-A 3rd-party server can use {@code notification_key} as the target for a message
-instead of an individual registration ID (or array of registration IDs). The maximum
-number of members allowed for a {@code notification_key} is 10. For more discussion
-of this topic, see <a href="notifications.html">User Notifications</a>. Optional.
-</td>
-<td style="width:100px">HTTP. This feature is supported in CCS, but you use it by
-specifying a notification key in the &quot;to&quot; field.</td>
-</tr>
-  <tr>
-    <td><code>collapse_key</code></td>
-    <td>An arbitrary string (such as &quot;Updates Available&quot;) that is used
-to collapse a group of like messages
-when the device is offline, so that only the last message gets sent to the
-client. This is intended to avoid sending too many messages to the phone when it
-comes back online. Note that since there is no guarantee of the order in which
-messages get sent, the &quot;last&quot; message may not actually be the last
-message sent by the application server. Collapse keys are also called
-<a href="#s2s">send-to-sync messages</a>.
-<br>
-<strong>Note:</strong> GCM allows a maximum of 4 different collapse keys to be
-used by the GCM server
-at any given time. In other words, the GCM server can simultaneously store 4
-different send-to-sync messages per device, each with a different collapse key.
-If you exceed
-this number GCM will only keep 4 collapse keys, with no guarantees about which
-ones they will be. See <a href="adv.html#collapsible">Advanced Topics</a> for more
-discussion of this topic. Optional.</td>
-<td>CCS, HTTP</td>
-</tr>
-  <tr>
-    <td><code>data</code></td>
-    <td>A JSON object whose fields represents the key-value pairs of the message's
-payload data. If present, the payload data it will be
-included in the Intent as application data, with the key being the extra's name.
-For instance, <code>"data":{"score":"3x1"}</code> would result in an intent extra
-named <code>score</code> whose value is the string <code>3x1</code>.
-There is no limit on the number of key/value pairs, though there is a limit on
-the total size of the message (4kb). The values could be any JSON object, but we
-recommend using strings, since the values will be converted to strings in the GCM
-server anyway. If you want to include objects or other non-string data types
-(such as integers or booleans), you have to do the conversion to string yourself.
-Also note that the key cannot be a reserved word (<code>from</code> or any word
-starting with <code>google.</code>). To complicate things slightly, there are
-some reserved words (such as <code>collapse_key</code>) that are technically
-allowed in payload data. However, if the request also contains the word, the
-value in the request will overwrite the value in the payload data. Hence using
-words that are defined as field names in this table is not recommended, even in
-cases where they are technically allowed. Optional.</td>
-<td>CCS, HTTP</td>
-</tr>
-  <tr>
-    <td><code>delay_while_idle</code></td>
-    <td>If included, indicates that the message should not be sent immediately
-if the device is idle. The server will wait for the device to become active, and
-then only the last message for each <code>collapse_key</code> value will be
-sent. The default value is <code>false</code>, and must be a JSON boolean. Optional.</td>
-<td>CCS, HTTP</td>
-</tr>
-  <tr>
-    <td><code>time_to_live</code></td>
-    <td>How long (in seconds) the message should be kept on GCM storage if the
-device is offline. Optional (default time-to-live is 4 weeks, and must be set as
-a JSON number).</td>
-<td>CCS, HTTP</td>
-</tr>
-<tr>
-  <td><code>restricted_package_name</code></td>
-  <td>A string containing the package name of your application. When set, messages
-will only be sent to registration IDs that match the package name. Optional.
-  </td>
-<td>HTTP</td>
-</tr>
-<tr>
-  <td><code>dry_run</code></td>
-  <td>If included, allows developers to test their request without actually
-sending a message. Optional. The default value is <code>false</code>, and must
-be a JSON boolean.
-  </td>
-<td>HTTP</td>
-</tr>
-</table>
-
-<p>If you want to test your request (either JSON or plain text) without delivering
-the message to the devices, you can set an optional HTTP or JSON parameter called
-<code>dry_run</code> with the value <code>true</code>. The result will be almost
-identical to running the request without this parameter, except that the message
-will not be delivered to the devices. Consequently, the response will contain fake
-IDs for the message and multicast fields.</p>
-
-<h3 id="plain-text">Plain text (HTTP only)</h3>
-
-<p>If you are using plain text instead of JSON, the message fields must be set as
-HTTP parameters sent in the body, and their syntax is slightly different, as
-described below:
-<table>
-  <tr>
-    <th>Field</th>
-    <th>Description</th>
-  </tr>
-  <tr>
-    <td><code>registration_id</code></td>
-    <td>Must contain the registration ID of the single device receiving the message.
-Required.</td>
-  </tr>
-  <tr>
-    <td><code>collapse_key</code></td>
-    <td>Same as JSON (see previous table). Optional.</td>
-  </tr>
-  <tr>
-    <td><code>data.&lt;key&gt;</code></td>
-
-    <td>Payload data, expressed as parameters prefixed with <code>data.</code> and
-suffixed as the key. For instance, a parameter of <code>data.score=3x1</code> would
-result in an intent extra named <code>score</code> whose value is the string
-<code>3x1</code>. There is no limit on the number of key/value parameters, though
-there is a limit on the total size of the  message. Also note that the key cannot
-be a reserved word (<code>from</code> or any word starting with
-<code>google.</code>). To complicate things slightly, there are some reserved words
-(such as <code>collapse_key</code>) that are technically allowed in payload data.
-However, if the request also contains the word, the value in the request will
-overwrite the value in the payload data. Hence using words that are defined as
-field names in this table is not recommended, even in cases where they are
-technically allowed. Optional.</td>
-
-  </tr>
-  <tr>
-    <td><code>delay_while_idle</code></td>
-    <td>Should be represented as <code>1</code> or <code>true</code> for
-<code>true</code>, anything else for <code>false</code>. Optional. The default
-value is <code>false</code>.</td>
-  </tr>
-  <tr>
-    <td><code>time_to_live</code></td>
-    <td>Same as JSON (see previous table). Optional.</td>
-  </tr>
-<tr>
-  <td><code>restricted_package_name</code></td>
-  <td>Same as JSON (see previous table). Optional.
-  </td>
-</tr>
-<tr>
-  <td><code>dry_run</code></td>
-  <td>Same as JSON (see previous table). Optional.
-  </td>
-</tr>
-</table>
-
-<h2 id="receive">Receiving Messages</h2>
-
-<p>This is the sequence of events that occurs when an Android application
-installed on a mobile device receives a message:</p>
-
+<p>To set up the server using a standard App Engine for Java:</p>
 <ol>
-  <li>The system receives the incoming message and extracts the raw key/value
-pairs from the message payload, if any.</li>
-  <li>The system passes the key/value pairs to the targeted Android application
-in a <code>com.google.android.c2dm.intent.RECEIVE</code> Intent as a set of
-extras.</li>
-  <li>The Android application extracts the raw data
-from the <code>com.google.android.c2dm.intent.RECEIVE</code><code> </code>Intent
-by key and processes the data.</li>
-</ol>
+  <li>Get the files from the <a href="http://code.google.com/p/gcm">open source site</a>, as described above.</p>
+  </li>
+  <li>In a text editor, edit <code>samples/gcm-demo-appengine/src/com/google/android/gcm/demo/server/ApiKeyInitializer.java</code> and replace the existing text with the API key obtained above.
 
-<p>See the documentation for each connection server for more detail on how it
-handles responses.</p>
+  <p class="note"><strong>Note:</strong> The API key value set in that class will be used just once to create a persistent entity on App Engine. If you deploy the application, you can use App Engine's <code>Datastore Viewer</code> to change it later.</p>
+  
+  </li>
+  <li>In a shell window, go to the <code>samples/gcm-demo-appengine</code> directory.</li>
+  <li>Start the development App Engine server by <code>ant runserver</code>, using the <code>-Dsdk.dir</code> to indicate the location of the App Engine SDK and <code>-Dserver.host</code> to set your server's hostname or IP address:</li>
+
+<pre class="prettyprint">
+$ ant -Dsdk.dir=/opt/google/appengine-java-sdk runserver -Dserver.host=192.168.1.10
+Buildfile: gcm-demo-appengine/build.xml
+
+init:
+    [mkdir] Created dir: gcm-demo-appengine/dist
+
+copyjars:
+
+compile:
+
+datanucleusenhance:
+  [enhance] DataNucleus Enhancer (version 1.1.4) : Enhancement of classes
+  [enhance] DataNucleus Enhancer completed with success for 0 classes. Timings : input=28 ms, enhance=0 ms, total=28 ms. Consult the log for full details
+  [enhance] DataNucleus Enhancer completed and no classes were enhanced. Consult the log for full details
+
+runserver:
+     [java] Jun 15, 2012 8:46:06 PM com.google.apphosting.utils.jetty.JettyLogger info
+     [java] INFO: Logging to JettyLogger(null) via com.google.apphosting.utils.jetty.JettyLogger
+     [java] Jun 15, 2012 8:46:06 PM com.google.apphosting.utils.config.AppEngineWebXmlReader readAppEngineWebXml
+     [java] INFO: Successfully processed gcm-demo-appengine/WebContent/WEB-INF/appengine-web.xml
+     [java] Jun 15, 2012 8:46:06 PM com.google.apphosting.utils.config.AbstractConfigXmlReader readConfigXml
+     [java] INFO: Successfully processed gcm-demo-appengine/WebContent/WEB-INF/web.xml
+     [java] Jun 15, 2012 8:46:09 PM com.google.android.gcm.demo.server.ApiKeyInitializer contextInitialized
+     [java] SEVERE: Created fake key. Please go to App Engine admin console, change its value to your API Key (the entity type is 'Settings' and its field to be changed is 'ApiKey'), then restart the server!
+     [java] Jun 15, 2012 8:46:09 PM com.google.appengine.tools.development.DevAppServerImpl start
+     [java] INFO: The server is running at http://192.168.1.10:8080/
+     [java] Jun 15, 2012 8:46:09 PM com.google.appengine.tools.development.DevAppServerImpl start
+     [java] INFO: The admin console is running at http://192.168.1.10:8080/_ah/admin
+</pre>
+
+  <li>Open the server's main page in a browser. The URL depends on the server you're using and your machine's IP address, but it will be something like <code>http://192.168.1.10:8080/home</code>, where <code>/home</code> is the path of the main servlet.</li>
+  
+  <p class="note"><strong>Note:</strong> You can get the IP by running <code>ifconfig</code> on Linux or MacOS, or <code>ipconfig</code> on Windows.</p>
+  
+</ol>
+<p> You server is now ready.</p>
+
+
diff --git a/docs/html/google/google_toc.cs b/docs/html/google/google_toc.cs
index 7f76c12..999c44e 100644
--- a/docs/html/google/google_toc.cs
+++ b/docs/html/google/google_toc.cs
@@ -123,27 +123,24 @@
         <span class="en">Google Cloud Messaging</span></a>
       </div>
       <ul>
-        <li><a href="<?cs var:toroot?>google/gcm/gcm.html">
-            <span class="en">Overview</span></a>
-        </li>
         <li><a href="<?cs var:toroot?>google/gcm/gs.html">
             <span class="en">Getting Started</span></a>
         </li>
-        <li><a href="<?cs var:toroot?>google/gcm/client.html">
-            <span class="en">Implementing GCM Client</span></a>
+        <li><a href="<?cs var:toroot?>google/gcm/gcm.html">
+            <span class="en">Architectural Overview</span></a>
         </li>
-        <li class="nav-section"><div class="nav-section-header"><a href="<?cs var:toroot?>google/gcm/server.html">
-              <span class="en">Implementing GCM Server</span></a></div>
-              <ul>
-              <li><a href="<?cs var:toroot?>google/gcm/ccs.html">
-              <span class="en">CCS (XMPP)</span></a></li>
-              <li><a href="<?cs var:toroot?>google/gcm/http.html">
-              <span class="en">HTTP</span></a></li>
-              </ul>
+         <li><a href="<?cs var:toroot?>google/gcm/ccs.html">
+              <span class="en">Cloud Connection Server</span></a>
         </li>
         <li><a href="<?cs var:toroot?>google/gcm/notifications.html">
               <span class="en">User Notifications</span></a>
         </li>
+        <li><a href="<?cs var:toroot?>google/gcm/client.html">
+            <span class="en">GCM Client</span></a>
+        </li>
+        <li><a href="<?cs var:toroot?>google/gcm/server.html">
+            <span class="en">GCM Server</span></a>
+        </li>
         <li><a href="<?cs var:toroot?>google/gcm/adv.html">
             <span class="en">Advanced Topics</span></a>
         </li>
diff --git a/docs/html/images/gcm/CCS-ack.png b/docs/html/images/gcm/CCS-ack.png
deleted file mode 100644
index bce2ab2..0000000
--- a/docs/html/images/gcm/CCS-ack.png
+++ /dev/null
Binary files differ
diff --git a/docs/html/images/gcm/GCM-arch.png b/docs/html/images/gcm/GCM-arch.png
deleted file mode 100644
index e8ffb15..0000000
--- a/docs/html/images/gcm/GCM-arch.png
+++ /dev/null
Binary files differ
diff --git a/graphics/java/android/graphics/Matrix.java b/graphics/java/android/graphics/Matrix.java
index 4e06448..32e0c01 100644
--- a/graphics/java/android/graphics/Matrix.java
+++ b/graphics/java/android/graphics/Matrix.java
@@ -21,9 +21,6 @@
 
 /**
  * The Matrix class holds a 3x3 matrix for transforming coordinates.
- * Matrix does not have a constructor, so it must be explicitly initialized
- * using either reset() - to construct an identity matrix, or one of the set..()
- * functions (e.g. setTranslate, setRotate, etc.).
  */
 public class Matrix {
 
diff --git a/location/java/android/location/IFusedGeofenceHardware.aidl b/location/java/android/location/IFusedGeofenceHardware.aidl
index 9dbf1f4..d8c3585 100644
--- a/location/java/android/location/IFusedGeofenceHardware.aidl
+++ b/location/java/android/location/IFusedGeofenceHardware.aidl
@@ -16,8 +16,8 @@
  
 package android.location;
 
-import android.location.Geofence;
- 
+import android.hardware.location.GeofenceHardwareRequestParcelable;
+
 /**
  * Fused Geofence Hardware interface.
  *
@@ -39,11 +39,9 @@
     /**
      * Adds a given list of geofences to the system.
      *
-     * @param geofenceIdsArray    The list of geofence Ids to add.
-     * @param geofencesArray      the list of geofences to add.
+     * @param geofenceRequestsArray    The list of geofences to add.
      */
-    // TODO: [GeofenceIntegration] GeofenceHardwareRequest is not a parcelable class exposed in aidl
-    void addGeofences(in int[] geofenceIdsArray, in Geofence[] geofencesArray);
+    void addGeofences(in GeofenceHardwareRequestParcelable[] geofenceRequestsArray);
 
     /**
      * Removes a give list of geofences from the system.
@@ -79,7 +77,8 @@
      *                                      the geofence.
      * @param monitorTransitions            The set of transitions to monitor.
      * @param notificationResponsiveness    The notification responsivness needed.
-     * @param unknownTimer                  The time span associated with the
+     * @param unknownTimer                  The time span associated with the.
+     * @param sourcesToUse                  The source technologies to use.
      *
      * Remarks: keep the options as separate fields to be able to leverage the class
      * GeofenceHardwareRequest without any changes
@@ -89,5 +88,6 @@
             in int lastTransition,
             in int monitorTransitions,
             in int notificationResponsiveness,
-            in int unknownTimer);
+            in int unknownTimer,
+            in int sourcesToUse);
 }
diff --git a/location/java/android/location/SettingInjectorService.java b/location/java/android/location/SettingInjectorService.java
new file mode 100644
index 0000000..d410408
--- /dev/null
+++ b/location/java/android/location/SettingInjectorService.java
@@ -0,0 +1,181 @@
+/*
+ * 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.app.IntentService;
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.Message;
+import android.os.Messenger;
+import android.os.RemoteException;
+import android.preference.Preference;
+import android.util.Log;
+
+/**
+ * Dynamically specifies the summary (subtile) and enabled status of a preference injected into
+ * the "Settings > Location > Location services" list.
+ *
+ * The location services list is intended for use only by preferences that affect multiple apps from
+ * the same developer. Location settings that apply only to one app should be shown within that app,
+ * rather than in the system settings.
+ *
+ * To add a preference to the list, a subclass of {@link SettingInjectorService} must be declared in
+ * the manifest as so:
+ * <pre>
+ *     <service android:name="com.example.android.injector.MyInjectorService" >
+ *         <intent-filter>
+ *             <action android:name="com.android.settings.InjectedLocationSetting" />
+ *         </intent-filter>
+ *
+ *         <meta-data
+ *             android:name="com.android.settings.InjectedLocationSetting"
+ *             android:resource="@xml/my_injected_location_setting" />
+ *     </service>
+ * </pre>
+ * The resource file specifies the static data for the setting:
+ * <pre>
+ *     <injected-location-setting xmlns:android="http://schemas.android.com/apk/res/android"
+ *         android:label="@string/injected_setting_label"
+ *         android:icon="@drawable/ic_launcher"
+ *         android:settingsActivity="com.example.android.injector.MySettingActivity"
+ *     />
+ * </pre>
+ * Here:
+ * <ul>
+ *     <li>label: The {@link Preference#getTitle()} value. The title should make it clear which apps
+ *     are affected by the setting, typically by including the name of the developer. For example,
+ *     "Acme Corp. ads preferences." </li>
+ *
+ *     <li>icon: The {@link Preference#getIcon()} value. Typically this will be a generic icon for
+ *     the developer rather than the icon for an individual app.</li>
+ *
+ *     <li>settingsActivity: the activity which is launched to allow the user to modify the setting
+ *     value  The activity must be in the same package as the subclass of
+ *     {@link SettingInjectorService}. The activity should use your own branding to help emphasize
+ *     to the user that it is not part of the system settings.</li>
+ * </ul>
+ *
+ * For consistency, the label and {@link #getStatus()} values should be provided in all of the
+ * locales supported by the system settings app. The text should not contain offensive language.
+ *
+ * For compactness, only one copy of a given setting should be injected. If each account has a
+ * distinct value for the setting, then the {@link #getStatus()} value should represent a summary of
+ * the state across all of the accounts and {@code settingsActivity} should display the value for
+ * each account.
+ *
+ * Apps that violate these guidelines will be taken down from the Google Play Store and/or flagged
+ * as malware.
+ */
+// TODO: is there a public list of supported locales?
+// TODO: is there a public list of guidelines for settings text?
+public abstract class SettingInjectorService extends IntentService {
+
+    /**
+     * Name of the bundle key for the string specifying the status of the setting (e.g., "ON" or
+     * "OFF").
+     *
+     * @hide
+     */
+    public static final String STATUS_KEY = "status";
+
+    /**
+     * Name of the bundle key for the string specifying whether the setting is currently enabled.
+     *
+     * @hide
+     */
+    public static final String ENABLED_KEY = "enabled";
+
+    /**
+     * Name of the intent key used to specify the messenger
+     *
+     * @hide
+     */
+    public static final String MESSENGER_KEY = "messenger";
+
+    private final String mLogTag;
+
+    /**
+     * Constructor.
+     *
+     * @param logTag used for logging, must be less than 23 characters
+     */
+    public SettingInjectorService(String logTag) {
+        super(logTag);
+
+        // Fast fail if log tag is too long
+        Log.isLoggable(logTag, Log.WARN);
+
+        mLogTag = logTag;
+    }
+
+    @Override
+    final protected void onHandleIntent(Intent intent) {
+        // Get messenger first to ensure intent doesn't get messed with (in case we later decide
+        // to pass intent into getStatus())
+        Messenger messenger = intent.getParcelableExtra(MESSENGER_KEY);
+
+        Status status = getStatus();
+
+        // Send the status back to the caller via the messenger
+        Message message = Message.obtain();
+        Bundle bundle = new Bundle();
+        bundle.putString(STATUS_KEY, status.summary);
+        bundle.putBoolean(ENABLED_KEY, status.enabled);
+        message.setData(bundle);
+
+        if (Log.isLoggable(mLogTag, Log.DEBUG)) {
+            Log.d(mLogTag,
+                    "received " + intent + " and " + status + ", sending message: " + message);
+        }
+        try {
+            messenger.send(message);
+        } catch (RemoteException e) {
+            Log.e(mLogTag, "", e);
+        }
+    }
+
+    /**
+     * Reads the status of the setting.
+     */
+    protected abstract Status getStatus();
+
+    /**
+     * Dynamic characteristics of an injected location setting.
+     */
+    public static final class Status {
+
+        public final String summary;
+
+        public final boolean enabled;
+
+        /**
+         * Constructor.
+         *
+         * @param summary the {@link Preference#getSummary()} value
+         * @param enabled the {@link Preference#isEnabled()} value
+         */
+        public Status(String summary, boolean enabled) {
+            this.summary = summary;
+            this.enabled = enabled;
+        }
+
+        @Override
+        public String toString() {
+            return "Status{summary='" + summary + '\'' + ", enabled=" + enabled + '}';
+        }
+    }
+}
diff --git a/media/java/android/media/MediaCodec.java b/media/java/android/media/MediaCodec.java
index 703eb27..f4e867e 100644
--- a/media/java/android/media/MediaCodec.java
+++ b/media/java/android/media/MediaCodec.java
@@ -564,6 +564,52 @@
     public native final String getName();
 
     /**
+     * Change a video encoder's target bitrate on the fly. The value is an
+     * Integer object containing the new bitrate in bps.
+     */
+    public static final String PARAMETER_KEY_VIDEO_BITRATE = "videoBitrate";
+
+    /**
+     * Temporarily suspend/resume encoding of input data. While suspended
+     * input data is effectively discarded instead of being fed into the
+     * encoder. This parameter really only makes sense to use with an encoder
+     * in "surface-input" mode, as the client code has no control over the
+     * input-side of the encoder in that case.
+     * The value is an Integer object containing the value 1 to suspend
+     * or the value 0 to resume.
+     */
+    public static final String PARAMETER_KEY_SUSPEND = "drop-input-frames";
+
+    /**
+     * Request that the encoder produce a sync frame "soon".
+     * Provide an Integer with the value 0.
+     */
+    public static final String PARAMETER_KEY_REQUEST_SYNC_FRAME = "request-sync";
+
+    /**
+     * Communicate additional parameter changes to the component instance.
+     */
+    public final void setParameters(Map<String, Object> params) {
+        if (params == null) {
+            return;
+        }
+
+        String[] keys = new String[params.size()];
+        Object[] values = new Object[params.size()];
+
+        int i = 0;
+        for (Map.Entry<String, Object> entry: params.entrySet()) {
+            keys[i] = entry.getKey();
+            values[i] = entry.getValue();
+            ++i;
+        }
+
+        setParameters(keys, values);
+    }
+
+    private native final void setParameters(String[] keys, Object[] values);
+
+    /**
      * Get the codec info. If the codec was created by createDecoderByType
      * or createEncoderByType, what component is chosen is not known beforehand,
      * and thus the caller does not have the MediaCodecInfo.
diff --git a/media/java/android/media/MediaCodecInfo.java b/media/java/android/media/MediaCodecInfo.java
index aeed7d4..90c12c6 100644
--- a/media/java/android/media/MediaCodecInfo.java
+++ b/media/java/android/media/MediaCodecInfo.java
@@ -72,7 +72,8 @@
     /**
      * Encapsulates the capabilities of a given codec component.
      * For example, what profile/level combinations it supports and what colorspaces
-     * it is capable of providing the decoded data in.
+     * it is capable of providing the decoded data in, as well as some
+     * codec-type specific capability flags.
      * <p>You can get an instance for a given {@link MediaCodecInfo} object with
      * {@link MediaCodecInfo#getCapabilitiesForType getCapabilitiesForType()}, passing a MIME type.
      */
@@ -139,6 +140,24 @@
          * OMX_COLOR_FORMATTYPE.
          */
         public int[] colorFormats;
+
+        private final static int FLAG_SupportsAdaptivePlayback       = (1 << 0);
+        private int flags;
+
+        /**
+         * <b>video decoder only</b>: codec supports seamless resolution changes.
+         */
+        public final static String FEATURE_AdaptivePlayback       = "adaptive-playback";
+
+        /**
+         * Query codec feature capabilities.
+         */
+        public final boolean isFeatureSupported(String name) {
+            if (name.equals(FEATURE_AdaptivePlayback)) {
+                return (flags & FLAG_SupportsAdaptivePlayback) != 0;
+            }
+            return false;
+        }
     };
 
     /**
diff --git a/media/jni/android_media_MediaCodec.cpp b/media/jni/android_media_MediaCodec.cpp
index ae1db87..a859506 100644
--- a/media/jni/android_media_MediaCodec.cpp
+++ b/media/jni/android_media_MediaCodec.cpp
@@ -310,6 +310,10 @@
     return OK;
 }
 
+status_t JMediaCodec::setParameters(const sp<AMessage> &msg) {
+    return mCodec->setParameters(msg);
+}
+
 void JMediaCodec::setVideoScalingMode(int mode) {
     if (mSurfaceTextureClient != NULL) {
         native_window_set_scaling_mode(mSurfaceTextureClient.get(), mode);
@@ -837,6 +841,27 @@
     return NULL;
 }
 
+static void android_media_MediaCodec_setParameters(
+        JNIEnv *env, jobject thiz, jobjectArray keys, jobjectArray vals) {
+    ALOGV("android_media_MediaCodec_setParameters");
+
+    sp<JMediaCodec> codec = getMediaCodec(env, thiz);
+
+    if (codec == NULL) {
+        jniThrowException(env, "java/lang/IllegalStateException", NULL);
+        return;
+    }
+
+    sp<AMessage> params;
+    status_t err = ConvertKeyValueArraysToMessage(env, keys, vals, &params);
+
+    if (err == OK) {
+        err = codec->setParameters(params);
+    }
+
+    throwExceptionAsNecessary(env, err);
+}
+
 static void android_media_MediaCodec_setVideoScalingMode(
         JNIEnv *env, jobject thiz, jint mode) {
     sp<JMediaCodec> codec = getMediaCodec(env, thiz);
@@ -986,6 +1011,9 @@
     { "getName", "()Ljava/lang/String;",
       (void *)android_media_MediaCodec_getName },
 
+    { "setParameters", "([Ljava/lang/String;[Ljava/lang/Object;)V",
+      (void *)android_media_MediaCodec_setParameters },
+
     { "setVideoScalingMode", "(I)V",
       (void *)android_media_MediaCodec_setVideoScalingMode },
 
diff --git a/media/jni/android_media_MediaCodec.h b/media/jni/android_media_MediaCodec.h
index 282d2c5..2fbbd72 100644
--- a/media/jni/android_media_MediaCodec.h
+++ b/media/jni/android_media_MediaCodec.h
@@ -87,6 +87,8 @@
 
     status_t getName(JNIEnv *env, jstring *name) const;
 
+    status_t setParameters(const sp<AMessage> &params);
+
     void setVideoScalingMode(int mode);
 
 protected:
diff --git a/media/jni/android_media_MediaCodecList.cpp b/media/jni/android_media_MediaCodecList.cpp
index 04430ec..caa594e 100644
--- a/media/jni/android_media_MediaCodecList.cpp
+++ b/media/jni/android_media_MediaCodecList.cpp
@@ -110,10 +110,11 @@
 
     Vector<MediaCodecList::ProfileLevel> profileLevels;
     Vector<uint32_t> colorFormats;
+    uint32_t flags;
 
     status_t err =
         MediaCodecList::getInstance()->getCodecCapabilities(
-                index, typeStr, &profileLevels, &colorFormats);
+                index, typeStr, &profileLevels, &colorFormats, &flags);
 
     env->ReleaseStringUTFChars(type, typeStr);
     typeStr = NULL;
@@ -127,6 +128,9 @@
         env->FindClass("android/media/MediaCodecInfo$CodecCapabilities");
     CHECK(capsClazz != NULL);
 
+    jfieldID flagsField =
+        env->GetFieldID(capsClazz, "flags", "I");
+
     jobject caps = env->AllocObject(capsClazz);
 
     jclass profileLevelClazz =
@@ -163,6 +167,8 @@
 
     env->SetObjectField(caps, profileLevelsField, profileLevelArray);
 
+    env->SetIntField(caps, flagsField, flags);
+
     env->DeleteLocalRef(profileLevelArray);
     profileLevelArray = NULL;
 
diff --git a/packages/PrintSpooler/AndroidManifest.xml b/packages/PrintSpooler/AndroidManifest.xml
index 74fd7a8..c00639d 100644
--- a/packages/PrintSpooler/AndroidManifest.xml
+++ b/packages/PrintSpooler/AndroidManifest.xml
@@ -50,6 +50,12 @@
             android:theme="@style/PrintJobConfigActivityTheme">
         </activity>
 
+        <activity
+            android:name=".ChoosePrinterActivity"
+            android:exported="false"
+            android:theme="@android:style/Theme.Holo.Light">
+        </activity>
+
         <receiver
             android:name=".NotificationController$NotificationBroadcastReceiver"
             android:exported="false" >
diff --git a/packages/PrintSpooler/res/layout/choose_printer_activity.xml b/packages/PrintSpooler/res/layout/choose_printer_activity.xml
new file mode 100644
index 0000000..c34a108
--- /dev/null
+++ b/packages/PrintSpooler/res/layout/choose_printer_activity.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 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.
+-->
+
+<ListView xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@+id/list_view"
+    android:layout_width="fill_parent"
+    android:layout_height="fill_parent"
+    android:orientation="vertical">
+</ListView>
+
diff --git a/packages/PrintSpooler/res/menu/choose_printer_activity.xml b/packages/PrintSpooler/res/menu/choose_printer_activity.xml
new file mode 100644
index 0000000..3774279
--- /dev/null
+++ b/packages/PrintSpooler/res/menu/choose_printer_activity.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 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.
+-->
+
+<menu xmlns:android="http://schemas.android.com/apk/res/android" >
+
+    <item
+        android:id="@+id/action_search"
+        android:title="@string/search"
+        android:icon="@*android:drawable/ic_menu_search_holo_light"
+        android:actionViewClass="android.widget.SearchView"
+        android:showAsAction="ifRoom"
+        android:alphabeticShortcut="f"
+         android:imeOptions="actionSearch">
+    </item>
+
+</menu>
diff --git a/packages/PrintSpooler/res/values/strings.xml b/packages/PrintSpooler/res/values/strings.xml
index 2086f58..1cd611f 100644
--- a/packages/PrintSpooler/res/values/strings.xml
+++ b/packages/PrintSpooler/res/values/strings.xml
@@ -58,6 +58,11 @@
     <!-- Title for the temporary dialog show while an app is generating a print job. [CHAR LIMIT=30] -->
     <string name="generating_print_job">Generating print job</string>
 
+    <!-- Choose printer activity -->
+
+    <!-- Title for the share action bar menu item. [CHAR LIMIT=20] -->
+    <string name="search">Search</string>
+
     <!-- Notifications -->
 
     <!-- Template for the notificaiton label for a printing print job. [CHAR LIMIT=25] -->
diff --git a/packages/PrintSpooler/src/com/android/printspooler/AvailablePrinterProvider.java b/packages/PrintSpooler/src/com/android/printspooler/AvailablePrinterProvider.java
new file mode 100644
index 0000000..658a224
--- /dev/null
+++ b/packages/PrintSpooler/src/com/android/printspooler/AvailablePrinterProvider.java
@@ -0,0 +1,285 @@
+/*
+ * 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.printspooler;
+
+import android.content.Context;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.Message;
+import android.os.RemoteException;
+import android.print.IPrinterDiscoverySessionController;
+import android.print.IPrinterDiscoverySessionObserver;
+import android.print.PrinterId;
+import android.print.PrinterInfo;
+import android.util.ArraySet;
+import android.util.Log;
+
+import java.lang.ref.WeakReference;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * This class is responsible to provide the available printers.
+ * It starts and stops printer discovery and manages the returned
+ * printers.
+ */
+public class AvailablePrinterProvider extends DataProvider<PrinterInfo>
+        implements DataLoader {
+    private static final String LOG_TAG = "AvailablePrinterProvider";
+
+    private final Set<PrinterId> mPrinteIdsSet = new ArraySet<PrinterId>();
+
+    private final List<PrinterInfo> mPrinters = new ArrayList<PrinterInfo>();
+
+    private final List<PrinterId> mPriorityList;
+
+    private PrinterDiscoverySession mDiscoverySession;
+
+    public AvailablePrinterProvider(Context context, List<PrinterId> priorityList) {
+        mDiscoverySession = new PrinterDiscoverySession(context.getMainLooper());
+        mPriorityList = priorityList;
+    }
+
+    @Override
+    public void startLoadData() {
+        mDiscoverySession.open();
+    }
+
+    @Override
+    public void stopLoadData() {
+        mDiscoverySession.close();
+    }
+
+    @Override
+    public int getItemCount() {
+        return mPrinters.size();
+    }
+
+    @Override
+    public int getItemIndex(PrinterInfo printer) {
+        return mPrinters.indexOf(printer);
+    }
+
+    @Override
+    public PrinterInfo getItemAt(int index) {
+        return mPrinters.get(index);
+    }
+
+    public void refreshItem(int index) {
+        PrinterInfo printer = getItemAt(index);
+        mDiscoverySession.requestPrinterUpdate(printer.getId());
+    }
+
+    private void addPrinters(List<PrinterInfo> printers) {
+        boolean addedPrinters = false;
+
+        final int addedPrinterCount = printers.size();
+        for (int i = 0; i < addedPrinterCount; i++) {
+           PrinterInfo addedPrinter = printers.get(i);
+           if (mPrinteIdsSet.add(addedPrinter.getId())) {
+               mPrinters.add(addedPrinter);
+               addedPrinters = true;
+           }
+        }
+
+        if (addedPrinters) {
+            notifyChanged();
+        }
+    }
+
+    private void updatePrinters(List<PrinterInfo> printers) {
+        boolean updatedPrinters = false;
+
+        final int updatedPrinterCount = printers.size();
+        for (int i = 0; i < updatedPrinterCount; i++) {
+            PrinterInfo updatedPrinter = printers.get(i);
+            if (mPrinteIdsSet.contains(updatedPrinter.getId())) {
+                final int oldPrinterCount = mPrinters.size();
+                for (int j = 0; j < oldPrinterCount; j++) {
+                    PrinterInfo oldPrinter = mPrinters.get(j);
+                    if (updatedPrinter.getId().equals(oldPrinter.getId())) {
+                        mPrinters.set(j, updatedPrinter);
+                        updatedPrinters = true;
+                        break;
+                    }
+                }
+            }
+        }
+
+        if (updatedPrinters) {
+            notifyChanged();
+        }
+    }
+
+    private void removePrinters(List<PrinterId> printers) {
+        boolean removedPrinters = false;
+
+        final int removedPrinterCount = printers.size();
+        for (int i = 0; i < removedPrinterCount; i++) {
+            PrinterId removedPrinter = printers.get(i);
+            if (mPrinteIdsSet.contains(removedPrinter)) {
+                mPrinteIdsSet.remove(removedPrinter);
+                Iterator<PrinterInfo> iterator = mPrinters.iterator();
+                while (iterator.hasNext()) {
+                    PrinterInfo oldPrinter = iterator.next();
+                    if (removedPrinter.equals(oldPrinter.getId())) {
+                        iterator.remove();
+                        break;
+                    }
+                }
+            }
+        }
+
+        if (removedPrinters) {
+            notifyChanged();
+        }
+    }
+
+    private final class PrinterDiscoverySession {
+
+        private final Handler mHandler;
+
+        private final IPrinterDiscoverySessionObserver mObserver;
+
+        private IPrinterDiscoverySessionController mController;
+
+        public PrinterDiscoverySession(Looper looper) {
+            mHandler = new SessionHandler(looper);
+            mObserver = new PrinterDiscoverySessionObserver(this);
+        }
+
+        public void open() {
+            PrintSpooler.peekInstance().createPrinterDiscoverySession(
+                    mObserver);
+        }
+
+        public void close() {
+            if (mController != null) {
+                try {
+                    mController.close();
+                } catch (RemoteException re) {
+                    Log.e(LOG_TAG, "Error closing printer discovery session", re);
+                } finally {
+                    mController = null;
+                }
+            }
+        }
+
+        public void requestPrinterUpdate(PrinterId printerId) {
+            if (mController != null) {
+                try {
+                    mController.requestPrinterUpdate(printerId);
+                } catch (RemoteException re) {
+                    Log.e(LOG_TAG, "Error requesting printer udpdate", re);
+                }
+            }
+        }
+
+        private final class SessionHandler extends Handler {
+            public static final int MSG_SET_CONTROLLER = 1;
+            public static final int MSG_ON_PRINTERS_ADDED = 2;
+            public static final int MSG_ON_PRINTERS_REMOVED = 3;
+            public static final int MSG_ON_PRINTERS_UPDATED = 4;
+
+            public SessionHandler(Looper looper) {
+                super(looper, null, false);
+            }
+
+            @Override
+            @SuppressWarnings("unchecked")
+            public void handleMessage(Message message) {
+                switch (message.what) {
+                    case MSG_SET_CONTROLLER: {
+                        mController = (IPrinterDiscoverySessionController) message.obj;
+                        try {
+                            mController.open(mPriorityList);
+                        } catch (RemoteException e) {
+                            Log.e(LOG_TAG, "Error starting printer discovery");
+                        }
+                    } break;
+
+                    case MSG_ON_PRINTERS_ADDED: {
+                        List<PrinterInfo> printers = (List<PrinterInfo>) message.obj;
+                        addPrinters(printers);
+                    } break;
+
+                    case MSG_ON_PRINTERS_REMOVED: {
+                        List<PrinterId> printers = (List<PrinterId>) message.obj;
+                        removePrinters(printers);
+                    } break;
+
+                    case MSG_ON_PRINTERS_UPDATED: {
+                        List<PrinterInfo> printers = (List<PrinterInfo>) message.obj;
+                        updatePrinters(printers);
+                    } break;
+                };
+            }
+        }
+    }
+
+    private static final class PrinterDiscoverySessionObserver
+            extends IPrinterDiscoverySessionObserver.Stub {
+
+        private final WeakReference<PrinterDiscoverySession> mWeakSession;
+
+        public PrinterDiscoverySessionObserver(PrinterDiscoverySession session) {
+            mWeakSession = new WeakReference<PrinterDiscoverySession>(session);
+        }
+
+        @Override
+        public void setController(IPrinterDiscoverySessionController controller) {
+            PrinterDiscoverySession sesison = mWeakSession.get();
+            if (sesison != null) {
+                sesison.mHandler.obtainMessage(
+                        PrinterDiscoverySession.SessionHandler.MSG_SET_CONTROLLER,
+                        controller).sendToTarget();
+            }
+        }
+
+        @Override
+        public void onPrintersAdded(List<PrinterInfo> printers) {
+            PrinterDiscoverySession sesison = mWeakSession.get();
+            if (sesison != null) {
+                sesison.mHandler.obtainMessage(
+                        PrinterDiscoverySession.SessionHandler.MSG_ON_PRINTERS_ADDED,
+                        printers).sendToTarget();
+            }
+        }
+
+        @Override
+        public void onPrintersRemoved(List<PrinterId> printers) {
+            PrinterDiscoverySession session = mWeakSession.get();
+            if (session != null) {
+                session.mHandler.obtainMessage(
+                        PrinterDiscoverySession.SessionHandler.MSG_ON_PRINTERS_REMOVED,
+                        printers).sendToTarget();
+            }
+        }
+
+        @Override
+        public void onPrintersUpdated(List<PrinterInfo> printers) {
+            PrinterDiscoverySession session = mWeakSession.get();
+            if (session != null) {
+                session.mHandler.obtainMessage(
+                        PrinterDiscoverySession.SessionHandler.MSG_ON_PRINTERS_UPDATED,
+                        printers).sendToTarget();
+            }
+        }
+    };
+}
diff --git a/packages/PrintSpooler/src/com/android/printspooler/ChoosePrinterActivity.java b/packages/PrintSpooler/src/com/android/printspooler/ChoosePrinterActivity.java
new file mode 100644
index 0000000..8b0dd66a
--- /dev/null
+++ b/packages/PrintSpooler/src/com/android/printspooler/ChoosePrinterActivity.java
@@ -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 com.android.printspooler;
+
+import android.app.Activity;
+import android.os.Bundle;
+
+public class ChoosePrinterActivity extends Activity {
+
+    @Override
+    public void onCreate(Bundle bundle) {
+        setContentView(R.layout.choose_printer_activity);
+    }
+}
diff --git a/packages/PrintSpooler/src/com/android/printspooler/DataLoader.java b/packages/PrintSpooler/src/com/android/printspooler/DataLoader.java
new file mode 100644
index 0000000..82cc2e1
--- /dev/null
+++ b/packages/PrintSpooler/src/com/android/printspooler/DataLoader.java
@@ -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 com.android.printspooler;
+
+/**
+ * This is the contract for a class that know how to load data.
+ */
+public interface DataLoader {
+
+    /**
+     * Requests to start loading data.
+     */
+    public void startLoadData();
+
+    /**
+     * Requests to stop loading data.
+     */
+    public void stopLoadData();
+}
diff --git a/packages/PrintSpooler/src/com/android/printspooler/DataProvider.java b/packages/PrintSpooler/src/com/android/printspooler/DataProvider.java
new file mode 100644
index 0000000..7b10903
--- /dev/null
+++ b/packages/PrintSpooler/src/com/android/printspooler/DataProvider.java
@@ -0,0 +1,50 @@
+/*
+ * 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.printspooler;
+
+import android.database.DataSetObservable;
+
+/**
+ * This is the simple contract for data providers.
+ *
+ * @param <T> The type of the providers data.
+ */
+public abstract class DataProvider<T> extends DataSetObservable {
+
+    /**
+     * Gets the number of items.
+     *
+     * @return The item count.
+     */
+    public abstract int getItemCount();
+
+    /**
+     * Gets the index of an item.
+     *
+     * @param item The item.
+     * @return The item index.
+     */
+    public abstract int getItemIndex(T item);
+
+    /**
+     * Gets an item at a given position.
+     *
+     * @param index The position.
+     * @return The item.
+     */
+    public abstract T getItemAt(int index);
+}
diff --git a/packages/PrintSpooler/src/com/android/printspooler/FavoritePrinterProvider.java b/packages/PrintSpooler/src/com/android/printspooler/FavoritePrinterProvider.java
new file mode 100644
index 0000000..2c539d1
--- /dev/null
+++ b/packages/PrintSpooler/src/com/android/printspooler/FavoritePrinterProvider.java
@@ -0,0 +1,364 @@
+/*
+ * 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.printspooler;
+
+import android.content.ComponentName;
+import android.content.Context;
+import android.os.AsyncTask;
+import android.os.Build;
+import android.print.PrinterId;
+import android.print.PrinterInfo;
+import android.util.ArrayMap;
+import android.util.AtomicFile;
+import android.util.Log;
+import android.util.Slog;
+import android.util.Xml;
+
+import com.android.internal.util.FastXmlSerializer;
+
+import libcore.io.IoUtils;
+
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+import org.xmlpull.v1.XmlSerializer;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * This class provides the favorite printers based on past usage.
+ */
+final class FavoritePrinterProvider extends DataProvider<PrinterInfo> implements DataLoader {
+
+    private static final String LOG_TAG = "FavoritePrinterProvider";
+
+    private static final boolean DEBUG = true && Build.IS_DEBUGGABLE;
+
+    private static final int MAX_HISTORY_LENGTH = 50;
+
+    private static final double WEIGHT_DECAY_COEFFICIENT = 0.95f;
+
+    private final List<PrinterRecord> mHistoricalPrinters = new ArrayList<PrinterRecord>();
+
+    private final List<PrinterRecord> mFavoritePrinters = new ArrayList<PrinterRecord>();
+
+    private final PersistenceManager mPersistenceManager;
+
+    public FavoritePrinterProvider(Context context) {
+        mPersistenceManager = new PersistenceManager(context);
+    }
+
+    public void addPrinter(PrinterInfo printer) {
+        addPrinterInternal(printer);
+        computeFavoritePrinters();
+        mPersistenceManager.writeState();
+    }
+
+    @Override
+    public int getItemCount() {
+        return mFavoritePrinters.size();
+    }
+
+    @Override
+    public PrinterInfo getItemAt(int index) {
+        return mFavoritePrinters.get(index).printer;
+    }
+
+    @Override
+    public int getItemIndex(PrinterInfo printer) {
+        return mFavoritePrinters.indexOf(printer);
+    }
+
+    @Override
+    public void startLoadData() {
+        mPersistenceManager.readStateLocked();
+        computeFavoritePrinters();
+    }
+
+    @Override
+    public void stopLoadData() {
+        /* do nothing */
+    }
+
+    private void addPrinterInternal(PrinterInfo printer) {
+        if (mHistoricalPrinters.size() >= MAX_HISTORY_LENGTH) {
+            mHistoricalPrinters.remove(0);
+        }
+        mHistoricalPrinters.add(new PrinterRecord(printer));
+    }
+
+    private void computeFavoritePrinters() {
+        Map<PrinterId, PrinterRecord> recordMap =
+                new ArrayMap<PrinterId, PrinterRecord>();
+
+        // Recompute the weights.
+        float currentWeight = 1.0f;
+        final int printerCount = mHistoricalPrinters.size();
+        for (int i = printerCount - 1; i >= 0; i--) {
+            PrinterRecord record = mHistoricalPrinters.get(i);
+            record.weight = currentWeight;
+            // Aggregate weight for the same printer
+            PrinterRecord oldRecord = recordMap.put(record.printer.getId(), record);
+            if (oldRecord != null) {
+                record.weight += oldRecord.weight;
+            }
+            currentWeight *= WEIGHT_DECAY_COEFFICIENT;
+        }
+
+        // Copy the unique printer records with computed weights.
+        mFavoritePrinters.addAll(recordMap.values());
+
+        // Soft the favorite printers.
+        Collections.sort(mFavoritePrinters);
+    }
+
+    private final class PrinterRecord implements Comparable<PrinterRecord> {
+        public final PrinterInfo printer;
+        public float weight;
+
+        public PrinterRecord(PrinterInfo printer) {
+            this.printer = printer;
+        }
+
+        @Override
+        public int compareTo(PrinterRecord another) {
+            return Float.floatToIntBits(another.weight) - Float.floatToIntBits(weight);
+        }
+    }
+
+    private final class PersistenceManager {
+        private static final String PERSIST_FILE_NAME = "printer_history.xml";
+
+        private static final String TAG_PRINTERS = "printers";
+
+        private static final String TAG_PRINTER = "printer";
+        private static final String TAG_PRINTER_ID = "printerId";
+
+        private static final String ATTR_LOCAL_ID = "localId";
+        private static final String ATTR_SERVICE_NAME = "serviceName";
+
+        private static final String ATTR_NAME = "name";
+        private static final String ATTR_DESCRIPTION = "description";
+        private static final String ATTR_STATUS = "status";
+
+        private final AtomicFile mStatePersistFile;
+
+        private PersistenceManager(Context context) {
+            mStatePersistFile = new AtomicFile(new File(context.getFilesDir(),
+                    PERSIST_FILE_NAME));
+        }
+
+        @SuppressWarnings("unchecked")
+        public void writeState() {
+
+            new AsyncTask<List<PrinterRecord>, Void, Void>() {
+                @Override
+                protected Void doInBackground(List<PrinterRecord>... printers) {
+                    doWriteState(printers[0]);
+                    return null;
+                }
+
+                @Override
+                protected void onPostExecute(Void result) {
+                    notifyChanged();
+                }
+
+            }.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR,
+                    new ArrayList<PrinterRecord>(mHistoricalPrinters));
+        }
+
+        private void doWriteState(List<PrinterRecord> printers) {
+            FileOutputStream out = null;
+            try {
+                out = mStatePersistFile.startWrite();
+
+                XmlSerializer serializer = new FastXmlSerializer();
+                serializer.setOutput(out, "utf-8");
+                serializer.startDocument(null, true);
+                serializer.startTag(null, TAG_PRINTERS);
+
+                final int printerCount = printers.size();
+                for (int i = printerCount - 1; i >= 0; i--) {
+                    PrinterInfo printer = printers.get(i).printer;
+
+                    serializer.startTag(null, TAG_PRINTER);
+
+                    serializer.attribute(null, ATTR_NAME, printer.getName());
+                    serializer.attribute(null, ATTR_STATUS, String.valueOf(printer.getStatus()));
+                    String description = printer.getDescription();
+                    if (description != null) {
+                        serializer.attribute(null, ATTR_DESCRIPTION, description);
+                    }
+
+                    PrinterId printerId = printer.getId();
+                    serializer.startTag(null, TAG_PRINTER_ID);
+                    serializer.attribute(null, ATTR_LOCAL_ID, printerId.getLocalId());
+                    serializer.attribute(null, ATTR_SERVICE_NAME, printerId.getServiceName()
+                            .flattenToString());
+                    serializer.endTag(null, TAG_PRINTER_ID);
+
+                    serializer.endTag(null, TAG_PRINTER);
+
+                    if (DEBUG) {
+                        Log.i(LOG_TAG, "[PERSISTED] " + printer);
+                    }
+                }
+
+                serializer.endTag(null, TAG_PRINTERS);
+                serializer.endDocument();
+                mStatePersistFile.finishWrite(out);
+
+                if (DEBUG) {
+                    Log.i(LOG_TAG, "[PERSIST END]");
+                }
+            } catch (IOException ioe) {
+                Slog.w(LOG_TAG, "Failed to write printer history, restoring backup.", ioe);
+                mStatePersistFile.failWrite(out);
+            } finally {
+                IoUtils.closeQuietly(out);
+            }
+        }
+
+        public void readStateLocked() {
+            FileInputStream in = null;
+            try {
+                in = mStatePersistFile.openRead();
+            } catch (FileNotFoundException e) {
+                Log.i(LOG_TAG, "No existing printer history.");
+                return;
+            }
+            try {
+                XmlPullParser parser = Xml.newPullParser();
+                parser.setInput(in, null);
+                parseState(parser);
+            } catch (IllegalStateException ise) {
+                Slog.w(LOG_TAG, "Failed parsing ", ise);
+            } catch (NullPointerException npe) {
+                Slog.w(LOG_TAG, "Failed parsing ", npe);
+            } catch (NumberFormatException nfe) {
+                Slog.w(LOG_TAG, "Failed parsing ", nfe);
+            } catch (XmlPullParserException xppe) {
+                Slog.w(LOG_TAG, "Failed parsing ", xppe);
+            } catch (IOException ioe) {
+                Slog.w(LOG_TAG, "Failed parsing ", ioe);
+            } catch (IndexOutOfBoundsException iobe) {
+                Slog.w(LOG_TAG, "Failed parsing ", iobe);
+            } finally {
+                IoUtils.closeQuietly(in);
+            }
+            notifyChanged();
+        }
+
+        private void parseState(XmlPullParser parser)
+                throws IOException, XmlPullParserException {
+            parser.next();
+            skipEmptyTextTags(parser);
+            expect(parser, XmlPullParser.START_TAG, TAG_PRINTERS);
+            parser.next();
+
+            while (parsePrinter(parser)) {
+                parser.next();
+            }
+
+            skipEmptyTextTags(parser);
+            expect(parser, XmlPullParser.END_TAG, TAG_PRINTERS);
+
+            // We were reading the new records first and appended them first,
+            // hence the historical list is in a reversed order, so fix that.
+            Collections.reverse(mHistoricalPrinters);
+        }
+
+        private boolean parsePrinter(XmlPullParser parser)
+                throws IOException, XmlPullParserException {
+            skipEmptyTextTags(parser);
+            if (!accept(parser, XmlPullParser.START_TAG, TAG_PRINTER)) {
+                return false;
+            }
+
+            String name = parser.getAttributeValue(null, ATTR_NAME);
+            String description = parser.getAttributeValue(null, ATTR_DESCRIPTION);
+            final int status = Integer.parseInt(parser.getAttributeValue(null, ATTR_STATUS));
+
+            parser.next();
+
+            skipEmptyTextTags(parser);
+            expect(parser, XmlPullParser.START_TAG, TAG_PRINTER_ID);
+            String localId = parser.getAttributeValue(null, ATTR_LOCAL_ID);
+            ComponentName service = ComponentName.unflattenFromString(parser.getAttributeValue(
+                    null, ATTR_SERVICE_NAME));
+            PrinterId printerId =  new PrinterId(service, localId);
+            parser.next();
+            skipEmptyTextTags(parser);
+            expect(parser, XmlPullParser.END_TAG, TAG_PRINTER_ID);
+            parser.next();
+
+            PrinterInfo.Builder builder = new PrinterInfo.Builder(printerId, name, status);
+            builder.setDescription(description);
+            PrinterInfo printer = builder.create();
+
+            addPrinterInternal(printer);
+
+            if (DEBUG) {
+                Log.i(LOG_TAG, "[RESTORED] " + printer);
+            }
+
+            skipEmptyTextTags(parser);
+            expect(parser, XmlPullParser.END_TAG, TAG_PRINTER);
+
+            return true;
+        }
+
+        private void expect(XmlPullParser parser, int type, String tag)
+                throws IOException, XmlPullParserException {
+            if (!accept(parser, type, tag)) {
+                throw new XmlPullParserException("Exepected event: " + type
+                        + " and tag: " + tag + " but got event: " + parser.getEventType()
+                        + " and tag:" + parser.getName());
+            }
+        }
+
+        private void skipEmptyTextTags(XmlPullParser parser)
+                throws IOException, XmlPullParserException {
+            while (accept(parser, XmlPullParser.TEXT, null)
+                    && "\n".equals(parser.getText())) {
+                parser.next();
+            }
+        }
+
+        private boolean accept(XmlPullParser parser, int type, String tag)
+                throws IOException, XmlPullParserException {
+            if (parser.getEventType() != type) {
+                return false;
+            }
+            if (tag != null) {
+                if (!tag.equals(parser.getName())) {
+                    return false;
+                }
+            } else if (parser.getName() != null) {
+                return false;
+            }
+            return true;
+        }
+    }
+}
diff --git a/packages/PrintSpooler/src/com/android/printspooler/PrintJobConfigActivity.java b/packages/PrintSpooler/src/com/android/printspooler/PrintJobConfigActivity.java
index 9160b7d..f8e9f43 100644
--- a/packages/PrintSpooler/src/com/android/printspooler/PrintJobConfigActivity.java
+++ b/packages/PrintSpooler/src/com/android/printspooler/PrintJobConfigActivity.java
@@ -22,6 +22,7 @@
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.PackageManager.NameNotFoundException;
+import android.database.DataSetObserver;
 import android.graphics.Rect;
 import android.graphics.drawable.Drawable;
 import android.os.Build;
@@ -34,8 +35,6 @@
 import android.os.RemoteException;
 import android.print.ILayoutResultCallback;
 import android.print.IPrintDocumentAdapter;
-import android.print.IPrinterDiscoverySessionController;
-import android.print.IPrinterDiscoverySessionObserver;
 import android.print.IWriteResultCallback;
 import android.print.PageRange;
 import android.print.PrintAttributes;
@@ -64,6 +63,7 @@
 import android.widget.AdapterView;
 import android.widget.AdapterView.OnItemSelectedListener;
 import android.widget.ArrayAdapter;
+import android.widget.BaseAdapter;
 import android.widget.Button;
 import android.widget.EditText;
 import android.widget.Spinner;
@@ -72,7 +72,6 @@
 import java.lang.ref.WeakReference;
 import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.Collections;
 import java.util.Comparator;
 import java.util.List;
 import java.util.concurrent.atomic.AtomicInteger;
@@ -132,11 +131,13 @@
         }
     };
 
-    private PrintSpooler mSpooler;
     private Editor mEditor;
     private Document mDocument;
     private PrintController mController;
-    private PrinterDiscoverySessionObserver mPrinterDiscoverySessionObserver;
+
+    private AvailablePrinterProvider mAvailablePrinters;
+
+    private FavoritePrinterProvider mFavoritePrinters;
 
     private int mPrintJobId;
 
@@ -168,12 +169,15 @@
             mCurrPrintAttributes.copyFrom(attributes);
         }
 
-        mSpooler = PrintSpooler.peekInstance();
+        // TODO: Use history
+        mAvailablePrinters = new AvailablePrinterProvider(this, null);
+        mFavoritePrinters = new FavoritePrinterProvider(this);
+
         mEditor = new Editor();
         mDocument = new Document();
         mController = new PrintController(new RemotePrintDocumentAdapter(
                 IPrintDocumentAdapter.Stub.asInterface(mIPrintDocumentAdapter),
-                mSpooler.generateFileForPrintJob(mPrintJobId)));
+                PrintSpooler.peekInstance().generateFileForPrintJob(mPrintJobId)));
 
         try {
             mIPrintDocumentAdapter.linkToDeath(mDeathRecipient, 0);
@@ -184,9 +188,26 @@
 
         mController.initialize();
         mEditor.initialize();
-        mPrinterDiscoverySessionObserver = new PrinterDiscoverySessionObserver(mEditor,
-                getMainLooper());
-        mSpooler.createPrinterDiscoverySession(mPrinterDiscoverySessionObserver);
+    }
+
+    @Override
+    protected void onResume() {
+        super.onResume();
+        // TODO: Polish this
+        if (!mEditor.isPrintConfirmed()) {
+            mAvailablePrinters.startLoadData();
+            mFavoritePrinters.startLoadData();
+        }
+    }
+
+    @Override
+    protected void onPause() {
+        // TODO: Polish this
+        if (!mEditor.isPrintConfirmed()) {
+            mAvailablePrinters.stopLoadData();
+            mFavoritePrinters.stopLoadData();
+        }
+        super.onPause();
     }
 
     @Override
@@ -194,17 +215,14 @@
         // We can safely do the work in here since at this point
         // the system is bound to our (spooler) process which
         // guarantees that this process will not be killed.
-        mPrinterDiscoverySessionObserver.close();
-        mPrinterDiscoverySessionObserver.destroy();
-        mPrinterDiscoverySessionObserver = null;
         if (mController.hasStarted()) {
             mController.finish();
         }
         if (mEditor.isPrintConfirmed() && mController.isFinished()) {
-            mSpooler.setPrintJobState(mPrintJobId,
+            PrintSpooler.peekInstance().setPrintJobState(mPrintJobId,
                     PrintJobInfo.STATE_QUEUED, null);
         } else {
-            mSpooler.setPrintJobState(mPrintJobId,
+            PrintSpooler.peekInstance().setPrintJobState(mPrintJobId,
                     PrintJobInfo.STATE_CANCELED, null);
         }
         mIPrintDocumentAdapter.unlinkToDeath(mDeathRecipient, 0);
@@ -320,7 +338,8 @@
                 // completed and nothing changed, so we handle writing as usual.
                 handleOnLayoutFinished(mDocument.info, false, mRequestCounter.get());
             } else {
-                mSpooler.setPrintJobAttributesNoPersistence(mPrintJobId, mCurrPrintAttributes);
+                PrintSpooler.peekInstance().setPrintJobAttributesNoPersistence(mPrintJobId,
+                        mCurrPrintAttributes);
 
                 mMetadata.putBoolean(PrintDocumentAdapter.METADATA_KEY_PRINT_PREVIEW,
                         !mEditor.isPrintConfirmed());
@@ -353,15 +372,14 @@
             }
 
             mControllerState = CONTROLLER_STATE_LAYOUT_COMPLETED;
+            mEditor.updateUi();
 
-            // If the info changed, we update the document and the print job,
-            // and update the UI since the the page range selection may have
-            // become invalid.
+            // If the info changed, we update the document and the print job.
             final boolean infoChanged = !info.equals(mDocument.info);
             if (infoChanged) {
                 mDocument.info = info;
-                mSpooler.setPrintJobPrintDocumentInfoNoPersistence(mPrintJobId, info);
-                mEditor.updateUi();
+                PrintSpooler.peekInstance().setPrintJobPrintDocumentInfoNoPersistence(
+                        mPrintJobId, info);
             }
 
             // If the document info or the layout changed, then
@@ -447,11 +465,13 @@
             if (Arrays.equals(mDocument.pages, mRequestedPages)) {
                 // We got a document with exactly the pages we wanted. Hence,
                 // the printer has to print all pages in the data.
-                mSpooler.setPrintJobPagesNoPersistence(mPrintJobId, ALL_PAGES_ARRAY);
+                PrintSpooler.peekInstance().setPrintJobPagesNoPersistence(mPrintJobId,
+                        ALL_PAGES_ARRAY);
             } else if (Arrays.equals(mDocument.pages, ALL_PAGES_ARRAY)) {
                 // We requested specific pages but got all of them. Hence,
                 // the printer has to print only the requested pages.
-                mSpooler.setPrintJobPagesNoPersistence(mPrintJobId, mRequestedPages);
+                PrintSpooler.peekInstance().setPrintJobPagesNoPersistence(mPrintJobId,
+                        mRequestedPages);
             } else if (PageRangeUtils.contains(mDocument.pages, mRequestedPages)) {
                 // We requested specific pages and got more but not all pages.
                 // Hence, we have to offset appropriately the printed pages to
@@ -460,14 +480,16 @@
                 final int offset = mDocument.pages[0].getStart() - pages[0].getStart();
                 PageRange[] offsetPages = Arrays.copyOf(mDocument.pages, mDocument.pages.length);
                 PageRangeUtils.offsetStart(offsetPages, offset);
-                mSpooler.setPrintJobPagesNoPersistence(mPrintJobId, offsetPages);
+                PrintSpooler.peekInstance().setPrintJobPagesNoPersistence(mPrintJobId,
+                        offsetPages);
             } else if (Arrays.equals(mRequestedPages, ALL_PAGES_ARRAY)
                     && mDocument.pages.length == 1 && mDocument.pages[0].getStart() == 0
                     && mDocument.pages[0].getEnd() == mDocument.info.getPageCount() - 1) {
                 // We requested all pages via the special constant and got all
                 // of them as an explicit enumeration. Hence, the printer has
                 // to print only the requested pages.
-                mSpooler.setPrintJobPagesNoPersistence(mPrintJobId, mDocument.pages);
+                PrintSpooler.peekInstance().setPrintJobPagesNoPersistence(mPrintJobId,
+                        mDocument.pages);
             } else {
                 // We did not get the pages we requested, then the application
                 // misbehaves, so we fail quickly.
@@ -592,7 +614,7 @@
         private final EditText mRangeEditText;
 
         private final Spinner mDestinationSpinner;
-        private final ArrayAdapter<SpinnerItem<PrinterInfo>> mDestinationSpinnerAdapter;
+        private final DestinationAdapter mDestinationSpinnerAdapter;
 
         private final Spinner mMediaSizeSpinner;
         private final ArrayAdapter<SpinnerItem<MediaSize>> mMediaSizeSpinnerAdapter;
@@ -623,15 +645,18 @@
                         return;
                     }
                     mCurrPrintAttributes.clear();
-                    SpinnerItem<PrinterInfo> dstItem = mDestinationSpinnerAdapter.getItem(position);
-                    if (dstItem != null) {
-                        PrinterInfo printer = dstItem.value;
-                        mSpooler.setPrintJobPrinterNoPersistence(mPrintJobId, printer);
+                    PrinterInfo printer = (PrinterInfo) mDestinationSpinnerAdapter
+                            .getItem(position);
+                    if (printer != null) {
+                        PrintSpooler.peekInstance().setPrintJobPrinterNoPersistence(
+                                mPrintJobId, printer);
                         PrinterCapabilitiesInfo capabilities = printer.getCapabilities();
                         if (capabilities == null) {
                             List<PrinterId> printerIds = new ArrayList<PrinterId>();
                             printerIds.add(printer.getId());
-                            mPrinterDiscoverySessionObserver.requestPrinterUpdate(printer.getId());
+                            final int index = mAvailablePrinters.getItemIndex(printer);
+                            mAvailablePrinters.refreshItem(index);
+                            mWaitingForPrinterCapabilities = true;
                             //TODO: We need a timeout for the update.
                         } else {
                             capabilities.getDefaults(mCurrPrintAttributes);
@@ -728,7 +753,7 @@
                 }
 
                 mCopiesEditText.setError(null);
-                mSpooler.setPrintJobCopiesNoPersistence(mPrintJobId, copies);
+                PrintSpooler.peekInstance().setPrintJobCopiesNoPersistence(mPrintJobId, copies);
                 updateUi();
 
                 if (hadErrors && !hasErrors() && printAttributesChanged()) {
@@ -805,6 +830,8 @@
         private boolean mIgnoreNextCopiesChange;
         private boolean mIgnoreNextRangeChange;
 
+        private boolean mWaitingForPrinterCapabilities;
+
         public Editor() {
             // Content container
             mContentContainer = findViewById(R.id.content_container);
@@ -812,13 +839,40 @@
             // Copies
             mCopiesEditText = (EditText) findViewById(R.id.copies_edittext);
             mCopiesEditText.setText(String.valueOf(MIN_COPIES));
-            mSpooler.setPrintJobCopiesNoPersistence(mPrintJobId, MIN_COPIES);
+            PrintSpooler.peekInstance().setPrintJobCopiesNoPersistence(mPrintJobId, MIN_COPIES);
             mCopiesEditText.addTextChangedListener(mCopiesTextWatcher);
             mCopiesEditText.selectAll();
 
             // Destination.
+            mDestinationSpinnerAdapter = new DestinationAdapter(mAvailablePrinters);
+            mDestinationSpinnerAdapter.registerDataSetObserver(new DataSetObserver() {
+                @Override
+                public void onChanged() {
+                    // Maybe we did not have capabilities when the current printer was
+                    // selected, but now the selected printer has capabilities. Generate
+                    // a fake selection so the code in the selection change handling takes
+                    // care of updating everything. This way the logic is in one place.
+                    if (mWaitingForPrinterCapabilities) {
+                        mWaitingForPrinterCapabilities = false;
+                        PrinterInfo printer = (PrinterInfo) mDestinationSpinner.getSelectedItem();
+                        if (printer != null) {
+                            if (printer.getCapabilities() != null) {
+                                final int selectedPosition =
+                                        mDestinationSpinner.getSelectedItemPosition();
+                                mOnItemSelectedListener.onItemSelected(mDestinationSpinner, null,
+                                        selectedPosition, selectedPosition);
+                            }
+                        }
+                    }
+                    updateUi();
+                }
+
+                @Override
+                public void onInvalidated() {
+                    updateUi();
+                }
+            });
             mDestinationSpinner = (Spinner) findViewById(R.id.destination_spinner);
-            mDestinationSpinnerAdapter = new DestinationAdapter();
             mDestinationSpinner.setAdapter(mDestinationSpinnerAdapter);
             mDestinationSpinner.setOnItemSelectedListener(mOnItemSelectedListener);
 
@@ -877,7 +931,6 @@
                 @Override
                 public void onClick(View v) {
                     mEditor.confirmPrint();
-                    updateUi();
                     mController.update();
                     showGeneratingPrintJobUi();
                 }
@@ -1001,6 +1054,11 @@
 
         public void confirmPrint() {
             mEditorState = EDITOR_STATE_CONFIRMED_PRINT;
+            PrinterInfo printer = (PrinterInfo) mDestinationSpinner.getSelectedItem();
+            if (printer != null) {
+                mFavoritePrinters.addPrinter(printer);
+            }
+            updateUi();
         }
 
         public boolean isPreviewConfirmed() {
@@ -1063,8 +1121,8 @@
 
             final int selectedIndex = mDestinationSpinner.getSelectedItemPosition();
 
-            if (selectedIndex < 0 || mDestinationSpinnerAdapter.getItem(
-                    selectedIndex).value.getCapabilities() == null) {
+            if (selectedIndex < 0 || ((PrinterInfo) mDestinationSpinnerAdapter.getItem(
+                    selectedIndex)).getCapabilities() == null) {
 
                 // Destination
                 mDestinationSpinner.setEnabled(false);
@@ -1121,16 +1179,12 @@
                 mPrintButton.setEnabled(false);
             } else {
                 PrintAttributes defaultAttributes = mTempPrintAttributes;
-                PrinterInfo printer = mDestinationSpinnerAdapter.getItem(selectedIndex).value;
+                PrinterInfo printer = (PrinterInfo) mDestinationSpinner.getSelectedItem();
                 PrinterCapabilitiesInfo capabilities = printer.getCapabilities();
                 printer.getCapabilities().getDefaults(defaultAttributes);
 
                 // Destination
-                if (mDestinationSpinnerAdapter.getCount() > 1) {
-                    mDestinationSpinner.setEnabled(true);
-                } else {
-                    mDestinationSpinner.setEnabled(false);
-                }
+                mDestinationSpinner.setEnabled(true);
 
                 // Copies
                 mCopiesEditText.setEnabled(true);
@@ -1159,9 +1213,6 @@
                     if (mediaSizeCount <= 0) {
                         mMediaSizeSpinner.setEnabled(false);
                         mMediaSizeSpinner.setSelection(AdapterView.INVALID_POSITION);
-                    } else if (mediaSizeCount == 1) {
-                        mMediaSizeSpinner.setEnabled(false);
-                        mMediaSizeSpinner.setSelection(0);
                     } else {
                         mMediaSizeSpinner.setEnabled(true);
                         final int selectedMediaSizeIndex = Math.max(mediaSizes.indexOf(
@@ -1210,9 +1261,6 @@
                     if (colorModeCount <= 0) {
                         mColorModeSpinner.setEnabled(false);
                         mColorModeSpinner.setSelection(AdapterView.INVALID_POSITION);
-                    } else if (colorModeCount == 1) {
-                        mColorModeSpinner.setEnabled(false);
-                        mColorModeSpinner.setSelection(0);
                     } else {
                         mColorModeSpinner.setEnabled(true);
                         final int selectedColorModeIndex = Integer.numberOfTrailingZeros(
@@ -1262,9 +1310,6 @@
                     if (orientationCount <= 0) {
                         mOrientationSpinner.setEnabled(false);
                         mOrientationSpinner.setSelection(AdapterView.INVALID_POSITION);
-                    } else if (orientationCount == 1) {
-                        mOrientationSpinner.setEnabled(false);
-                        mOrientationSpinner.setSelection(0);
                     } else {
                         mOrientationSpinner.setEnabled(true);
                         final int selectedOrientationIndex = Integer.numberOfTrailingZeros(
@@ -1336,99 +1381,6 @@
             }
         }
 
-        public void addPrinters(List<PrinterInfo> addedPrinters) {
-            final int addedPrinterCount = addedPrinters.size();
-            for (int i = 0; i < addedPrinterCount; i++) {
-                PrinterInfo addedPrinter = addedPrinters.get(i);
-                boolean duplicate = false;
-                final int existingPrinterCount = mDestinationSpinnerAdapter.getCount();
-                for (int j = 0; j < existingPrinterCount; j++) {
-                    PrinterInfo existingPrinter = mDestinationSpinnerAdapter.getItem(j).value;
-                    if (addedPrinter.getId().equals(existingPrinter.getId())) {
-                        duplicate = true;
-                        break;
-                    }
-                }
-                if (!duplicate) {
-                    mDestinationSpinnerAdapter.add(new SpinnerItem<PrinterInfo>(
-                            addedPrinter, addedPrinter.getName()));
-                } else {
-                    Log.w(LOG_TAG, "Skipping a duplicate printer: " + addedPrinter);
-                }
-            }
-
-            if (mDestinationSpinner.getSelectedItemPosition() == AdapterView.INVALID_POSITION
-                    && mDestinationSpinnerAdapter.getCount() > 0) {
-                mDestinationSpinner.setSelection(0);
-            }
-
-            mEditor.updateUi();
-        }
-
-        public void removePrinters(List<PrinterId> pritnerIds) {
-            final int printerIdCount = pritnerIds.size();
-            for (int i = 0; i < printerIdCount; i++) {
-                PrinterId removedPrinterId = pritnerIds.get(i);
-                boolean removed = false;
-                final int existingPrinterCount = mDestinationSpinnerAdapter.getCount();
-                for (int j = 0; j < existingPrinterCount; j++) {
-                    PrinterInfo existingPrinter = mDestinationSpinnerAdapter.getItem(j).value;
-                    if (removedPrinterId.equals(existingPrinter.getId())) {
-                        mDestinationSpinnerAdapter.remove(mDestinationSpinnerAdapter.getItem(j));
-                        removed = true;
-                        break;
-                    }
-                }
-                if (!removed) {
-                    Log.w(LOG_TAG, "Ignoring not added printer with id: " + removedPrinterId);
-                }
-            }
-
-            if (mDestinationSpinner.getSelectedItemPosition() != AdapterView.INVALID_POSITION
-                    && mDestinationSpinnerAdapter.getCount() == 0) {
-                mDestinationSpinner.setSelection(AdapterView.INVALID_POSITION);
-            }
-        }
-
-        @SuppressWarnings("unchecked")
-        public void updatePrinters(List<PrinterInfo> pritners) {
-            SpinnerItem<PrinterInfo> selectedItem =
-                    (SpinnerItem<PrinterInfo>) mDestinationSpinner.getSelectedItem();
-            PrinterId selectedPrinterId = (selectedItem != null)
-                    ? selectedItem.value.getId() : null;
-
-            boolean updated = false;
-
-            final int printerCount = pritners.size();
-            for (int i = 0; i < printerCount; i++) {
-                PrinterInfo updatedPrinter = pritners.get(i);
-                final int existingPrinterCount = mDestinationSpinnerAdapter.getCount();
-                for (int j = 0; j < existingPrinterCount; j++) {
-                    PrinterInfo existingPrinter = mDestinationSpinnerAdapter.getItem(j).value;
-                    if (updatedPrinter.getId().equals(existingPrinter.getId())) {
-                        existingPrinter.copyFrom(updatedPrinter);
-                        updated = true;
-                        if (selectedPrinterId != null
-                                && selectedPrinterId.equals(updatedPrinter.getId())) {
-                            // The selected printer was updated. We simulate a fake
-                            // selection to reuse the normal printer change handling.
-                            mOnItemSelectedListener.onItemSelected(mDestinationSpinner,
-                                    mDestinationSpinner.getSelectedView(),
-                                    mDestinationSpinner.getSelectedItemPosition(),
-                                    mDestinationSpinner.getSelectedItemId());
-                            // TODO: This will reset the UI to the defaults for the
-                            // printer. We may need to revisit this.
-                            
-                        }
-                        break;
-                    }
-                }
-            }
-            if (updated) {
-                mDestinationSpinnerAdapter.notifyDataSetChanged();
-            }
-        }
-
         private boolean hasErrors() {
             return mRangeEditText.getError() != null
                     || mCopiesEditText.getError() != null;
@@ -1455,10 +1407,39 @@
             }
         }
 
-        private final class DestinationAdapter extends ArrayAdapter<SpinnerItem<PrinterInfo>> {
+        private final class DestinationAdapter extends BaseAdapter {
+            private final AvailablePrinterProvider mProvider;
 
-            public DestinationAdapter() {
-                super( PrintJobConfigActivity.this, R.layout.spinner_dropdown_item);
+            private final DataSetObserver mObserver = new DataSetObserver() {
+                @Override
+                public void onChanged() {
+                    notifyDataSetChanged();
+                }
+
+                @Override
+                public void onInvalidated() {
+                    notifyDataSetInvalidated();
+                }
+            };
+
+            public DestinationAdapter(AvailablePrinterProvider provider) {
+                mProvider = provider;
+                mProvider.registerObserver(mObserver);
+            }
+
+            @Override
+            public int getCount() {
+                return mProvider.getItemCount();
+            }
+
+            @Override
+            public Object getItem(int position) {
+                return mProvider.getItemAt(position);
+            }
+
+            @Override
+            public long getItemId(int position) {
+                return position;
             }
 
             @Override
@@ -1474,7 +1455,7 @@
                             R.layout.spinner_dropdown_item, parent, false);
                 }
 
-                PrinterInfo printerInfo = getItem(position).value;
+                PrinterInfo printerInfo = mProvider.getItemAt(position);
                 TextView title = (TextView) convertView.findViewById(R.id.title);
                 title.setText(printerInfo.getName());
 
@@ -1495,132 +1476,6 @@
         }
     }
 
-    private static final class PrinterDiscoverySessionObserver
-            extends IPrinterDiscoverySessionObserver.Stub {
-        private static final int MSG_SET_CONTROLLER = 1;
-        private static final int MSG_ON_PRINTERS_ADDED = 2;
-        private static final int MSG_ON_PRINTERS_REMOVED = 3;
-        private static final int MSG_ON_PRINTERS_UPDATED = 4;
-
-        private Handler mHandler;
-        private Editor mEditor;
-        private IPrinterDiscoverySessionController mController;
-
-        @SuppressWarnings("unchecked")
-        public PrinterDiscoverySessionObserver(Editor editor, Looper looper) {
-            mEditor = editor;
-            mHandler = new Handler(looper, null, true) {
-                @Override
-                public void handleMessage(Message message) {
-                    switch (message.what) {
-                        case MSG_SET_CONTROLLER: {
-                            mController = (IPrinterDiscoverySessionController) message.obj;
-                            // TODO: This should be cleaned up
-                            List<PrinterId> printerIds = Collections.emptyList();
-                            try {
-                                mController.open(printerIds);
-                            } catch (RemoteException e) {
-                                Log.e(LOG_TAG, "Error starting printer discovery");
-                            }
-                        } break;
-
-                        case MSG_ON_PRINTERS_ADDED: {
-                            List<PrinterInfo> printers = (List<PrinterInfo>) message.obj;
-                            mEditor.addPrinters(printers);
-                        } break;
-
-                        case MSG_ON_PRINTERS_REMOVED: {
-                            List<PrinterId> printerIds = (List<PrinterId>) message.obj;
-                            mEditor.removePrinters(printerIds);
-                        } break;
-
-                        case MSG_ON_PRINTERS_UPDATED: {
-                            List<PrinterInfo> printers = (List<PrinterInfo>) message.obj;
-                            mEditor.updatePrinters(printers);
-                        } break;
-                    }
-                }
-            };
-        }
-
-        public void open(List<PrinterId> priorityList) {
-            if (mController != null) {
-                try {
-                    mController.open(priorityList);
-                } catch (RemoteException re) {
-                    Log.e(LOG_TAG, "Error closing printer discovery session", re);
-                }
-            }
-        }
-
-        public void close() {
-            if (mController != null) {
-                try {
-                    mController.close();
-                } catch (RemoteException re) {
-                    Log.e(LOG_TAG, "Error closing printer discovery session", re);
-                }
-            }
-        }
-
-        public void requestPrinterUpdate(PrinterId printerId) {
-            if (mController != null) {
-                try {
-                    mController.requestPrinterUpdate(printerId);
-                } catch (RemoteException re) {
-                    Log.e(LOG_TAG, "Error requestin printer update", re);
-                }
-            }
-        }
-
-        @Override
-        public void setController(IPrinterDiscoverySessionController controller) {
-            synchronized (this) {
-                if (mHandler != null) {
-                    mHandler.obtainMessage(MSG_SET_CONTROLLER, controller)
-                        .sendToTarget();
-                }
-            }
-        }
-
-        @Override
-        public void onPrintersAdded(List<PrinterInfo> printers) {
-            synchronized (this) {
-                if (mHandler != null) {
-                    mHandler.obtainMessage(MSG_ON_PRINTERS_ADDED, printers)
-                        .sendToTarget();
-                }
-            }
-        }
-
-        @Override
-        public void onPrintersRemoved(List<PrinterId> printers) {
-            synchronized (this) {
-                if (mHandler != null) {
-                    mHandler.obtainMessage(MSG_ON_PRINTERS_REMOVED, printers)
-                        .sendToTarget();
-                }
-            }
-        }
-
-        @Override
-        public void onPrintersUpdated(List<PrinterInfo> printers) {
-            synchronized (this) {
-                if (mHandler != null) {
-                    mHandler.obtainMessage(MSG_ON_PRINTERS_UPDATED, printers)
-                        .sendToTarget();
-                }
-            }
-        }
-
-        public void destroy() {
-            synchronized (this) {
-                mHandler = null;
-                mEditor = null;
-            }
-        }
-    }
-
     /**
      * An instance of this class class is intended to be the first focusable
      * in a layout to which the system automatically gives focus. It performs
diff --git a/packages/PrintSpooler/src/com/android/printspooler/PrintSpooler.java b/packages/PrintSpooler/src/com/android/printspooler/PrintSpooler.java
index 1b8b81a..c2cf65e 100644
--- a/packages/PrintSpooler/src/com/android/printspooler/PrintSpooler.java
+++ b/packages/PrintSpooler/src/com/android/printspooler/PrintSpooler.java
@@ -477,7 +477,7 @@
         private static final String ATTR_FITTING_MODE = "fittingMode";
         private static final String ATTR_ORIENTATION = "orientation";
 
-        private static final String ATTR_PRINTER_NAME = "printerName";
+        private static final String ATTR_LOCAL_ID = "printerName";
         private static final String ATTR_SERVICE_NAME = "serviceName";
 
         private static final String ATTR_WIDTH_MILS = "widthMils";
@@ -568,7 +568,7 @@
                     PrinterId printerId = printJob.getPrinterId();
                     if (printerId != null) {
                         serializer.startTag(null, TAG_PRINTER_ID);
-                        serializer.attribute(null, ATTR_PRINTER_NAME, printerId.getLocalId());
+                        serializer.attribute(null, ATTR_LOCAL_ID, printerId.getLocalId());
                         serializer.attribute(null, ATTR_SERVICE_NAME, printerId.getServiceName()
                                 .flattenToString());
                         serializer.endTag(null, TAG_PRINTER_ID);
@@ -695,13 +695,7 @@
                 Slog.w(LOG_TAG, "Failed to write state, restoring backup.", e);
                 mStatePersistFile.failWrite(out);
             } finally {
-                if (out != null) {
-                    try {
-                        out.close();
-                    } catch (IOException ioe) {
-                        /* ignore */
-                    }
-                }
+                IoUtils.closeQuietly(out);
             }
         }
 
@@ -733,11 +727,7 @@
             } catch (IndexOutOfBoundsException iobe) {
                 Slog.w(LOG_TAG, "Failed parsing ", iobe);
             } finally {
-                try {
-                    in.close();
-                } catch (IOException ioe) {
-                    /* ignore */
-                }
+                IoUtils.closeQuietly(in);
             }
         }
 
@@ -784,7 +774,7 @@
 
             skipEmptyTextTags(parser);
             if (accept(parser, XmlPullParser.START_TAG, TAG_PRINTER_ID)) {
-                String localId = parser.getAttributeValue(null, ATTR_PRINTER_NAME);
+                String localId = parser.getAttributeValue(null, ATTR_LOCAL_ID);
                 ComponentName service = ComponentName.unflattenFromString(parser.getAttributeValue(
                         null, ATTR_SERVICE_NAME));
                 printJob.setPrinterId(new PrinterId(service, localId));
diff --git a/packages/SystemUI/ic_sysbar_internal.psd b/packages/SystemUI/ic_sysbar_internal.psd
deleted file mode 100644
index 929c872..0000000
--- a/packages/SystemUI/ic_sysbar_internal.psd
+++ /dev/null
Binary files differ
diff --git a/packages/SystemUI/res/drawable-nodpi/lightning.png b/packages/SystemUI/res/drawable-nodpi/lightning.png
new file mode 100644
index 0000000..29de308
--- /dev/null
+++ b/packages/SystemUI/res/drawable-nodpi/lightning.png
Binary files differ
diff --git a/packages/SystemUI/res/layout/quick_settings_tile_battery.xml b/packages/SystemUI/res/layout/quick_settings_tile_battery.xml
index c41e9b9..f3b894c 100644
--- a/packages/SystemUI/res/layout/quick_settings_tile_battery.xml
+++ b/packages/SystemUI/res/layout/quick_settings_tile_battery.xml
@@ -19,14 +19,14 @@
         android:layout_height="match_parent"
         android:layout_gravity="top"
         android:orientation="vertical">
-    <ImageView
+    <com.android.systemui.BatteryMeterView
             android:id="@+id/image"
             android:layout_marginTop="@dimen/qs_tile_margin_above_icon"
             android:layout_marginBottom="@dimen/qs_tile_margin_below_icon"
-            android:layout_width="@dimen/qs_tile_icon_size"
-            android:layout_height="@dimen/qs_tile_icon_size"
+            android:layout_width="22dp"
+            android:layout_height="32dp"
+            android:padding="3dp"
             android:layout_gravity="top|center_horizontal"
-            android:scaleType="centerInside"
             />
     <TextView
             style="@style/TextAppearance.QuickSettings.TileView"
@@ -36,4 +36,4 @@
             android:layout_gravity="top|center_horizontal"
             android:gravity="top|center_horizontal"
             />
-</LinearLayout>
\ No newline at end of file
+</LinearLayout>
diff --git a/packages/SystemUI/res/layout/signal_cluster_view.xml b/packages/SystemUI/res/layout/signal_cluster_view.xml
index aab5083..66b06ef 100644
--- a/packages/SystemUI/res/layout/signal_cluster_view.xml
+++ b/packages/SystemUI/res/layout/signal_cluster_view.xml
@@ -20,8 +20,9 @@
 
 <com.android.systemui.statusbar.SignalClusterView
     xmlns:android="http://schemas.android.com/apk/res/android"
-    android:layout_height="wrap_content"
+    android:layout_height="match_parent"
     android:layout_width="wrap_content"
+    android:gravity="center"
     android:orientation="horizontal"
     >
     <FrameLayout
diff --git a/packages/SystemUI/res/layout/status_bar.xml b/packages/SystemUI/res/layout/status_bar.xml
index b27536d..4741cec 100644
--- a/packages/SystemUI/res/layout/status_bar.xml
+++ b/packages/SystemUI/res/layout/status_bar.xml
@@ -95,11 +95,13 @@
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
                     />
-                <ImageView
+                <!-- battery must be padded below by 1px to match assets -->
+                <com.android.systemui.BatteryMeterView
                     android:id="@+id/battery"
-                    android:layout_height="wrap_content"
-                    android:layout_width="wrap_content"
-                    android:paddingStart="4dip"
+                    android:layout_height="16dp"
+                    android:layout_width="10dp"
+                    android:paddingBottom="1px"
+                    android:layout_marginStart="4dip"
                     />
             </LinearLayout>
     
diff --git a/packages/SystemUI/res/values/arrays.xml b/packages/SystemUI/res/values/arrays.xml
index cd6aaf6..506722d2 100644
--- a/packages/SystemUI/res/values/arrays.xml
+++ b/packages/SystemUI/res/values/arrays.xml
@@ -40,4 +40,16 @@
         <item>@null</item>
     </array>
 
+    <!-- BatteryMeterView parameters -->
+    <array name="batterymeter_color_levels">
+        <item>4</item>
+        <item>15</item>
+        <item>100</item>
+    </array>
+    <array name="batterymeter_color_values">
+        <item>#FFFF0000</item>
+        <item>#FFFE6600</item>
+        <item>#FF3792B4</item>
+    </array>
+
 </resources>
diff --git a/packages/SystemUI/res/values/colors.xml b/packages/SystemUI/res/values/colors.xml
index 803be6e..04de60f 100644
--- a/packages/SystemUI/res/values/colors.xml
+++ b/packages/SystemUI/res/values/colors.xml
@@ -34,4 +34,6 @@
     <drawable name="heads_up_notification_bg_pressed">#ff33B5E5</drawable>
     <drawable name="notification_header_bg">#FF000000</drawable>
     <color name="notification_panel_scrim_color">#B0000000</color>
+
+    <color name="batterymeter_frame_color">#FF404040</color>
 </resources>
diff --git a/packages/SystemUI/res/values/strings.xml b/packages/SystemUI/res/values/strings.xml
index eec8177..c849aa6 100644
--- a/packages/SystemUI/res/values/strings.xml
+++ b/packages/SystemUI/res/values/strings.xml
@@ -503,4 +503,7 @@
     <string name="status_bar_help_title">Notifications appear here</string>
     <!-- Body of help text shown when the notification panel is pulled down for the very first time. [CHAR LIMIT=NONE] -->
     <string name="status_bar_help_text">Access them anytime by swiping down.\nSwipe down again for system controls.</string>
+
+    <!-- Glyph to be overlaid atop the battery when the level is extremely low. Do not translate. -->
+    <string name="battery_meter_very_low_overlay_symbol">!</string>
 </resources>
diff --git a/packages/SystemUI/src/com/android/systemui/BatteryMeterView.java b/packages/SystemUI/src/com/android/systemui/BatteryMeterView.java
new file mode 100755
index 0000000..aa4362e
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/BatteryMeterView.java
@@ -0,0 +1,302 @@
+/*
+ * 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.systemui;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.res.Resources;
+import android.content.res.TypedArray;
+import android.graphics.Canvas;
+import android.graphics.Paint;
+import android.graphics.Rect;
+import android.graphics.RectF;
+import android.graphics.Typeface;
+import android.graphics.drawable.Drawable;
+import android.os.BatteryManager;
+import android.provider.Settings;
+import android.util.AttributeSet;
+import android.view.View;
+
+public class BatteryMeterView extends View {
+    public static final String TAG = BatteryMeterView.class.getSimpleName();
+    public static final String ACTION_LEVEL_TEST = "com.android.systemui.BATTERY_LEVEL_TEST";
+
+    public static final boolean ENABLE_PERCENT = true;
+    public static final boolean SINGLE_DIGIT_PERCENT = false;
+    public static final boolean SHOW_100_PERCENT = false;
+
+    public static final int FULL = 96;
+    public static final int EMPTY = 4;
+
+    int[] mColors;
+
+    boolean mShowPercent = true;
+    Paint mFramePaint, mBatteryPaint, mWarningTextPaint, mTextPaint;
+    int mButtonHeight;
+    private float mTextHeight, mWarningTextHeight;
+    Drawable mLightning;
+
+    private int mHeight;
+    private int mWidth;
+    private String mWarningString;
+
+    private class BatteryTracker extends BroadcastReceiver {
+        // current battery status
+        int level;
+        String percentStr;
+        int plugType;
+        boolean plugged;
+        int health;
+        int status;
+        String technology;
+        int voltage;
+        int temperature;
+        boolean testmode = false;
+
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            final String action = intent.getAction();
+            if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
+                if (testmode && ! intent.getBooleanExtra("testmode", false)) return;
+
+                level = (int)(100f
+                        * intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0)
+                        / intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100));
+
+                plugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
+                plugged = plugType != 0;
+                health = intent.getIntExtra(BatteryManager.EXTRA_HEALTH,
+                        BatteryManager.BATTERY_HEALTH_UNKNOWN);
+                status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
+                        BatteryManager.BATTERY_STATUS_UNKNOWN);
+                technology = intent.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY);
+                voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0);
+                temperature = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0);
+
+                setContentDescription(
+                        context.getString(R.string.accessibility_battery_level, level));
+                postInvalidate();
+            } else if (action.equals(ACTION_LEVEL_TEST)) {
+                testmode = true;
+                post(new Runnable() {
+                    int curLevel = 0;
+                    int incr = 1;
+                    int saveLevel = level;
+                    int savePlugged = plugType;
+                    Intent dummy = new Intent(Intent.ACTION_BATTERY_CHANGED);
+                    @Override
+                    public void run() {
+                        if (curLevel < 0) {
+                            testmode = false;
+                            dummy.putExtra("level", saveLevel);
+                            dummy.putExtra("plugged", savePlugged);
+                            dummy.putExtra("testmode", false);
+                        } else {
+                            dummy.putExtra("level", curLevel);
+                            dummy.putExtra("plugged", incr > 0 ? BatteryManager.BATTERY_PLUGGED_AC : 0);
+                            dummy.putExtra("testmode", true);
+                        }
+                        getContext().sendBroadcast(dummy);
+
+                        if (!testmode) return;
+
+                        curLevel += incr;
+                        if (curLevel == 100) {
+                            incr *= -1;
+                        }
+                        postDelayed(this, 200);
+                    }
+                });
+            }
+        }
+    }
+
+    BatteryTracker mTracker = new BatteryTracker();
+
+    @Override
+    public void onAttachedToWindow() {
+        super.onAttachedToWindow();
+
+        IntentFilter filter = new IntentFilter();
+        filter.addAction(Intent.ACTION_BATTERY_CHANGED);
+        filter.addAction(ACTION_LEVEL_TEST);
+        getContext().registerReceiver(mTracker, filter);
+    }
+
+    @Override
+    public void onDetachedFromWindow() {
+        super.onDetachedFromWindow();
+
+        getContext().unregisterReceiver(mTracker);
+    }
+
+    public BatteryMeterView(Context context) {
+        this(context, null, 0);
+    }
+
+    public BatteryMeterView(Context context, AttributeSet attrs) {
+        this(context, attrs, 0);
+    }
+
+    public BatteryMeterView(Context context, AttributeSet attrs, int defStyle) {
+        super(context, attrs, defStyle);
+
+        final Resources res = context.getResources();
+        TypedArray levels = res.obtainTypedArray(R.array.batterymeter_color_levels);
+        TypedArray colors = res.obtainTypedArray(R.array.batterymeter_color_values);
+
+        final int N = levels.length();
+        mColors = new int[2*N];
+        for (int i=0; i<N; i++) {
+            mColors[2*i] = levels.getInt(i, 0);
+            mColors[2*i+1] = colors.getColor(i, 0);
+        }
+
+        mShowPercent = ENABLE_PERCENT && 0 != Settings.System.getInt(
+                context.getContentResolver(), "status_bar_show_battery_percent", 0);
+
+        mWarningString = context.getString(R.string.battery_meter_very_low_overlay_symbol);
+
+        mFramePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
+        mFramePaint.setColor(res.getColor(R.color.batterymeter_frame_color));
+        mBatteryPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
+        mBatteryPaint.setColor(0xFF00FF00); // will be replaced by something from mColors
+
+        mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
+        mTextPaint.setColor(0xFFFFFFFF);
+        Typeface font = Typeface.create("sans-serif-condensed", Typeface.NORMAL);
+        mTextPaint.setTypeface(font);
+        mTextPaint.setTextAlign(Paint.Align.CENTER);
+
+        mWarningTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
+        mWarningTextPaint.setColor(mColors[1]);
+        font = Typeface.create("sans-serif", Typeface.BOLD);
+        mWarningTextPaint.setTypeface(font);
+        mWarningTextPaint.setTextAlign(Paint.Align.CENTER);
+
+        mLightning = getResources().getDrawable(R.drawable.lightning);
+    }
+
+    @Override
+    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
+        mHeight = h;
+        mWidth = w;
+        mWarningTextPaint.setTextSize(h * 0.75f);
+        mWarningTextHeight = -mWarningTextPaint.getFontMetrics().ascent;
+    }
+
+    private int getColorForLevel(int percent) {
+        int thresh, color = 0;
+        for (int i=0; i<mColors.length; i+=2) {
+            thresh = mColors[i];
+            color = mColors[i+1];
+            if (percent <= thresh) return color;
+        }
+        return color;
+    }
+
+    @Override
+    public void draw(Canvas c) {
+        final int level = mTracker.level;
+        float drawFrac = (float) level / 100f;
+        final int pt = getPaddingTop();
+        final int pl = getPaddingLeft();
+        final int pr = getPaddingRight();
+        final int pb = getPaddingBottom();
+        int height = mHeight - pt - pb;
+        int width = mWidth - pl - pr;
+
+        mButtonHeight = (int) (height * 0.12f);
+
+        final RectF frame = new RectF(0, 0, width, height);
+        frame.offset(pl, pt);
+
+        // Log.v("BatteryGauge", String.format("canvas: %dx%d frame: %s",
+        // c.getWidth(), c.getHeight(), frame.toString()));
+
+        final RectF buttonframe = new RectF(
+                frame.left + width * 0.25f,
+                frame.top,
+                frame.right - width * 0.25f,
+                frame.top + mButtonHeight);
+
+        frame.top += mButtonHeight;
+
+        // first, draw the battery shape
+        c.drawRect(frame, mFramePaint);
+
+        // fill 'er up
+        final int pct = mTracker.level;
+        final int color = getColorForLevel(pct);
+        mBatteryPaint.setColor(color);
+
+        if (level >= FULL) {
+            drawFrac = 1f;
+        } else if (level <= EMPTY) {
+            drawFrac = 0f;
+        }
+
+        c.drawRect(buttonframe,
+                drawFrac == 1f ? mBatteryPaint : mFramePaint);
+
+        RectF clip = new RectF(frame);
+        clip.top += (frame.height() * (1f - drawFrac));
+
+        c.save(Canvas.CLIP_SAVE_FLAG);
+        c.clipRect(clip);
+        c.drawRect(frame, mBatteryPaint);
+        c.restore();
+
+        if (level <= EMPTY) {
+            final float x = mWidth * 0.5f;
+            final float y = (mHeight + mWarningTextHeight) * 0.48f;
+            c.drawText(mWarningString, x, y, mWarningTextPaint);
+        } else if (mTracker.plugged) {
+            final Rect r = new Rect(
+                    (int)frame.left + width / 4,  (int)frame.top + height / 5,
+                    (int)frame.right - width / 4, (int)frame.bottom - height / 6);
+            mLightning.setBounds(r);
+            mLightning.draw(c);
+        } else if (mShowPercent && !(mTracker.level == 100 && !SHOW_100_PERCENT)) {
+            mTextPaint.setTextSize(height *
+                    (SINGLE_DIGIT_PERCENT ? 0.75f
+                            : (mTracker.level == 100 ? 0.38f : 0.5f)));
+            mTextHeight = -mTextPaint.getFontMetrics().ascent;
+
+            final String str = String.valueOf(SINGLE_DIGIT_PERCENT ? (pct/10) : pct);
+            final float x = mWidth * 0.5f;
+            final float y = (mHeight + mTextHeight) * 0.47f;
+            c.drawText(str,
+                    x,
+                    y,
+                    mTextPaint);
+
+//            Paint pt = new Paint();
+//            pt.setStrokeWidth(1f);
+//            pt.setStyle(Paint.Style.STROKE);
+//            pt.setColor(0xFFFF0000);
+//            c.drawRect(x, y-mTextHeight, x+tw, y, pt);
+//
+//            Slog.v(TAG, "tw=" + tw + " th=" + mTextHeight);
+//
+//            pt.setColor(0xFFFF00FF);
+//            c.drawRect(1, 1, mWidth, mHeight, pt);
+        }
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java
index d0a6385..b78239b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java
@@ -118,7 +118,7 @@
             int i = 0;
             float totalweight = 0f;
             float weight = 10f;
-            for (final Iterator<MotionEventCopy> iter = mEventBuf.descendingIterator();
+            for (final Iterator<MotionEventCopy> iter = mEventBuf.iterator();
                     iter.hasNext();) {
                 final MotionEventCopy event = iter.next();
                 if (last != null) {
@@ -126,13 +126,22 @@
                     final float dx = (event.x - last.x);
                     final float dy = (event.y - last.y);
                     if (FlingTracker.DEBUG) {
-                        Log.v("FlingTracker", String.format("   [%d] dx=%.1f dy=%.1f dt=%.0f vx=%.1f vy=%.1f",
-                                i,
+                        Log.v("FlingTracker", String.format(
+                                "   [%d] (t=%d %.1f,%.1f) dx=%.1f dy=%.1f dt=%f vx=%.1f vy=%.1f",
+                                i, event.t, event.x, event.y,
                                 dx, dy, dt,
                                 (dx/dt),
                                 (dy/dt)
                                 ));
                     }
+                    if (event.t == last.t) {
+                        // Really not sure what to do with events that happened at the same time,
+                        // so we'll skip subsequent events.
+                        if (DEBUG_NAN) {
+                            Log.v("FlingTracker", "skipping simultaneous event at t=" + event.t);
+                        }
+                        continue;
+                    }
                     mVX += weight * dx / dt;
                     mVY += weight * dy / dt;
                     totalweight += weight;
@@ -158,18 +167,18 @@
             }
         }
         public float getXVelocity() {
-            if (Float.isNaN(mVX)) {
+            if (Float.isNaN(mVX) || Float.isInfinite(mVX)) {
                 if (DEBUG_NAN) {
-                    Log.v("FlingTracker", "warning: vx=NaN");
+                    Log.v("FlingTracker", "warning: vx=" + mVX);
                 }
                 mVX = 0;
             }
             return mVX;
         }
         public float getYVelocity() {
-            if (Float.isNaN(mVY)) {
+            if (Float.isNaN(mVY) || Float.isInfinite(mVX)) {
                 if (DEBUG_NAN) {
-                    Log.v("FlingTracker", "warning: vx=NaN");
+                    Log.v("FlingTracker", "warning: vx=" + mVY);
                 }
                 mVY = 0;
             }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
index 7497087..62be5d6 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
@@ -507,7 +507,6 @@
         // Other icons
         mLocationController = new LocationController(mContext); // will post a notification
         mBatteryController = new BatteryController(mContext);
-        mBatteryController.addIconView((ImageView)mStatusBarView.findViewById(R.id.battery));
         mNetworkController = new NetworkController(mContext);
         mBluetoothController = new BluetoothController(mContext);
         mRotationLockController = new RotationLockController(mContext);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettings.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettings.java
index 5233f42..5f034a8c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettings.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettings.java
@@ -494,7 +494,9 @@
         }
 
         // Battery
-        final QuickSettingsBasicTile batteryTile = new QuickSettingsBasicTile(mContext);
+        final QuickSettingsTileView batteryTile = (QuickSettingsTileView)
+                inflater.inflate(R.layout.quick_settings_tile, parent, false);
+        batteryTile.setContent(R.layout.quick_settings_tile_battery, inflater);
         batteryTile.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
@@ -506,9 +508,6 @@
             public void refreshView(QuickSettingsTileView unused, State state) {
                 QuickSettingsModel.BatteryState batteryState =
                         (QuickSettingsModel.BatteryState) state;
-                Drawable d = batteryState.pluggedIn
-                        ? mChargingBatteryLevels
-                        : mBatteryLevels;
                 String t;
                 if (batteryState.batteryLevel == 100) {
                     t = mContext.getString(R.string.quick_settings_battery_charged_label);
@@ -519,9 +518,7 @@
                         : mContext.getString(R.string.status_bar_settings_battery_meter_format,
                                 batteryState.batteryLevel);
                 }
-                batteryTile.setImageDrawable(d);
-                batteryTile.getImageView().setImageLevel(batteryState.batteryLevel);
-                batteryTile.setText(t);
+                ((TextView)batteryTile.findViewById(R.id.text)).setText(t);
                 batteryTile.setContentDescription(
                         mContext.getString(R.string.accessibility_quick_settings_battery, t));
             }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/LocationController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/LocationController.java
index fcf04ac..c2ffff8 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/LocationController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/LocationController.java
@@ -53,7 +53,6 @@
     private StatusBarManager mStatusBarManager;
 
     private boolean mAreActiveLocationRequests;
-    private boolean mIsAirplaneMode;
 
     private ArrayList<LocationSettingsChangeCallback> mSettingsChangeCallbacks =
             new ArrayList<LocationSettingsChangeCallback>();
@@ -76,9 +75,6 @@
 
         IntentFilter filter = new IntentFilter();
         filter.addAction(LocationManager.HIGH_POWER_REQUEST_CHANGE_ACTION);
-        // Listen for a change in the airplane mode setting so we can defensively turn off the
-        // high power location icon when radios are disabled.
-        filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
         context.registerReceiver(this, filter);
 
         mAppOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
@@ -100,7 +96,6 @@
 
         // Examine the current location state and initialize the status view.
         updateActiveLocationRequests();
-        updateAirplaneMode();
         refreshViews();
     }
 
@@ -170,11 +165,9 @@
         return false;
     }
 
-    // Updates the status view based on the current state of location requests and airplane mode.
+    // Updates the status view based on the current state of location requests.
     private void refreshViews() {
-        // The airplane mode check is defensive - there shouldn't be any active high power
-        // location requests when airplane mode is on.
-        if (!mIsAirplaneMode && mAreActiveLocationRequests) {
+        if (mAreActiveLocationRequests) {
             mStatusBarManager.setIcon(LOCATION_STATUS_ICON_PLACEHOLDER, LOCATION_STATUS_ICON_ID, 0,
                     mContext.getString(R.string.accessibility_location_active));
         } else {
@@ -191,25 +184,11 @@
         }
     }
 
-    // Reads the airplane mode setting and updates the status view if necessary.
-    private void updateAirplaneMode() {
-        boolean wasAirplaneMode = mIsAirplaneMode;
-        // TODO This probably warrants a utility method in Settings.java.
-        mIsAirplaneMode = (Settings.Global.getInt(
-                mContext.getContentResolver(),
-                Settings.Global.AIRPLANE_MODE_ON, 0) == 1);
-        if (mIsAirplaneMode != wasAirplaneMode) {
-            refreshViews();
-        }
-    }
-
     @Override
     public void onReceive(Context context, Intent intent) {
         final String action = intent.getAction();
         if (LocationManager.HIGH_POWER_REQUEST_CHANGE_ACTION.equals(action)) {
             updateActiveLocationRequests();
-        } else if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) {
-            updateAirplaneMode();
         }
     }
 }
diff --git a/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java b/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
index 952dfda..22b5f03 100644
--- a/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
+++ b/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
@@ -943,7 +943,7 @@
                         }
                     }
                 });
-        mTransientNavigationConfirmation = new TransientNavigationConfirmation(mContext, mHandler);
+        mTransientNavigationConfirmation = new TransientNavigationConfirmation(mContext);
         mWindowManagerFuncs.registerPointerEventListener(mSystemGestures);
 
         mVibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
@@ -5114,11 +5114,14 @@
                 // show navigation transient bar
                 vis |= View.NAVIGATION_BAR_TRANSIENT;
                 if ((mLastSystemUiFlags & View.NAVIGATION_BAR_TRANSIENT) == 0) {
-                    vis &= ~View.SYSTEM_UI_FLAG_LOW_PROFILE;
                     setBarShowingLw(mNavigationBar, true);
                 }
             }
         }
+        if (mStatusTransientBar != TRANSIENT_BAR_NONE
+                || mNavigationTransientBar != TRANSIENT_BAR_NONE) {
+            vis &= ~View.SYSTEM_UI_FLAG_LOW_PROFILE;
+        }
         return vis;
     }
 
@@ -5414,5 +5417,18 @@
         pw.print(prefix); pw.print("mDemoHdmiRotation="); pw.print(mDemoHdmiRotation);
                 pw.print(" mDemoHdmiRotationLock="); pw.println(mDemoHdmiRotationLock);
         pw.print(prefix); pw.print("mUndockedHdmiRotation="); pw.println(mUndockedHdmiRotation);
+        dumpTransient(pw, prefix,
+                mStatusBar, "mStatusTransientBar", mStatusTransientBar);
+        dumpTransient(pw, prefix,
+                mNavigationBar, "mNavigationTransientBar", mNavigationTransientBar);
+    }
+
+    private void dumpTransient(PrintWriter pw, String pre, WindowState win, String var, int val) {
+        if (win != null) {
+            pw.print(pre); pw.print(var); pw.print('=');
+            pw.println(val == TRANSIENT_BAR_HIDING ? "HIDING"
+                     : val == TRANSIENT_BAR_SHOWING ? "SHOWING"
+                     : "NONE");
+        }
     }
 }
diff --git a/policy/src/com/android/internal/policy/impl/TransientNavigationConfirmation.java b/policy/src/com/android/internal/policy/impl/TransientNavigationConfirmation.java
index bd5bd80..3c4f092 100644
--- a/policy/src/com/android/internal/policy/impl/TransientNavigationConfirmation.java
+++ b/policy/src/com/android/internal/policy/impl/TransientNavigationConfirmation.java
@@ -18,9 +18,13 @@
 
 import android.content.Context;
 import android.os.Handler;
+import android.os.Message;
 import android.util.ArraySet;
 import android.util.Slog;
 import android.view.View;
+import android.view.animation.Animation;
+import android.view.animation.AnimationSet;
+import android.view.animation.AnimationUtils;
 import android.widget.Toast;
 
 import com.android.internal.R;
@@ -30,29 +34,26 @@
  *  is hidden.
  */
 public class TransientNavigationConfirmation {
-    private final String TAG = "TransientNavigationConfirmation";
-    private final boolean DEBUG = false;
+    private static final String TAG = "TransientNavigationConfirmation";
+    private static final boolean DEBUG = false;
 
     private final Context mContext;
-    private final Handler mHandler;
+    private final H mHandler;
     private final ArraySet<String> mConfirmedUserPackages = new ArraySet<String>();
-
-    private final Runnable mHandleDismiss = new Runnable() {
-        @Override
-        public void run() {
-            if (mToast != null) {
-                mToast.cancel();
-                mToast = null;
-            }
-        }
-    };
+    private final long mShowDelayMs;
 
     private Toast mToast;
     private String mLastUserPackage;
 
-    public TransientNavigationConfirmation(Context context, Handler handler) {
+    public TransientNavigationConfirmation(Context context) {
         mContext = context;
-        mHandler = handler;
+        mHandler = new H();
+        mShowDelayMs = getNavBarExitDuration() * 3;
+    }
+
+    private long getNavBarExitDuration() {
+        Animation exit = AnimationUtils.loadAnimation(mContext, R.anim.dock_bottom_exit);
+        return exit != null ? exit.getDuration() : 0;
     }
 
     public void transientNavigationChanged(int userId, String pkg, boolean isNavTransient) {
@@ -60,16 +61,17 @@
             return;
         }
         String userPkg = userId + ":" + pkg;
+        mHandler.removeMessages(H.SHOW);
         if (isNavTransient) {
             mLastUserPackage = userPkg;
             if (!mConfirmedUserPackages.contains(userPkg)) {
                 if (DEBUG) Slog.d(TAG, "Showing transient navigation confirmation for " + userPkg);
-                mHandler.post(handleShowConfirmation(userPkg));
+                mHandler.sendMessageDelayed(mHandler.obtainMessage(H.SHOW, userPkg), mShowDelayMs);
             }
         } else {
             mLastUserPackage = null;
             if (DEBUG) Slog.d(TAG, "Hiding transient navigation confirmation for " + userPkg);
-            mHandler.post(mHandleDismiss);
+            mHandler.sendEmptyMessage(H.HIDE);
         }
     }
 
@@ -80,22 +82,24 @@
         }
     }
 
-    private Runnable handleShowConfirmation(final String userPkg) {
-        return new Runnable() {
-            @Override
-            public void run() {
-                // create the confirmation toast bar
-                final int msg = R.string.transient_navigation_confirmation;
-                mToast = Toast.makeBar(mContext, msg, Toast.LENGTH_INFINITE);
-                mToast.setAction(R.string.ok, confirmAction(userPkg));
+    private void handleHide() {
+        if (mToast != null) {
+            mToast.cancel();
+            mToast = null;
+        }
+    }
 
-                // we will be hiding the nav bar, so layout as if it's already hidden
-                mToast.getView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
+    private void handleShow(String userPkg) {
+        // create the confirmation toast bar
+        final int msg = R.string.transient_navigation_confirmation;
+        mToast = Toast.makeBar(mContext, msg, Toast.LENGTH_INFINITE);
+        mToast.setAction(R.string.ok, confirmAction(userPkg));
 
-                // show the confirmation
-                mToast.show();
-            }
-        };
+        // we will be hiding the nav bar, so layout as if it's already hidden
+        mToast.getView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
+
+        // show the confirmation
+        mToast.show();
     }
 
     private Runnable confirmAction(final String userPkg) {
@@ -103,8 +107,25 @@
             @Override
             public void run() {
                 mConfirmedUserPackages.add(userPkg);
-                mHandleDismiss.run();
+                handleHide();
             }
         };
     }
+
+    private final class H extends Handler {
+        private static final int SHOW = 0;
+        private static final int HIDE = 1;
+
+        @Override
+        public void handleMessage(Message msg) {
+            switch(msg.what) {
+                case SHOW:
+                    handleShow((String)msg.obj);
+                    break;
+                case HIDE:
+                    handleHide();
+                    break;
+            }
+        }
+    }
 }
diff --git a/services/java/com/android/server/ConnectivityService.java b/services/java/com/android/server/ConnectivityService.java
index bb0d248..a0e6dd1 100644
--- a/services/java/com/android/server/ConnectivityService.java
+++ b/services/java/com/android/server/ConnectivityService.java
@@ -3916,13 +3916,13 @@
             Random rand = new Random();
             mParams = params;
 
-            try {
-                if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
-                    log("isMobileOk: not mobile capable");
-                    result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
-                    return result;
-                }
+            if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
+                log("isMobileOk: not mobile capable");
+                result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
+                return result;
+            }
 
+            try {
                 // Enable fail fast as we'll do retries here and use a
                 // hipri connection so the default connection stays active.
                 log("isMobileOk: start hipri url=" + params.mUrl);
diff --git a/services/java/com/android/server/LocationManagerService.java b/services/java/com/android/server/LocationManagerService.java
index a32699a..9761441 100644
--- a/services/java/com/android/server/LocationManagerService.java
+++ b/services/java/com/android/server/LocationManagerService.java
@@ -420,19 +420,7 @@
             Slog.e(TAG,  "no geocoder provider found");
         }
 
-        // bind to geofence provider
-        GeofenceProxy provider = GeofenceProxy.createAndBind(mContext,
-                com.android.internal.R.bool.config_enableGeofenceOverlay,
-                com.android.internal.R.string.config_geofenceProviderPackageName,
-                com.android.internal.R.array.config_locationProviderPackageNames,
-                mLocationHandler,
-                gpsProvider.getGpsGeofenceProxy());
-        if (provider == null) {
-            Slog.e(TAG,  "no geofence provider found");
-        }
-
         // bind to fused provider
-        // TODO: [GeofenceIntegration] bind #getGeofenceHardware() with the GeofenceProxy
         FlpHardwareProvider flpHardwareProvider = FlpHardwareProvider.getInstance(mContext);
         FusedProxy fusedProxy = FusedProxy.createAndBind(
                 mContext,
@@ -441,10 +429,21 @@
                 com.android.internal.R.bool.config_enableFusedLocationOverlay,
                 com.android.internal.R.string.config_fusedLocationProviderPackageName,
                 com.android.internal.R.array.config_locationProviderPackageNames);
-
         if(fusedProxy == null) {
             Slog.e(TAG, "No FusedProvider found.");
         }
+
+        // bind to geofence provider
+        GeofenceProxy provider = GeofenceProxy.createAndBind(mContext,
+                com.android.internal.R.bool.config_enableGeofenceOverlay,
+                com.android.internal.R.string.config_geofenceProviderPackageName,
+                com.android.internal.R.array.config_locationProviderPackageNames,
+                mLocationHandler,
+                gpsProvider.getGpsGeofenceProxy(),
+                flpHardwareProvider.getGeofenceHardware());
+        if (provider == null) {
+            Slog.e(TAG,  "no geofence provider found");
+        }
     }
 
     /**
@@ -549,30 +548,52 @@
             return s.toString();
         }
 
+        /**
+         * Update AppOp monitoring for this receiver.
+         *
+         * @param allow If true receiver is currently active, if false it's been removed.
+         */
         public void updateMonitoring(boolean allow) {
             if (mHideFromAppOps) {
                 return;
             }
 
+            boolean requestingLocation = false;
+            boolean requestingHighPowerLocation = false;
+            if (allow) {
+                // See if receiver has any enabled update records.  Also note if any update records
+                // are high power (has a high power provider with an interval under a threshold).
+                for (UpdateRecord updateRecord : mUpdateRecords.values()) {
+                    if (isAllowedByCurrentUserSettingsLocked(updateRecord.mProvider)) {
+                        requestingLocation = true;
+                        LocationProviderInterface locationProvider
+                            = mProvidersByName.get(updateRecord.mProvider);
+                        ProviderProperties properties = locationProvider != null
+                                ? locationProvider.getProperties() : null;
+                        if (properties != null
+                                && properties.mPowerRequirement == Criteria.POWER_HIGH
+                                && updateRecord.mRequest.getInterval() < HIGH_POWER_INTERVAL_MS) {
+                            requestingHighPowerLocation = true;
+                            break;
+                        }
+                    }
+                }
+            }
+
             // First update monitoring of any location request (including high power).
-            mOpMonitoring = updateMonitoring(allow, mOpMonitoring,
+            mOpMonitoring = updateMonitoring(
+                    requestingLocation,
+                    mOpMonitoring,
                     AppOpsManager.OP_MONITOR_LOCATION);
 
             // Now update monitoring of high power requests only.
-            // A high power request is any gps request with interval under a threshold.
-            boolean allowHighPower = allow;
-            if (allowHighPower) {
-                UpdateRecord gpsRecord = mUpdateRecords.get(LocationManager.GPS_PROVIDER);
-                if (gpsRecord == null
-                        || gpsRecord.mRequest.getInterval() > HIGH_POWER_INTERVAL_MS) {
-                    allowHighPower = false;
-                }
-            }
             boolean wasHighPowerMonitoring = mOpHighPowerMonitoring;
-            mOpHighPowerMonitoring = updateMonitoring(allowHighPower, mOpHighPowerMonitoring,
+            mOpHighPowerMonitoring = updateMonitoring(
+                    requestingHighPowerLocation,
+                    mOpHighPowerMonitoring,
                     AppOpsManager.OP_MONITOR_HIGH_POWER_LOCATION);
             if (mOpHighPowerMonitoring != wasHighPowerMonitoring) {
-                // send an intent to notify that a high power request has been added/removed.
+                // Send an intent to notify that a high power request has been added/removed.
                 Intent intent = new Intent(LocationManager.HIGH_POWER_REQUEST_CHANGE_ACTION);
                 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
             }
@@ -689,6 +710,10 @@
         }
 
         public boolean callProviderEnabledLocked(String provider, boolean enabled) {
+            // First update AppOp monitoring.
+            // An app may get/lose location access as providers are enabled/disabled.
+            updateMonitoring(true);
+
             if (mListener != null) {
                 try {
                     synchronized (this) {
diff --git a/services/java/com/android/server/am/ActivityManagerService.java b/services/java/com/android/server/am/ActivityManagerService.java
index a6d7e3c..be6119d 100644
--- a/services/java/com/android/server/am/ActivityManagerService.java
+++ b/services/java/com/android/server/am/ActivityManagerService.java
@@ -8062,12 +8062,10 @@
             if (activity == null) {
                 Slog.w(TAG, "getAssistContextExtras error: no resumed activity");
                 validActivity = false;
-            }
-            if (activity.app == null || activity.app.thread == null) {
+            } else if (activity.app == null || activity.app.thread == null) {
                 Slog.w(TAG, "getAssistContextExtras error: no process for " + activity);
                 validActivity = false;
-            }
-            if (activity.app.pid == Binder.getCallingPid()) {
+            } else if (activity.app.pid == Binder.getCallingPid()) {
                 Slog.w(TAG, "getAssistContextExtras error: request process same as " + activity);
                 validActivity = false;
             }
diff --git a/services/java/com/android/server/dreams/DreamManagerService.java b/services/java/com/android/server/dreams/DreamManagerService.java
index 21e54fe..b6e7781 100644
--- a/services/java/com/android/server/dreams/DreamManagerService.java
+++ b/services/java/com/android/server/dreams/DreamManagerService.java
@@ -86,7 +86,13 @@
 
     @Override
     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
-        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
+        if (mContext.checkCallingOrSelfPermission("android.permission.DUMP")
+                != PackageManager.PERMISSION_GRANTED) {
+            pw.println("Permission Denial: can't dump DreamManager from pid="
+                    + Binder.getCallingPid()
+                    + ", uid=" + Binder.getCallingUid());
+            return;
+        }
 
         pw.println("DREAM MANAGER (dumpsys dreams)");
         pw.println();
diff --git a/services/java/com/android/server/location/FlpHardwareProvider.java b/services/java/com/android/server/location/FlpHardwareProvider.java
index 226c18c..ebeccfb 100644
--- a/services/java/com/android/server/location/FlpHardwareProvider.java
+++ b/services/java/com/android/server/location/FlpHardwareProvider.java
@@ -16,12 +16,13 @@
 
 package com.android.server.location;
 
+import android.hardware.location.GeofenceHardware;
 import android.hardware.location.GeofenceHardwareImpl;
+import android.hardware.location.GeofenceHardwareRequestParcelable;
 import android.hardware.location.IFusedLocationHardware;
 import android.hardware.location.IFusedLocationHardwareSink;
 import android.location.IFusedGeofenceHardware;
 import android.location.FusedBatchOptions;
-import android.location.Geofence;
 import android.location.Location;
 import android.location.LocationListener;
 import android.location.LocationManager;
@@ -49,6 +50,15 @@
     private final Context mContext;
     private final Object mLocationSinkLock = new Object();
 
+    // FlpHal result codes, they must be equal to the ones in fused_location.h
+    private static final int FLP_RESULT_SUCCESS = 0;
+    private static final int FLP_RESULT_ERROR = -1;
+    private static final int FLP_RESULT_INSUFFICIENT_MEMORY = -2;
+    private static final int FLP_RESULT_TOO_MANY_GEOFENCES = -3;
+    private static final int FLP_RESULT_ID_EXISTS = -4;
+    private static final int FLP_RESULT_ID_UNKNOWN = -5;
+    private static final int FLP_RESULT_INVALID_GEOFENCE_TRANSITION = -6;
+
     public static FlpHardwareProvider getInstance(Context context) {
         if (sSingletonInstance == null) {
             sSingletonInstance = new FlpHardwareProvider(context);
@@ -120,29 +130,46 @@
             Location location,
             int transition,
             long timestamp,
-            int sourcesUsed
-            ) {
-        // TODO: [GeofenceIntegration] change GeofenceHardwareImpl to accept a location object
+            int sourcesUsed) {
+        getGeofenceHardwareSink().reportGeofenceTransition(
+                geofenceId,
+                updateLocationInformation(location),
+                transition,
+                timestamp,
+                GeofenceHardware.MONITORING_TYPE_FUSED_HARDWARE,
+                sourcesUsed);
     }
 
     private void onGeofenceMonitorStatus(int status, int source, Location location) {
-        // TODO: [GeofenceIntegration]
+        getGeofenceHardwareSink().reportGeofenceMonitorStatus(
+                GeofenceHardware.MONITORING_TYPE_FUSED_HARDWARE,
+                status,
+                updateLocationInformation(location),
+                source);
     }
 
     private void onGeofenceAdd(int geofenceId, int result) {
-        // TODO: [GeofenceIntegration] map between GPS and FLP results to pass a consistent status
+        getGeofenceHardwareSink().reportGeofenceAddStatus(
+                geofenceId,
+                translateToGeofenceHardwareStatus(result));
     }
 
     private void onGeofenceRemove(int geofenceId, int result) {
-        // TODO: [GeofenceIntegration] map between GPS and FLP results to pass a consistent status
+        getGeofenceHardwareSink().reportGeofenceRemoveStatus(
+                geofenceId,
+                translateToGeofenceHardwareStatus(result));
     }
 
     private void onGeofencePause(int geofenceId, int result) {
-        // TODO; [GeofenceIntegration] map between GPS and FLP results
+        getGeofenceHardwareSink().reportGeofencePauseStatus(
+                geofenceId,
+                translateToGeofenceHardwareStatus(result));
     }
 
     private void onGeofenceResume(int geofenceId, int result) {
-        // TODO: [GeofenceIntegration] map between GPS and FLP results
+        getGeofenceHardwareSink().reportGeofenceResumeStatus(
+                geofenceId,
+                translateToGeofenceHardwareStatus(result));
     }
 
     /**
@@ -175,7 +202,8 @@
 
     // FlpGeofencingInterface members
     private native boolean nativeIsGeofencingSupported();
-    private native void nativeAddGeofences(int[] geofenceIdsArray, Geofence[] geofencesArray);
+    private native void nativeAddGeofences(
+            GeofenceHardwareRequestParcelable[] geofenceRequestsArray);
     private native void nativePauseGeofence(int geofenceId);
     private native void  nativeResumeGeofence(int geofenceId, int monitorTransitions);
     private native void nativeModifyGeofenceOption(
@@ -281,8 +309,8 @@
         }
 
         @Override
-        public void addGeofences(int[] geofenceIdsArray, Geofence[] geofencesArray) {
-            nativeAddGeofences(geofenceIdsArray, geofencesArray);
+        public void addGeofences(GeofenceHardwareRequestParcelable[] geofenceRequestsArray) {
+            nativeAddGeofences(geofenceRequestsArray);
         }
 
         @Override
@@ -305,17 +333,15 @@
                 int lastTransition,
                 int monitorTransitions,
                 int notificationResponsiveness,
-                int unknownTimer
-                ) {
-            // TODO: [GeofenceIntegration] set sourcesToUse to the right value
-            // TODO: expose sourcesToUse externally when needed
+                int unknownTimer,
+                int sourcesToUse) {
             nativeModifyGeofenceOption(
                     geofenceId,
                     lastTransition,
                     monitorTransitions,
                     notificationResponsiveness,
                     unknownTimer,
-                    /* sourcesToUse */ 0xFFFF);
+                    sourcesToUse);
         }
     };
 
@@ -347,10 +373,39 @@
 
     private GeofenceHardwareImpl getGeofenceHardwareSink() {
         if (mGeofenceHardwareSink == null) {
-            // TODO: [GeofenceIntegration] we need to register ourselves with GeofenceHardwareImpl
             mGeofenceHardwareSink = GeofenceHardwareImpl.getInstance(mContext);
         }
 
         return mGeofenceHardwareSink;
     }
-}
\ No newline at end of file
+
+    private static int translateToGeofenceHardwareStatus(int flpHalResult) {
+        switch(flpHalResult) {
+            case FLP_RESULT_SUCCESS:
+                return GeofenceHardware.GEOFENCE_SUCCESS;
+            case FLP_RESULT_ERROR:
+                return GeofenceHardware.GEOFENCE_FAILURE;
+            // TODO: uncomment this once the ERROR definition is marked public
+            //case FLP_RESULT_INSUFFICIENT_MEMORY:
+            //    return GeofenceHardware.GEOFENCE_ERROR_INSUFFICIENT_MEMORY;
+            case FLP_RESULT_TOO_MANY_GEOFENCES:
+                return GeofenceHardware.GEOFENCE_ERROR_TOO_MANY_GEOFENCES;
+            case FLP_RESULT_ID_EXISTS:
+                return GeofenceHardware.GEOFENCE_ERROR_ID_EXISTS;
+            case FLP_RESULT_ID_UNKNOWN:
+                return GeofenceHardware.GEOFENCE_ERROR_ID_UNKNOWN;
+            case FLP_RESULT_INVALID_GEOFENCE_TRANSITION:
+                return GeofenceHardware.GEOFENCE_ERROR_INVALID_TRANSITION;
+            default:
+                Log.e(TAG, String.format("Invalid FlpHal result code: %d", flpHalResult));
+                return GeofenceHardware.GEOFENCE_FAILURE;
+        }
+    }
+
+    private Location updateLocationInformation(Location location) {
+        location.setProvider(LocationManager.FUSED_PROVIDER);
+        // set the elapsed time-stamp just as GPS provider does
+        location.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
+        return location;
+    }
+}
diff --git a/services/java/com/android/server/location/GeofenceProxy.java b/services/java/com/android/server/location/GeofenceProxy.java
index f6be27b..a86c923 100644
--- a/services/java/com/android/server/location/GeofenceProxy.java
+++ b/services/java/com/android/server/location/GeofenceProxy.java
@@ -22,6 +22,7 @@
 import android.hardware.location.IGeofenceHardware;
 import android.location.IGeofenceProvider;
 import android.location.IGpsGeofenceHardware;
+import android.location.IFusedGeofenceHardware;
 import android.content.Context;
 import android.os.Handler;
 import android.os.IBinder;
@@ -44,6 +45,7 @@
     private Context mContext;
     private IGeofenceHardware mGeofenceHardware;
     private IGpsGeofenceHardware mGpsGeofenceHardware;
+    private IFusedGeofenceHardware mFusedGeofenceHardware;
 
     private static final int GEOFENCE_PROVIDER_CONNECTED = 1;
     private static final int GEOFENCE_HARDWARE_CONNECTED = 2;
@@ -60,9 +62,11 @@
 
     public static GeofenceProxy createAndBind(Context context,
             int overlaySwitchResId, int defaultServicePackageNameResId,
-            int initialPackageNamesResId, Handler handler, IGpsGeofenceHardware gpsGeofence) {
+            int initialPackageNamesResId, Handler handler, IGpsGeofenceHardware gpsGeofence,
+            IFusedGeofenceHardware fusedGeofenceHardware) {
         GeofenceProxy proxy = new GeofenceProxy(context, overlaySwitchResId,
-            defaultServicePackageNameResId, initialPackageNamesResId, handler, gpsGeofence);
+            defaultServicePackageNameResId, initialPackageNamesResId, handler, gpsGeofence,
+            fusedGeofenceHardware);
         if (proxy.bindGeofenceProvider()) {
             return proxy;
         } else {
@@ -72,11 +76,13 @@
 
     private GeofenceProxy(Context context,
             int overlaySwitchResId, int defaultServicePackageNameResId,
-            int initialPackageNamesResId, Handler handler, IGpsGeofenceHardware gpsGeofence) {
+            int initialPackageNamesResId, Handler handler, IGpsGeofenceHardware gpsGeofence,
+            IFusedGeofenceHardware fusedGeofenceHardware) {
         mContext = context;
         mServiceWatcher = new ServiceWatcher(context, TAG, SERVICE_ACTION, overlaySwitchResId,
             defaultServicePackageNameResId, initialPackageNamesResId, mRunnable, handler);
         mGpsGeofenceHardware = gpsGeofence;
+        mFusedGeofenceHardware = fusedGeofenceHardware;
         bindHardwareGeofence();
     }
 
@@ -123,6 +129,13 @@
         }
     }
 
+    private void setFusedGeofence() {
+        try {
+            mGeofenceHardware.setFusedGeofenceHardware(mFusedGeofenceHardware);
+        } 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,
@@ -142,6 +155,7 @@
                     break;
                 case GEOFENCE_HARDWARE_CONNECTED:
                     setGpsGeofence();
+                    setFusedGeofence();
                     mGeofenceHardwareConnected = true;
                     if (mGeofenceProviderConnected) {
                         setGeofenceHardwareInProvider();
diff --git a/services/java/com/android/server/location/GpsLocationProvider.java b/services/java/com/android/server/location/GpsLocationProvider.java
index 38453c8..6053c61 100644
--- a/services/java/com/android/server/location/GpsLocationProvider.java
+++ b/services/java/com/android/server/location/GpsLocationProvider.java
@@ -24,9 +24,10 @@
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.database.Cursor;
+import android.hardware.location.GeofenceHardware;
 import android.hardware.location.GeofenceHardwareImpl;
-import android.hardware.location.IGeofenceHardware;
 import android.location.Criteria;
+import android.location.FusedBatchOptions;
 import android.location.IGpsGeofenceHardware;
 import android.location.IGpsStatusListener;
 import android.location.IGpsStatusProvider;
@@ -195,6 +196,17 @@
 
     private static final String PROPERTIES_FILE = "/etc/gps.conf";
 
+    private static final int GPS_GEOFENCE_UNAVAILABLE = 1<<0L;
+    private static final int GPS_GEOFENCE_AVAILABLE = 1<<1L;
+
+    // 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;
+
     /** simpler wrapper for ProviderRequest + Worksource */
     private static class GpsRequest {
         public ProviderRequest request;
@@ -501,7 +513,7 @@
                 LocationManager locManager =
                         (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
                 locManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER,
-                        0, 0, new NetworkLocationListener(), mHandler.getLooper());                
+                        0, 0, new NetworkLocationListener(), mHandler.getLooper());
             }
         });
     }
@@ -1405,6 +1417,62 @@
     }
 
     /**
+     * Helper method to construct a location object.
+     */
+    private Location buildLocation(
+            int flags,
+            double latitude,
+            double longitude,
+            double altitude,
+            float speed,
+            float bearing,
+            float accuracy,
+            long timestamp) {
+        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);
+            location.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
+        }
+        if((flags & LOCATION_HAS_ALTITUDE) == LOCATION_HAS_ALTITUDE) {
+            location.setAltitude(altitude);
+        }
+        if((flags & LOCATION_HAS_SPEED) == LOCATION_HAS_SPEED) {
+            location.setSpeed(speed);
+        }
+        if((flags & LOCATION_HAS_BEARING) == LOCATION_HAS_BEARING) {
+            location.setBearing(bearing);
+        }
+        if((flags & LOCATION_HAS_ACCURACY) == LOCATION_HAS_ACCURACY) {
+            location.setAccuracy(accuracy);
+        }
+        return location;
+    }
+
+    /**
+     * Converts the GPS HAL status to the internal Geofence Hardware status.
+     */
+    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;
+            default:
+                return -1;
+        }
+    }
+
+    /**
      * Called from native to report GPS Geofence transition
      * All geofence callbacks are called on the same thread
      */
@@ -1414,8 +1482,22 @@
         if (mGeofenceHardwareImpl == null) {
             mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
         }
-        mGeofenceHardwareImpl.reportGpsGeofenceTransition(geofenceId, flags, latitude, longitude,
-           altitude, speed, bearing, accuracy, timestamp, transition, transitionTimestamp);
+        Location location = buildLocation(
+                flags,
+                latitude,
+                longitude,
+                altitude,
+                speed,
+                bearing,
+                accuracy,
+                timestamp);
+        mGeofenceHardwareImpl.reportGeofenceTransition(
+                geofenceId,
+                location,
+                transition,
+                transitionTimestamp,
+                GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE,
+                FusedBatchOptions.SourceTechnologies.GNSS);
     }
 
     /**
@@ -1427,8 +1509,24 @@
         if (mGeofenceHardwareImpl == null) {
             mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
         }
-        mGeofenceHardwareImpl.reportGpsGeofenceStatus(status, flags, latitude, longitude, altitude,
-            speed, bearing, accuracy, timestamp);
+        Location location = buildLocation(
+                flags,
+                latitude,
+                longitude,
+                altitude,
+                speed,
+                bearing,
+                accuracy,
+                timestamp);
+        int monitorStatus = GeofenceHardware.MONITOR_CURRENTLY_UNAVAILABLE;
+        if(status == GPS_GEOFENCE_AVAILABLE) {
+            monitorStatus = GeofenceHardware.MONITOR_CURRENTLY_AVAILABLE;
+        }
+        mGeofenceHardwareImpl.reportGeofenceMonitorStatus(
+                GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE,
+                monitorStatus,
+                location,
+                FusedBatchOptions.SourceTechnologies.GNSS);
     }
 
     /**
@@ -1438,7 +1536,7 @@
         if (mGeofenceHardwareImpl == null) {
             mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
         }
-        mGeofenceHardwareImpl.reportGpsGeofenceAddStatus(geofenceId, status);
+        mGeofenceHardwareImpl.reportGeofenceAddStatus(geofenceId, getGeofenceStatus(status));
     }
 
     /**
@@ -1448,7 +1546,7 @@
         if (mGeofenceHardwareImpl == null) {
             mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
         }
-        mGeofenceHardwareImpl.reportGpsGeofenceRemoveStatus(geofenceId, status);
+        mGeofenceHardwareImpl.reportGeofenceRemoveStatus(geofenceId, getGeofenceStatus(status));
     }
 
     /**
@@ -1458,7 +1556,7 @@
         if (mGeofenceHardwareImpl == null) {
             mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
         }
-        mGeofenceHardwareImpl.reportGpsGeofencePauseStatus(geofenceId, status);
+        mGeofenceHardwareImpl.reportGeofencePauseStatus(geofenceId, getGeofenceStatus(status));
     }
 
     /**
@@ -1468,7 +1566,7 @@
         if (mGeofenceHardwareImpl == null) {
             mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
         }
-        mGeofenceHardwareImpl.reportGpsGeofenceResumeStatus(geofenceId, status);
+        mGeofenceHardwareImpl.reportGeofenceResumeStatus(geofenceId, getGeofenceStatus(status));
     }
 
     //=============================================================
diff --git a/services/java/com/android/server/pm/PackageManagerService.java b/services/java/com/android/server/pm/PackageManagerService.java
index 656080b..78c1c79 100755
--- a/services/java/com/android/server/pm/PackageManagerService.java
+++ b/services/java/com/android/server/pm/PackageManagerService.java
@@ -1792,8 +1792,8 @@
         }
     }
 
+    @Override
     public int[] getPackageGids(String packageName) {
-        final boolean enforcedDefault = isPermissionEnforcedDefault(READ_EXTERNAL_STORAGE);
         // reader
         synchronized (mPackages) {
             PackageParser.Package p = mPackages.get(packageName);
@@ -1801,17 +1801,7 @@
                 Log.v(TAG, "getPackageGids" + packageName + ": " + p);
             if (p != null) {
                 final PackageSetting ps = (PackageSetting)p.mExtras;
-                final SharedUserSetting suid = ps.sharedUser;
-                int[] gids = suid != null ? suid.gids : ps.gids;
-
-                // include GIDs for any unenforced permissions
-                if (!isPermissionEnforcedLocked(READ_EXTERNAL_STORAGE, enforcedDefault)) {
-                    final BasePermission basePerm = mSettings.mPermissions.get(
-                            READ_EXTERNAL_STORAGE);
-                    gids = appendInts(gids, basePerm.gids);
-                }
-
-                return gids;
+                return ps.getGids();
             }
         }
         // stupid thing to indicate an error.
@@ -2132,7 +2122,6 @@
     }
 
     public int checkPermission(String permName, String pkgName) {
-        final boolean enforcedDefault = isPermissionEnforcedDefault(permName);
         synchronized (mPackages) {
             PackageParser.Package p = mPackages.get(pkgName);
             if (p != null && p.mExtras != null) {
@@ -2145,15 +2134,11 @@
                     return PackageManager.PERMISSION_GRANTED;
                 }
             }
-            if (!isPermissionEnforcedLocked(permName, enforcedDefault)) {
-                return PackageManager.PERMISSION_GRANTED;
-            }
         }
         return PackageManager.PERMISSION_DENIED;
     }
 
     public int checkUidPermission(String permName, int uid) {
-        final boolean enforcedDefault = isPermissionEnforcedDefault(permName);
         synchronized (mPackages) {
             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
             if (obj != null) {
@@ -2167,9 +2152,6 @@
                     return PackageManager.PERMISSION_GRANTED;
                 }
             }
-            if (!isPermissionEnforcedLocked(permName, enforcedDefault)) {
-                return PackageManager.PERMISSION_GRANTED;
-            }
         }
         return PackageManager.PERMISSION_DENIED;
     }
@@ -11112,42 +11094,9 @@
     }
 
     @Override
+    @Deprecated
     public boolean isPermissionEnforced(String permission) {
-        final boolean enforcedDefault = isPermissionEnforcedDefault(permission);
-        synchronized (mPackages) {
-            return isPermissionEnforcedLocked(permission, enforcedDefault);
-        }
-    }
-
-    /**
-     * Check if given permission should be enforced by default. Should always be
-     * called outside of {@link #mPackages} lock.
-     */
-    private boolean isPermissionEnforcedDefault(String permission) {
-        if (READ_EXTERNAL_STORAGE.equals(permission)) {
-            return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
-                    android.provider.Settings.Global.READ_EXTERNAL_STORAGE_ENFORCED_DEFAULT, 0)
-                    != 0;
-        } else {
-            return true;
-        }
-    }
-
-    /**
-     * Check if user has requested that given permission be enforced, using
-     * given default if undefined.
-     */
-    private boolean isPermissionEnforcedLocked(String permission, boolean enforcedDefault) {
-        if (READ_EXTERNAL_STORAGE.equals(permission)) {
-            if (mSettings.mReadExternalStorageEnforced != null) {
-                return mSettings.mReadExternalStorageEnforced;
-            } else {
-                // User hasn't defined; fall back to secure default
-                return enforcedDefault;
-            }
-        } else {
-            return true;
-        }
+        return true;
     }
 
     public boolean isStorageLow() {
diff --git a/services/java/com/android/server/pm/PackageSetting.java b/services/java/com/android/server/pm/PackageSetting.java
index f7f0870..b6f9f5b 100644
--- a/services/java/com/android/server/pm/PackageSetting.java
+++ b/services/java/com/android/server/pm/PackageSetting.java
@@ -52,4 +52,8 @@
             + Integer.toHexString(System.identityHashCode(this))
             + " " + name + "/" + appId + "}";
     }
-}
\ No newline at end of file
+
+    public int[] getGids() {
+        return sharedUser != null ? sharedUser.gids : gids;
+    }
+}
diff --git a/services/java/com/android/server/pm/Settings.java b/services/java/com/android/server/pm/Settings.java
index e78362b..e18202b 100644
--- a/services/java/com/android/server/pm/Settings.java
+++ b/services/java/com/android/server/pm/Settings.java
@@ -1385,9 +1385,10 @@
 
                 StringBuilder sb = new StringBuilder();
                 for (final PackageSetting pkg : mPackages.values()) {
-                    ApplicationInfo ai = pkg.pkg.applicationInfo;
-                    String dataPath = ai.dataDir;
-                    boolean isDebug  = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
+                    final ApplicationInfo ai = pkg.pkg.applicationInfo;
+                    final String dataPath = ai.dataDir;
+                    final boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
+                    final int[] gids = pkg.getGids();
 
                     // Avoid any application that has a space in its path
                     // or that is handled by the system.
@@ -1401,6 +1402,7 @@
                     // debugFlag  - 0 or 1 if the package is debuggable.
                     // dataPath   - path to package's data path
                     // seinfo     - seinfo label for the app (assigned at install time)
+                    // gids       - supplementary gids this app launches with
                     //
                     // NOTE: We prefer not to expose all ApplicationInfo flags for now.
                     //
@@ -1417,6 +1419,16 @@
                     sb.append(dataPath);
                     sb.append(" ");
                     sb.append(ai.seinfo);
+                    sb.append(" ");
+                    if (gids != null && gids.length > 0) {
+                        sb.append(gids[0]);
+                        for (int i = 1; i < gids.length; i++) {
+                            sb.append(",");
+                            sb.append(gids[i]);
+                        }
+                    } else {
+                        sb.append("none");
+                    }
                     sb.append("\n");
                     str.write(sb.toString().getBytes());
                 }
@@ -1425,6 +1437,7 @@
                 str.close();
                 journal.commit();
             } catch (Exception e) {
+                Log.wtf(TAG, "Failed to write packages.list", e);
                 IoUtils.closeQuietly(str);
                 journal.rollback();
             }
diff --git a/services/java/com/android/server/print/RemotePrintService.java b/services/java/com/android/server/print/RemotePrintService.java
index 322de6c..491dddc 100644
--- a/services/java/com/android/server/print/RemotePrintService.java
+++ b/services/java/com/android/server/print/RemotePrintService.java
@@ -110,6 +110,7 @@
     }
 
     private void handleBinderDied() {
+        mPendingCommands.clear();
         ensureUnbound();
     }
 
diff --git a/services/java/com/android/server/wifi/WifiService.java b/services/java/com/android/server/wifi/WifiService.java
index 6e0e055..db030f1 100644
--- a/services/java/com/android/server/wifi/WifiService.java
+++ b/services/java/com/android/server/wifi/WifiService.java
@@ -25,18 +25,20 @@
 import android.content.IntentFilter;
 import android.content.pm.PackageManager;
 import android.database.ContentObserver;
-import android.net.wifi.IWifiManager;
-import android.net.wifi.ScanResult;
-import android.net.wifi.WifiInfo;
-import android.net.wifi.WifiManager;
-import android.net.wifi.WifiStateMachine;
-import android.net.wifi.WifiConfiguration;
-import android.net.wifi.WifiWatchdogStateMachine;
 import android.net.DhcpInfo;
 import android.net.DhcpResults;
 import android.net.LinkAddress;
 import android.net.NetworkUtils;
 import android.net.RouteInfo;
+import android.net.wifi.IWifiManager;
+import android.net.wifi.ScanResult;
+import android.net.wifi.BatchedScanResult;
+import android.net.wifi.BatchedScanSettings;
+import android.net.wifi.WifiConfiguration;
+import android.net.wifi.WifiInfo;
+import android.net.wifi.WifiManager;
+import android.net.wifi.WifiStateMachine;
+import android.net.wifi.WifiWatchdogStateMachine;
 import android.os.Binder;
 import android.os.Handler;
 import android.os.Messenger;
@@ -63,6 +65,7 @@
 import java.net.InetAddress;
 import java.net.Inet4Address;
 import java.util.ArrayList;
+import java.util.HashMap;
 import java.util.List;
 
 import java.util.concurrent.atomic.AtomicBoolean;
@@ -121,6 +124,8 @@
     /* Tracks the persisted states for wi-fi & airplane mode */
     final WifiSettingsStore mSettingsStore;
 
+    final boolean mBatchedScanSupported;
+
     /**
      * Asynchronous channel to WifiStateMachine
      */
@@ -246,6 +251,9 @@
         mWifiController = new WifiController(mContext, this, wifiThread.getLooper());
         mWifiController.start();
 
+        mBatchedScanSupported = mContext.getResources().getBoolean(
+                R.bool.config_wifi_batched_scan_supported);
+
         registerForScanModeChange();
         mContext.registerReceiver(
                 new BroadcastReceiver() {
@@ -314,6 +322,142 @@
         mWifiStateMachine.startScan(Binder.getCallingUid(), workSource);
     }
 
+    private class BatchedScanRequest extends DeathRecipient {
+        BatchedScanSettings settings;
+        int uid;
+
+        BatchedScanRequest(BatchedScanSettings settings, IBinder binder, int uid) {
+            super(0, null, binder, null);
+            this.settings = settings;
+            this.uid = uid;
+        }
+        public void binderDied() {
+            stopBatchedScan(settings, mBinder);
+        }
+        public String toString() {
+            return "BatchedScanRequest{settings=" + settings + ", binder=" + mBinder + "}";
+        }
+    }
+
+    private final List<BatchedScanRequest> mBatchedScanners = new ArrayList<BatchedScanRequest>();
+
+    public boolean isBatchedScanSupported() {
+        return mBatchedScanSupported;
+    }
+
+    /**
+     * see {@link android.net.wifi.WifiManager#requestBatchedScan()}
+     */
+    public boolean requestBatchedScan(BatchedScanSettings requested, IBinder binder) {
+        enforceChangePermission();
+        if (mBatchedScanSupported == false) return false;
+        requested = new BatchedScanSettings(requested);
+        if (requested.isInvalid()) return false;
+        BatchedScanRequest r = new BatchedScanRequest(requested, binder, Binder.getCallingUid());
+        synchronized(mBatchedScanners) {
+            mBatchedScanners.add(r);
+            resolveBatchedScannersLocked();
+        }
+        return true;
+    }
+
+    public List<BatchedScanResult> getBatchedScanResults(String callingPackage) {
+        enforceAccessPermission();
+        if (mBatchedScanSupported == false) return new ArrayList<BatchedScanResult>();
+        int userId = UserHandle.getCallingUserId();
+        int uid = Binder.getCallingUid();
+        long ident = Binder.clearCallingIdentity();
+        try {
+            if (mAppOps.noteOp(AppOpsManager.OP_WIFI_SCAN, uid, callingPackage)
+                    != AppOpsManager.MODE_ALLOWED) {
+                return new ArrayList<BatchedScanResult>();
+            }
+            int currentUser = ActivityManager.getCurrentUser();
+            if (userId != currentUser) {
+                return new ArrayList<BatchedScanResult>();
+            } else {
+                return mWifiStateMachine.syncGetBatchedScanResultsList();
+            }
+        } finally {
+            Binder.restoreCallingIdentity(ident);
+        }
+    }
+
+
+    public void stopBatchedScan(BatchedScanSettings settings, IBinder binder) {
+        enforceChangePermission();
+        if (mBatchedScanSupported == false) return;
+        synchronized(mBatchedScanners) {
+            BatchedScanRequest found = null;
+            for (BatchedScanRequest r : mBatchedScanners) {
+                if (r.mBinder.equals(binder) && r.settings.equals(settings)) {
+                    found = r;
+                    break;
+                }
+            }
+            if (found != null) {
+                mBatchedScanners.remove(found);
+                resolveBatchedScannersLocked();
+            }
+        }
+    }
+
+    private void resolveBatchedScannersLocked() {
+        BatchedScanSettings setting = new BatchedScanSettings();
+        setting.scanIntervalSec = BatchedScanSettings.DEFAULT_INTERVAL_SEC;
+        int responsibleUid = 0;
+        setting.channelSet = new ArrayList<String>();
+
+        if (mBatchedScanners.size() == 0) {
+            mWifiStateMachine.setBatchedScanSettings(null, 0);
+            return;
+        }
+
+        for (BatchedScanRequest r : mBatchedScanners) {
+            BatchedScanSettings s = r.settings;
+            if (s.maxScansPerBatch != BatchedScanSettings.UNSPECIFIED &&
+                    s.maxScansPerBatch < setting.maxScansPerBatch) {
+                setting.maxScansPerBatch = s.maxScansPerBatch;
+                responsibleUid = r.uid;
+            }
+            if (s.maxApPerScan != BatchedScanSettings.UNSPECIFIED &&
+                    s.maxApPerScan > setting.maxApPerScan) {
+                setting.maxApPerScan = s.maxApPerScan;
+            }
+            if (s.scanIntervalSec != BatchedScanSettings.UNSPECIFIED &&
+                    s.scanIntervalSec < setting.scanIntervalSec) {
+                setting.scanIntervalSec = s.scanIntervalSec;
+                responsibleUid = r.uid;
+            }
+            if (s.maxApForDistance != BatchedScanSettings.UNSPECIFIED &&
+                    s.maxApForDistance > setting.maxApForDistance) {
+                setting.maxApForDistance = s.maxApForDistance;
+            }
+            if (s.channelSet != null) {
+                for (String i : s.channelSet) {
+                    if (setting.channelSet.contains(i) == false) setting.channelSet.add(i);
+                }
+            }
+        }
+        if (setting.channelSet.size() == 0) setting.channelSet = null;
+        if (setting.scanIntervalSec < BatchedScanSettings.MIN_INTERVAL_SEC) {
+            setting.scanIntervalSec = BatchedScanSettings.MIN_INTERVAL_SEC;
+        }
+        if (setting.maxScansPerBatch == BatchedScanSettings.UNSPECIFIED) {
+            setting.maxScansPerBatch = BatchedScanSettings.DEFAULT_SCANS_PER_BATCH;
+        }
+        if (setting.maxApPerScan == BatchedScanSettings.UNSPECIFIED) {
+            setting.maxApPerScan = BatchedScanSettings.DEFAULT_AP_PER_SCAN;
+        }
+        if (setting.scanIntervalSec == BatchedScanSettings.UNSPECIFIED) {
+            setting.scanIntervalSec = BatchedScanSettings.DEFAULT_INTERVAL_SEC;
+        }
+        if (setting.maxApForDistance == BatchedScanSettings.UNSPECIFIED) {
+            setting.maxApForDistance = BatchedScanSettings.DEFAULT_AP_FOR_DISTANCE;
+        }
+        mWifiStateMachine.setBatchedScanSettings(setting, responsibleUid);
+    }
+
     private void enforceAccessPermission() {
         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
                                                 "WifiService");
@@ -569,11 +713,11 @@
         int userId = UserHandle.getCallingUserId();
         int uid = Binder.getCallingUid();
         long ident = Binder.clearCallingIdentity();
-        if (mAppOps.noteOp(AppOpsManager.OP_WIFI_SCAN, uid, callingPackage)
-                != AppOpsManager.MODE_ALLOWED) {
-            return new ArrayList<ScanResult>();
-        }
         try {
+            if (mAppOps.noteOp(AppOpsManager.OP_WIFI_SCAN, uid, callingPackage)
+                    != AppOpsManager.MODE_ALLOWED) {
+                return new ArrayList<ScanResult>();
+            }
             int currentUser = ActivityManager.getCurrentUser();
             if (userId != currentUser) {
                 return new ArrayList<ScanResult>();
diff --git a/services/jni/com_android_server_location_FlpHardwareProvider.cpp b/services/jni/com_android_server_location_FlpHardwareProvider.cpp
index 48b86db..c871828 100644
--- a/services/jni/com_android_server_location_FlpHardwareProvider.cpp
+++ b/services/jni/com_android_server_location_FlpHardwareProvider.cpp
@@ -261,6 +261,75 @@
 }
 
 /*
+ * Helper function to unwrap Geofence structures from the Java Runtime calls.
+ */
+static void TranslateGeofenceFromGeofenceHardwareRequestParcelable(
+    JNIEnv* env,
+    jobject geofenceRequestObject,
+    Geofence& geofence) {
+  jclass geofenceRequestClass = env->GetObjectClass(geofenceRequestObject);
+
+  jmethodID getId = env->GetMethodID(geofenceRequestClass, "getId", "()I");
+  geofence.geofence_id = env->CallIntMethod(geofenceRequestObject, getId);
+
+  jmethodID getType = env->GetMethodID(geofenceRequestClass, "getType", "()I");
+  // this works because GeofenceHardwareRequest.java and fused_location.h have
+  // the same notion of geofence types
+  GeofenceType type = (GeofenceType)env->CallIntMethod(geofenceRequestObject, getType);
+  if(type != TYPE_CIRCLE) {
+    ThrowOnError(env, FLP_RESULT_ERROR, __FUNCTION__);
+  }
+  geofence.data->type = type;
+  GeofenceCircle& circle = geofence.data->geofence.circle;
+
+  jmethodID getLatitude = env->GetMethodID(
+      geofenceRequestClass,
+      "getLatitude",
+      "()D");
+  circle.latitude = env->CallDoubleMethod(geofenceRequestObject, getLatitude);
+
+  jmethodID getLongitude = env->GetMethodID(
+      geofenceRequestClass,
+      "getLongitude",
+      "()D");
+  circle.longitude = env->CallDoubleMethod(geofenceRequestObject, getLongitude);
+
+  jmethodID getRadius = env->GetMethodID(geofenceRequestClass, "getRadius", "()D");
+  circle.radius_m = env->CallDoubleMethod(geofenceRequestObject, getRadius);
+
+  GeofenceOptions* options = geofence.options;
+  jmethodID getMonitorTransitions = env->GetMethodID(
+      geofenceRequestClass,
+      "getMonitorTransitions",
+      "()I");
+  options->monitor_transitions = env->CallIntMethod(
+      geofenceRequestObject,
+      getMonitorTransitions);
+
+  jmethodID getUnknownTimer = env->GetMethodID(
+      geofenceRequestClass,
+      "getUnknownTimer",
+      "()I");
+  options->unknown_timer_ms = env->CallIntMethod(geofenceRequestObject, getUnknownTimer);
+
+  jmethodID getNotificationResponsiveness = env->GetMethodID(
+      geofenceRequestClass,
+      "getNotificationResponsiveness",
+      "()D");
+  options->notification_responsivenes_ms = env->CallIntMethod(
+      geofenceRequestObject,
+      getNotificationResponsiveness);
+
+  jmethodID getLastTransition = env->GetMethodID(
+      geofenceRequestClass,
+      "getLastTransition",
+      "()I");
+  options->last_transition = env->CallIntMethod(geofenceRequestObject, getLastTransition);
+
+  // TODO: set data.sources_to_use when available
+}
+
+/*
  * Helper function to transform FlpLocation into a java object.
  */
 static void TranslateToObject(const FlpLocation* location, jobject& locationObject) {
@@ -559,7 +628,7 @@
   }
 
   err = module->methods->open(
-        module, 
+        module,
         FUSED_LOCATION_HARDWARE_MODULE_ID, &sHardwareDevice);
   if(err != 0) {
     ALOGE("Error opening device '%s': %d", FUSED_LOCATION_HARDWARE_MODULE_ID, err);
@@ -749,10 +818,9 @@
 static void AddGeofences(
     JNIEnv* env,
     jobject object,
-    jintArray geofenceIdsArray,
-    jobjectArray geofencesArray) {
-  if(geofencesArray == NULL) {
-    ALOGE("Invalid Geofences to add: %p", geofencesArray);
+    jobjectArray geofenceRequestsArray) {
+  if(geofenceRequestsArray == NULL) {
+    ALOGE("Invalid Geofences to add: %p", geofenceRequestsArray);
     ThrowOnError(env, FLP_RESULT_ERROR, __FUNCTION__);
   }
 
@@ -760,23 +828,32 @@
     ThrowOnError(env, FLP_RESULT_ERROR, __FUNCTION__);
   }
 
-  jint geofencesCount = env->GetArrayLength(geofenceIdsArray);
-  Geofence* geofences = new Geofence[geofencesCount];
+  jint geofenceRequestsCount = env->GetArrayLength(geofenceRequestsArray);
+  if(geofenceRequestsCount == 0) {
+    return;
+  }
+
+  Geofence* geofences = new Geofence[geofenceRequestsCount];
   if (geofences == NULL) {
     ThrowOnError(env, FLP_RESULT_INSUFFICIENT_MEMORY, __FUNCTION__);
   }
 
-  jint* ids = env->GetIntArrayElements(geofenceIdsArray, /* isCopy */ NULL);
-  for (int i = 0; i < geofencesCount; ++i) {
-    geofences[i].geofence_id = ids[i];
+  for (int i = 0; i < geofenceRequestsCount; ++i) {
+    geofences[i].data = new GeofenceData();
+    geofences[i].options = new GeofenceOptions();
+    jobject geofenceObject = env->GetObjectArrayElement(geofenceRequestsArray, i);
 
-    // TODO: fill in the GeofenceData
-
-    // TODO: fill in the GeofenceOptions
+    TranslateGeofenceFromGeofenceHardwareRequestParcelable(env, geofenceObject, geofences[i]);
   }
 
-  sFlpGeofencingInterface->add_geofences(geofencesCount, &geofences);
-  if (geofences != NULL) delete[] geofences;
+  sFlpGeofencingInterface->add_geofences(geofenceRequestsCount, &geofences);
+  if (geofences != NULL) {
+    for(int i = 0; i < geofenceRequestsCount; ++i) {
+      delete geofences[i].data;
+      delete geofences[i].options;
+    }
+    delete[] geofences;
+  }
 }
 
 static void PauseGeofence(JNIEnv* env, jobject object, jint geofenceId) {
@@ -847,41 +924,41 @@
   {"nativeCleanup", "()V", reinterpret_cast<void*>(Cleanup)},
   {"nativeIsSupported", "()Z", reinterpret_cast<void*>(IsSupported)},
   {"nativeGetBatchSize", "()I", reinterpret_cast<void*>(GetBatchSize)},
-  {"nativeStartBatching", 
-        "(ILandroid/location/FusedBatchOptions;)V", 
+  {"nativeStartBatching",
+        "(ILandroid/location/FusedBatchOptions;)V",
         reinterpret_cast<void*>(StartBatching)},
-  {"nativeUpdateBatchingOptions", 
-        "(ILandroid/location/FusedBatchOptions;)V", 
+  {"nativeUpdateBatchingOptions",
+        "(ILandroid/location/FusedBatchOptions;)V",
         reinterpret_cast<void*>(UpdateBatchingOptions)},
   {"nativeStopBatching", "(I)V", reinterpret_cast<void*>(StopBatching)},
-  {"nativeRequestBatchedLocation", 
-        "(I)V", 
+  {"nativeRequestBatchedLocation",
+        "(I)V",
         reinterpret_cast<void*>(GetBatchedLocation)},
-  {"nativeInjectLocation", 
-        "(Landroid/location/Location;)V", 
+  {"nativeInjectLocation",
+        "(Landroid/location/Location;)V",
         reinterpret_cast<void*>(InjectLocation)},
-  {"nativeIsDiagnosticSupported", 
-        "()Z", 
+  {"nativeIsDiagnosticSupported",
+        "()Z",
         reinterpret_cast<void*>(IsDiagnosticSupported)},
-  {"nativeInjectDiagnosticData", 
-        "(Ljava/lang/String;)V", 
+  {"nativeInjectDiagnosticData",
+        "(Ljava/lang/String;)V",
         reinterpret_cast<void*>(InjectDiagnosticData)},
-  {"nativeIsDeviceContextSupported", 
-        "()Z", 
+  {"nativeIsDeviceContextSupported",
+        "()Z",
         reinterpret_cast<void*>(IsDeviceContextSupported)},
-  {"nativeInjectDeviceContext", 
-        "(I)V", 
+  {"nativeInjectDeviceContext",
+        "(I)V",
         reinterpret_cast<void*>(InjectDeviceContext)},
-  {"nativeIsGeofencingSupported", 
-        "()Z", 
+  {"nativeIsGeofencingSupported",
+        "()Z",
         reinterpret_cast<void*>(IsGeofencingSupported)},
-  {"nativeAddGeofences", 
-        "([I[Landroid/location/Geofence;)V", 
+  {"nativeAddGeofences",
+        "([Landroid/hardware/location/GeofenceHardwareRequestParcelable;)V",
         reinterpret_cast<void*>(AddGeofences)},
   {"nativePauseGeofence", "(I)V", reinterpret_cast<void*>(PauseGeofence)},
   {"nativeResumeGeofence", "(II)V", reinterpret_cast<void*>(ResumeGeofence)},
-  {"nativeModifyGeofenceOption", 
-        "(IIIIII)V", 
+  {"nativeModifyGeofenceOption",
+        "(IIIIII)V",
         reinterpret_cast<void*>(ModifyGeofenceOption)},
   {"nativeRemoveGeofences", "([I)V", reinterpret_cast<void*>(RemoveGeofences)}
 };
diff --git a/wifi/java/android/net/wifi/BatchedScanResult.aidl b/wifi/java/android/net/wifi/BatchedScanResult.aidl
new file mode 100644
index 0000000..a70bc0a
--- /dev/null
+++ b/wifi/java/android/net/wifi/BatchedScanResult.aidl
@@ -0,0 +1,19 @@
+/**
+ * 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.net.wifi;
+
+parcelable BatchedScanResult;
diff --git a/wifi/java/android/net/wifi/BatchedScanResult.java b/wifi/java/android/net/wifi/BatchedScanResult.java
new file mode 100644
index 0000000..eb4e0276
--- /dev/null
+++ b/wifi/java/android/net/wifi/BatchedScanResult.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.net.wifi;
+
+import android.os.Parcelable;
+import android.os.Parcel;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * Describes the Results of a batched set of wifi scans where the firmware performs many
+ * scans and stores the timestamped results without waking the main processor each time.
+ * @hide pending review
+ */
+public class BatchedScanResult implements Parcelable {
+    private static final String TAG = "BatchedScanResult";
+
+    /** Inidcates this scan was interrupted and may only have partial results. */
+    public boolean truncated;
+
+    /** The result of this particular scan. */
+    public final List<ScanResult> scanResults = new ArrayList<ScanResult>();
+
+
+    public BatchedScanResult() {
+    }
+
+    public BatchedScanResult(BatchedScanResult source) {
+        truncated = source.truncated;
+        for (ScanResult s : source.scanResults) scanResults.add(new ScanResult(s));
+    }
+
+    @Override
+    public String toString() {
+        StringBuffer sb = new StringBuffer();
+
+        sb.append("BatchedScanResult: ").
+                append("truncated: ").append(String.valueOf(truncated)).
+                append("scanResults: [");
+        for (ScanResult s : scanResults) {
+            sb.append(" <").append(s.toString()).append("> ");
+        }
+        sb.append(" ]");
+        return sb.toString();
+    }
+
+    /** Implement the Parcelable interface {@hide} */
+    public int describeContents() {
+        return 0;
+    }
+
+    /** Implement the Parcelable interface {@hide} */
+    public void writeToParcel(Parcel dest, int flags) {
+        dest.writeInt(truncated ? 1 : 0);
+        dest.writeInt(scanResults.size());
+        for (ScanResult s : scanResults) {
+            s.writeToParcel(dest, flags);
+        }
+    }
+
+    /** Implement the Parcelable interface {@hide} */
+    public static final Creator<BatchedScanResult> CREATOR =
+        new Creator<BatchedScanResult>() {
+            public BatchedScanResult createFromParcel(Parcel in) {
+                BatchedScanResult result = new BatchedScanResult();
+                result.truncated = (in.readInt() == 1);
+                int count = in.readInt();
+                while (count-- > 0) {
+                    result.scanResults.add(ScanResult.CREATOR.createFromParcel(in));
+                }
+                return result;
+            }
+
+            public BatchedScanResult[] newArray(int size) {
+                return new BatchedScanResult[size];
+            }
+        };
+}
diff --git a/wifi/java/android/net/wifi/BatchedScanSettings.aidl b/wifi/java/android/net/wifi/BatchedScanSettings.aidl
new file mode 100644
index 0000000..8cfc508
--- /dev/null
+++ b/wifi/java/android/net/wifi/BatchedScanSettings.aidl
@@ -0,0 +1,19 @@
+/**
+ * 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.net.wifi;
+
+parcelable BatchedScanSettings;
diff --git a/wifi/java/android/net/wifi/BatchedScanSettings.java b/wifi/java/android/net/wifi/BatchedScanSettings.java
new file mode 100644
index 0000000..82945d6
--- /dev/null
+++ b/wifi/java/android/net/wifi/BatchedScanSettings.java
@@ -0,0 +1,226 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.net.wifi;
+
+import android.os.Parcelable;
+import android.os.Parcel;
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+/**
+ * Describes the settings for batched wifi scans where the firmware performs many
+ * scans and stores the timestamped results without waking the main processor each time.
+ * This can give information over time with minimal battery impact.
+ * @hide pending review
+ */
+public class BatchedScanSettings implements Parcelable {
+    private static final String TAG = "BatchedScanSettings";
+
+    /** Used to indicate no preference for an int value */
+    public final static int UNSPECIFIED = Integer.MAX_VALUE;
+
+    // TODO - make MIN/mAX dynamic and gservices adjustable.
+    public final static int MIN_SCANS_PER_BATCH = 2;
+    public final static int MAX_SCANS_PER_BATCH = 255;
+    public final static int DEFAULT_SCANS_PER_BATCH = MAX_SCANS_PER_BATCH;
+
+    public final static int MIN_AP_PER_SCAN = 2;
+    public final static int MAX_AP_PER_SCAN = 255;
+    public final static int DEFAULT_AP_PER_SCAN = 16;
+
+    public final static int MIN_INTERVAL_SEC = 0;
+    public final static int MAX_INTERVAL_SEC = 3600;
+    public final static int DEFAULT_INTERVAL_SEC = 30;
+
+    public final static int MIN_AP_FOR_DISTANCE = 0;
+    public final static int MAX_AP_FOR_DISTANCE = MAX_AP_PER_SCAN;
+    public final static int DEFAULT_AP_FOR_DISTANCE = 0;
+
+
+    /** The expected number of scans per batch.  Note that the firmware may drop scans
+     *  leading to fewer scans during the normal batch scan duration.  This value need not
+     *  be specified (may be set to {@link UNSPECIFIED}) by the application and we will try
+     *  to scan as many times as the firmware can support.  If another app requests fewer
+     *  scans per batch we will attempt to honor that.
+     */
+    public int maxScansPerBatch;
+
+    /** The maximum desired AP listed per scan.  Fewer AP may be returned if that's all
+     *  that the driver detected.  If another application requests more AP per scan that
+     *  will take precedence.  The if more channels are detected than we request, the APs
+     *  with the lowest signal strength will be dropped.
+     */
+    public int maxApPerScan;
+
+    /** The channels used in the scan.  If all channels should be used, {@code null} may be
+     *  specified.  If another application requests more channels or all channels, that
+     *  will take precedence.
+     */
+    public Collection<String> channelSet;
+
+    /** The time between the start of two sequential scans, in seconds.  If another
+     *  application requests more frequent scans, that will take precedence.  If this
+     * value is less than the duration of a scan, the next scan should start immediately.
+     */
+    public int scanIntervalSec;
+
+    /** The number of the best (strongest signal) APs for which the firmware will
+     *  attempt to get distance information (RTT).  Not all firmware supports this
+     *  feature, so it may be ignored.  If another application requests a greater
+     *  number, that will take precedence.
+     */
+    public int maxApForDistance;
+
+    public BatchedScanSettings() {
+        clear();
+    }
+
+    public void clear() {
+        maxScansPerBatch = UNSPECIFIED;
+        maxApPerScan = UNSPECIFIED;
+        channelSet = null;
+        scanIntervalSec = UNSPECIFIED;
+        maxApForDistance = UNSPECIFIED;
+    }
+
+    public BatchedScanSettings(BatchedScanSettings source) {
+        maxScansPerBatch = source.maxScansPerBatch;
+        maxApPerScan = source.maxApPerScan;
+        if (source.channelSet != null) {
+            channelSet = new ArrayList(source.channelSet);
+        }
+        scanIntervalSec = source.scanIntervalSec;
+        maxApForDistance = source.maxApForDistance;
+    }
+
+    private boolean channelSetIsValid() {
+        if (channelSet == null || channelSet.isEmpty()) return true;
+        for (String channel : channelSet) {
+            try {
+                int i = Integer.parseInt(channel);
+                if (i > 0 && i < 197) continue;
+            } catch (NumberFormatException e) {}
+            if (channel.equals("A") || channel.equals("B")) continue;
+            return false;
+        }
+        return true;
+    }
+    /** @hide */
+    public boolean isInvalid() {
+        if (maxScansPerBatch != UNSPECIFIED && (maxScansPerBatch < MIN_SCANS_PER_BATCH ||
+                maxScansPerBatch > MAX_SCANS_PER_BATCH)) return true;
+        if (maxApPerScan != UNSPECIFIED && (maxApPerScan < MIN_AP_PER_SCAN ||
+                maxApPerScan > MAX_AP_PER_SCAN)) return true;
+        if (channelSetIsValid() == false) return true;
+        if (scanIntervalSec != UNSPECIFIED && (scanIntervalSec < MIN_INTERVAL_SEC ||
+                scanIntervalSec > MAX_INTERVAL_SEC)) return true;
+        if (maxApForDistance != UNSPECIFIED && (maxApForDistance < MIN_AP_FOR_DISTANCE ||
+                maxApForDistance > MAX_AP_FOR_DISTANCE)) return true;
+        return false;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (obj instanceof BatchedScanSettings == false) return false;
+        BatchedScanSettings o = (BatchedScanSettings)obj;
+        if (maxScansPerBatch != o.maxScansPerBatch ||
+              maxApPerScan != o.maxApPerScan ||
+              scanIntervalSec != o.scanIntervalSec ||
+              maxApForDistance != o.maxApForDistance) return false;
+        if (channelSet == null) {
+            return (o.channelSet == null);
+        }
+        return channelSet.equals(o.channelSet);
+    }
+
+    @Override
+    public int hashCode() {
+        return maxScansPerBatch +
+                (maxApPerScan * 3) +
+                (scanIntervalSec * 5) +
+                (maxApForDistance * 7) +
+                (channelSet.hashCode() * 11);
+    }
+
+    @Override
+    public String toString() {
+        StringBuffer sb = new StringBuffer();
+        String none = "<none>";
+
+        sb.append("BatchScanSettings [maxScansPerBatch: ").
+                append(maxScansPerBatch == UNSPECIFIED ? none : maxScansPerBatch).
+                append(", maxApPerScan: ").append(maxApPerScan == UNSPECIFIED? none : maxApPerScan).
+                append(", scanIntervalSec: ").
+                append(scanIntervalSec == UNSPECIFIED ? none : scanIntervalSec).
+                append(", maxApForDistance: ").
+                append(maxApForDistance == UNSPECIFIED ? none : maxApForDistance).
+                append(", channelSet: ");
+        if (channelSet == null) {
+            sb.append("ALL");
+        } else {
+            sb.append("<");
+            for (String channel : channelSet) {
+                sb.append(" " + channel);
+            }
+            sb.append(">");
+        }
+        sb.append("]");
+        return sb.toString();
+    }
+
+    /** Implement the Parcelable interface {@hide} */
+    public int describeContents() {
+        return 0;
+    }
+
+    /** Implement the Parcelable interface {@hide} */
+    public void writeToParcel(Parcel dest, int flags) {
+        dest.writeInt(maxScansPerBatch);
+        dest.writeInt(maxApPerScan);
+        dest.writeInt(scanIntervalSec);
+        dest.writeInt(maxApForDistance);
+        dest.writeInt(channelSet == null ? 0 : channelSet.size());
+        if (channelSet != null) {
+            for (String channel : channelSet) dest.writeString(channel);
+        }
+    }
+
+    /** Implement the Parcelable interface {@hide} */
+    public static final Creator<BatchedScanSettings> CREATOR =
+        new Creator<BatchedScanSettings>() {
+            public BatchedScanSettings createFromParcel(Parcel in) {
+                BatchedScanSettings settings = new BatchedScanSettings();
+                settings.maxScansPerBatch = in.readInt();
+                settings.maxApPerScan = in.readInt();
+                settings.scanIntervalSec = in.readInt();
+                settings.maxApForDistance = in.readInt();
+                int channelCount = in.readInt();
+                if (channelCount > 0) {
+                    settings.channelSet = new ArrayList(channelCount);
+                    while (channelCount-- > 0) {
+                        settings.channelSet.add(in.readString());
+                    }
+                }
+                return settings;
+            }
+
+            public BatchedScanSettings[] newArray(int size) {
+                return new BatchedScanSettings[size];
+            }
+        };
+}
diff --git a/wifi/java/android/net/wifi/IWifiManager.aidl b/wifi/java/android/net/wifi/IWifiManager.aidl
index 8103e84..c8cf323 100644
--- a/wifi/java/android/net/wifi/IWifiManager.aidl
+++ b/wifi/java/android/net/wifi/IWifiManager.aidl
@@ -16,8 +16,10 @@
 
 package android.net.wifi;
 
-import android.net.wifi.WifiInfo;
+import android.net.wifi.BatchedScanResult;
+import android.net.wifi.BatchedScanSettings;
 import android.net.wifi.WifiConfiguration;
+import android.net.wifi.WifiInfo;
 import android.net.wifi.ScanResult;
 import android.net.DhcpInfo;
 
@@ -114,5 +116,13 @@
     void enableTdls(String remoteIPAddress, boolean enable);
 
     void enableTdlsWithMacAddress(String remoteMacAddress, boolean enable);
+
+    boolean requestBatchedScan(in BatchedScanSettings requested, IBinder binder);
+
+    void stopBatchedScan(in BatchedScanSettings requested, IBinder binder);
+
+    List<BatchedScanResult> getBatchedScanResults(String callingPackage);
+
+    boolean isBatchedScanSupported();
 }
 
diff --git a/wifi/java/android/net/wifi/ScanResult.java b/wifi/java/android/net/wifi/ScanResult.java
index 9977419..12729d2 100644
--- a/wifi/java/android/net/wifi/ScanResult.java
+++ b/wifi/java/android/net/wifi/ScanResult.java
@@ -54,7 +54,26 @@
      * Time Synchronization Function (tsf) timestamp in microseconds when
      * this result was last seen.
      */
-     public long timestamp;
+    public long timestamp;
+
+    /**
+     * The approximate distance to the AP in centimeter, if available.  Else
+     * {@link UNSPECIFIED}.
+     * {@hide}
+     */
+    public int distanceCm;
+
+    /**
+     * The standard deviation of the distance to the AP, if available.
+     * Else {@link UNSPECIFIED}.
+     * {@hide}
+     */
+    public int distanceSdCm;
+
+    /**
+     * {@hide}
+     */
+    public final static int UNSPECIFIED = -1;
 
     /** {@hide} */
     public ScanResult(WifiSsid wifiSsid, String BSSID, String caps, int level, int frequency,
@@ -66,8 +85,23 @@
         this.level = level;
         this.frequency = frequency;
         this.timestamp = tsf;
+        this.distanceCm = UNSPECIFIED;
+        this.distanceSdCm = UNSPECIFIED;
     }
 
+    /** {@hide} */
+    public ScanResult(WifiSsid wifiSsid, String BSSID, String caps, int level, int frequency,
+            long tsf, int distCm, int distSdCm) {
+        this.wifiSsid = wifiSsid;
+        this.SSID = (wifiSsid != null) ? wifiSsid.toString() : WifiSsid.NONE;
+        this.BSSID = BSSID;
+        this.capabilities = caps;
+        this.level = level;
+        this.frequency = frequency;
+        this.timestamp = tsf;
+        this.distanceCm = distCm;
+        this.distanceSdCm = distSdCm;
+    }
 
     /** copy constructor {@hide} */
     public ScanResult(ScanResult source) {
@@ -79,6 +113,8 @@
             level = source.level;
             frequency = source.frequency;
             timestamp = source.timestamp;
+            distanceCm = source.distanceCm;
+            distanceSdCm = source.distanceSdCm;
         }
     }
 
@@ -100,6 +136,11 @@
             append(", timestamp: ").
             append(timestamp);
 
+        sb.append(", distance: ").append((distanceCm != UNSPECIFIED ? distanceCm : "?")).
+                append("(cm)");
+        sb.append(", distanceSd: ").append((distanceSdCm != UNSPECIFIED ? distanceSdCm : "?")).
+                append("(cm)");
+
         return sb.toString();
     }
 
@@ -121,6 +162,8 @@
         dest.writeInt(level);
         dest.writeInt(frequency);
         dest.writeLong(timestamp);
+        dest.writeInt(distanceCm);
+        dest.writeInt(distanceSdCm);
     }
 
     /** Implement the Parcelable interface {@hide} */
@@ -137,7 +180,9 @@
                     in.readString(),
                     in.readInt(),
                     in.readInt(),
-                    in.readLong()
+                    in.readLong(),
+                    in.readInt(),
+                    in.readInt()
                 );
             }
 
diff --git a/wifi/java/android/net/wifi/WifiManager.java b/wifi/java/android/net/wifi/WifiManager.java
index 6793710..01ca378 100644
--- a/wifi/java/android/net/wifi/WifiManager.java
+++ b/wifi/java/android/net/wifi/WifiManager.java
@@ -35,6 +35,7 @@
 import java.net.InetAddress;
 import java.util.concurrent.CountDownLatch;
 
+import com.android.internal.R;
 import com.android.internal.util.AsyncChannel;
 import com.android.internal.util.Protocol;
 
@@ -365,6 +366,14 @@
     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
     public static final String SCAN_RESULTS_AVAILABLE_ACTION = "android.net.wifi.SCAN_RESULTS";
     /**
+     * A batch of access point scans has been completed and the results areavailable.
+     * Call {@link #getBatchedScanResults()} to obtain the results.
+     * @hide pending review
+     */
+    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
+    public static final String BATCHED_SCAN_RESULTS_AVAILABLE_ACTION =
+            "android.net.wifi.BATCHED_RESULTS";
+    /**
      * The RSSI (signal strength) has changed.
      * @see #EXTRA_NEW_RSSI
      */
@@ -778,6 +787,59 @@
     }
 
     /**
+     * Request a batched scan for access points.  To end your requested batched scan,
+     * call stopBatchedScan with the same Settings.
+     *
+     * If there are mulitple requests for batched scans, the more demanding settings will
+     * take precidence.
+     *
+     * @param requested {@link BatchedScanSettings} the scan settings requested.
+     * @return false on known error
+     * @hide
+     */
+    public boolean requestBatchedScan(BatchedScanSettings requested) {
+        try {
+            return mService.requestBatchedScan(requested, new Binder());
+        } catch (RemoteException e) { return false; }
+    }
+
+    /**
+     * Check if the Batched Scan feature is supported.
+     *
+     * @return false if not supported.
+     * @hide
+     */
+    public boolean isBatchedScanSupported() {
+        try {
+            return mService.isBatchedScanSupported();
+        } catch (RemoteException e) { return false; }
+    }
+
+    /**
+     * End a requested batch scan for this applicaiton.  Note that batched scan may
+     * still occur if other apps are using them.
+     * @hide
+     */
+    public void stopBatchedScan(BatchedScanSettings requested) {
+        try {
+            mService.stopBatchedScan(requested, new Binder());
+        } catch (RemoteException e) {}
+    }
+
+    /**
+     * Retrieve the latest batched scan result.  This should be called immediately after
+     * {@link BATCHED_SCAN_RESULTS_AVAILABLE_ACTION} is received.
+     * @hide
+     */
+    public List<BatchedScanResult> getBatchedScanResults() {
+        try {
+            return mService.getBatchedScanResults(mContext.getBasePackageName());
+        } catch (RemoteException e) {
+            return null;
+        }
+    }
+
+    /**
      * Return dynamic information about the current Wi-Fi connection, if any is active.
      * @return the Wi-Fi information, contained in {@link WifiInfo}.
      */
diff --git a/wifi/java/android/net/wifi/WifiNative.java b/wifi/java/android/net/wifi/WifiNative.java
index d30c7cf..0359076 100644
--- a/wifi/java/android/net/wifi/WifiNative.java
+++ b/wifi/java/android/net/wifi/WifiNative.java
@@ -219,6 +219,40 @@
         return doStringCommand("BSS RANGE=" + sid + "- MASK=0x21987");
     }
 
+    /**
+     * Format of command
+     * DRIVER WLS_BATCHING SET SCAN_FRQ=x BESTN=y CHANNEL=<z, w, t> RTT=s
+     * where x is an ascii representation of an integer number of seconds between scans
+     *       y is an ascii representation of an integer number of the max AP to remember per scan
+     *       z, w, t represent a 1..n size list of channel numbers and/or 'A', 'B' values
+     *           indicating entire ranges of channels
+     *       s is an ascii representation of an integer number of highest-strength AP
+     *           for which we'd like approximate distance reported
+     *
+     * The return value is an ascii integer representing a guess of the number of scans
+     * the firmware can remember before it runs out of buffer space or -1 on error
+     */
+    public String setBatchedScanSettings(BatchedScanSettings settings) {
+        if (settings == null) return doStringCommand("DRIVER WLS_BATCHING STOP");
+        String cmd = "DRIVER WLS_BATCHING SET SCAN_FRQ=" + settings.scanIntervalSec;
+        if (settings.maxApPerScan != BatchedScanSettings.UNSPECIFIED) {
+            cmd += " BESTN " + settings.maxApPerScan;
+        }
+        if (settings.channelSet != null && !settings.channelSet.isEmpty()) {
+            cmd += " CHANNEL=<";
+            for (String channel : settings.channelSet) cmd += " " + channel;
+            cmd += ">";
+        }
+        if (settings.maxApForDistance != BatchedScanSettings.UNSPECIFIED) {
+            cmd += " RTT=" + settings.maxApForDistance;
+        }
+        return doStringCommand(cmd);
+    }
+
+    public String getBatchedScanResults() {
+        return doStringCommand("DRIVER WLS_BATCHING GET");
+    }
+
     public boolean startDriver() {
         return doBooleanCommand("DRIVER START");
     }
diff --git a/wifi/java/android/net/wifi/WifiStateMachine.java b/wifi/java/android/net/wifi/WifiStateMachine.java
index 1fcd609..764c00a 100644
--- a/wifi/java/android/net/wifi/WifiStateMachine.java
+++ b/wifi/java/android/net/wifi/WifiStateMachine.java
@@ -123,6 +123,11 @@
     private static final int SCAN_RESULT_CACHE_SIZE = 80;
     private final LruCache<String, ScanResult> mScanResultCache;
 
+    /* Batch scan results */
+    private final List<BatchedScanResult> mBatchedScanResults =
+            new ArrayList<BatchedScanResult>();
+    private int mBatchedScanOwnerUid = UNKNOWN_SCAN_SOURCE;
+
     /* Chipset supports background scan */
     private final boolean mBackgroundScanSupported;
 
@@ -211,6 +216,7 @@
     private AlarmManager mAlarmManager;
     private PendingIntent mScanIntent;
     private PendingIntent mDriverStopIntent;
+    private PendingIntent mBatchedScanIntervalIntent;
 
     /* Tracks current frequency mode */
     private AtomicInteger mFrequencyBand = new AtomicInteger(WifiManager.WIFI_FREQUENCY_BAND_AUTO);
@@ -356,6 +362,13 @@
 
     public static final int CMD_BOOT_COMPLETED            = BASE + 134;
 
+    /* change the batch scan settings.
+     * arg1 = responsible UID
+     * obj = the new settings
+     */
+    public static final int CMD_SET_BATCH_SCAN            = BASE + 135;
+    public static final int CMD_START_NEXT_BATCHED_SCAN   = BASE + 136;
+
     public static final int CONNECT_MODE                   = 1;
     public static final int SCAN_ONLY_MODE                 = 2;
     public static final int SCAN_ONLY_WITH_WIFI_OFF_MODE   = 3;
@@ -520,6 +533,8 @@
     private static final String ACTION_DELAYED_DRIVER_STOP =
         "com.android.server.WifiManager.action.DELAYED_DRIVER_STOP";
 
+    private static final String ACTION_REFRESH_BATCHED_SCAN =
+            "com.android.server.WifiManager.action.REFRESH_BATCHED_SCAN";
     /**
      * Keep track of whether WIFI is running.
      */
@@ -542,6 +557,9 @@
 
     private final IBatteryStats mBatteryStats;
 
+    private BatchedScanSettings mBatchedScanSettings = null;
+
+
     public WifiStateMachine(Context context, String wlanInterface) {
         super("WifiStateMachine");
         mContext = context;
@@ -577,6 +595,9 @@
         Intent scanIntent = new Intent(ACTION_START_SCAN, null);
         mScanIntent = PendingIntent.getBroadcast(mContext, SCAN_REQUEST, scanIntent, 0);
 
+        Intent batchedIntent = new Intent(ACTION_REFRESH_BATCHED_SCAN, null);
+        mBatchedScanIntervalIntent = PendingIntent.getBroadcast(mContext, 0, batchedIntent, 0);
+
         mDefaultFrameworkScanIntervalMs = mContext.getResources().getInteger(
                 R.integer.config_wifi_framework_scan_interval);
 
@@ -614,22 +635,25 @@
                 },
                 new IntentFilter(ACTION_START_SCAN));
 
-        IntentFilter screenFilter = new IntentFilter();
-        screenFilter.addAction(Intent.ACTION_SCREEN_ON);
-        screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
-        BroadcastReceiver screenReceiver = new BroadcastReceiver() {
-            @Override
-            public void onReceive(Context context, Intent intent) {
-                String action = intent.getAction();
+        IntentFilter filter = new IntentFilter();
+        filter.addAction(Intent.ACTION_SCREEN_ON);
+        filter.addAction(Intent.ACTION_SCREEN_OFF);
+        filter.addAction(ACTION_REFRESH_BATCHED_SCAN);
+        mContext.registerReceiver(
+                new BroadcastReceiver() {
+                    @Override
+                    public void onReceive(Context context, Intent intent) {
+                        String action = intent.getAction();
 
-                if (action.equals(Intent.ACTION_SCREEN_ON)) {
-                    handleScreenStateChanged(true);
-                } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
-                    handleScreenStateChanged(false);
-                }
-            }
-        };
-        mContext.registerReceiver(screenReceiver, screenFilter);
+                        if (action.equals(Intent.ACTION_SCREEN_ON)) {
+                            handleScreenStateChanged(true);
+                        } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
+                            handleScreenStateChanged(false);
+                        } else if (action.equals(ACTION_REFRESH_BATCHED_SCAN)) {
+                            startNextBatchedScanAsync();
+                        }
+                    }
+                }, filter);
 
         mContext.registerReceiver(
                 new BroadcastReceiver() {
@@ -738,6 +762,269 @@
         sendMessage(CMD_START_SCAN, callingUid, 0, workSource);
     }
 
+    /**
+     * start or stop batched scanning using the given settings
+     */
+    public void setBatchedScanSettings(BatchedScanSettings settings, int callingUid) {
+        sendMessage(CMD_SET_BATCH_SCAN, callingUid, 0, settings);
+    }
+
+    public List<BatchedScanResult> syncGetBatchedScanResultsList() {
+        synchronized (mBatchedScanResults) {
+            List<BatchedScanResult> batchedScanList =
+                    new ArrayList<BatchedScanResult>(mBatchedScanResults.size());
+            for(BatchedScanResult result: mBatchedScanResults) {
+                batchedScanList.add(new BatchedScanResult(result));
+            }
+            return batchedScanList;
+        }
+    }
+
+    private void startBatchedScan() {
+        // first grab any existing data
+        retrieveBatchedScanData();
+
+        mAlarmManager.cancel(mBatchedScanIntervalIntent);
+
+        String scansExpected = mWifiNative.setBatchedScanSettings(mBatchedScanSettings);
+
+        try {
+            int expected = Integer.parseInt(scansExpected);
+            setNextBatchedAlarm(expected);
+        } catch (NumberFormatException e) {
+            loge("Exception parsing WifiNative.setBatchedScanSettings response " + e);
+        }
+    }
+
+    // called from BroadcastListener
+    private void startNextBatchedScanAsync() {
+        sendMessage(CMD_START_NEXT_BATCHED_SCAN);
+    }
+
+    private void startNextBatchedScan() {
+        // first grab any existing data
+        int nextCount = retrieveBatchedScanData();
+
+        setNextBatchedAlarm(nextCount);
+    }
+
+    // return true if new/different
+    private boolean recordBatchedScanSettings(BatchedScanSettings settings) {
+        if (DBG) log("set batched scan to " + settings);
+        if (settings != null) {
+            // TODO - noteBatchedScanStart(message.arg1);
+            if (settings.equals(mBatchedScanSettings)) return false;
+        } else {
+            if (mBatchedScanSettings == null) return false;
+            // TODO - noteBatchedScanStop(message.arg1);
+        }
+        mBatchedScanSettings = settings;
+        return true;
+    }
+
+    private void stopBatchedScan() {
+        mAlarmManager.cancel(mBatchedScanIntervalIntent);
+        retrieveBatchedScanData();
+        mWifiNative.setBatchedScanSettings(null);
+    }
+
+    private void setNextBatchedAlarm(int scansExpected) {
+
+        if (mBatchedScanSettings == null || scansExpected < 1) return;
+
+        if (mBatchedScanSettings.maxScansPerBatch < scansExpected) {
+            scansExpected = mBatchedScanSettings.maxScansPerBatch;
+        }
+
+        int secToFull = mBatchedScanSettings.scanIntervalSec;
+        secToFull *= scansExpected;
+
+        int debugPeriod = SystemProperties.getInt("wifi.batchedScan.pollPeriod", 0);
+        if (debugPeriod > 0) secToFull = debugPeriod;
+
+        // set the alarm to do the next poll.  We set it a little short as we'd rather
+        // wake up wearly than miss a scan due to buffer overflow
+        mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+                + ((secToFull - (mBatchedScanSettings.scanIntervalSec / 2)) * 1000),
+                mBatchedScanIntervalIntent);
+    }
+
+    /**
+     * Start reading new scan data
+     * Data comes in as:
+     * "scancount=5\n"
+     * "nextcount=5\n"
+     *   "apcount=3\n"
+     *   "trunc\n" (optional)
+     *     "bssid=...\n"
+     *     "ssid=...\n"
+     *     "freq=...\n" (in Mhz)
+     *     "level=...\n"
+     *     "dist=...\n" (in cm)
+     *     "distsd=...\n" (standard deviation, in cm)
+     *     "===="
+     *     "bssid=...\n"
+     *     etc
+     *     "===="
+     *     "bssid=...\n"
+     *     etc
+     *     "%%%%"
+     *   "apcount=2\n"
+     *     "bssid=...\n"
+     *     etc
+     *     "%%%%
+     *   etc
+     *   "----"
+     */
+    private int retrieveBatchedScanData() {
+        String rawData = mWifiNative.getBatchedScanResults();
+        if (rawData == null) {
+            loge("Unexpected null BatchedScanResults");
+            return 0;
+        }
+
+        int nextCount = 0;
+        int scanCount = 0;
+        final String END_OF_SCAN = "====";
+        final String END_OF_BATCH = "%%%%";
+        final String END_OF_BATCHES = "----";
+        final String SCANCOUNT = "scancount=";
+        final String NEXTCOUNT = "nextcount=";
+        final String TRUNCATED = "trunc";
+        final String APCOUNT = "apcount=";
+        final String AGE = "age=";
+        final String DIST = "dist=";
+        final String DISTSD = "distsd=";
+
+        String splitData[] = rawData.split("\n");
+        int n = 0;
+        if (splitData[n].startsWith(SCANCOUNT)) {
+            try {
+                scanCount = Integer.parseInt(splitData[n++].substring(SCANCOUNT.length()));
+            } catch (NumberFormatException e) {}
+        }
+        if (scanCount == 0) {
+            loge("scanCount not found");
+            return 0;
+        }
+        if (splitData[n].startsWith(NEXTCOUNT)) {
+            try {
+                nextCount = Integer.parseInt(splitData[n++].substring(NEXTCOUNT.length()));
+            } catch (NumberFormatException e) {}
+        }
+        if (nextCount == 0) {
+            loge("nextCount not found");
+            return 0;
+        }
+
+        final Intent intent = new Intent(WifiManager.BATCHED_SCAN_RESULTS_AVAILABLE_ACTION);
+        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
+
+        synchronized (mBatchedScanResults) {
+            mBatchedScanResults.clear();
+            BatchedScanResult batchedScanResult = new BatchedScanResult();
+
+            String bssid = null;
+            WifiSsid wifiSsid = null;
+            int level = 0;
+            int freq = 0;
+            int dist, distSd;
+            long tsf = 0;
+            dist = distSd = ScanResult.UNSPECIFIED;
+            long now = System.currentTimeMillis();
+
+            while (true) {
+                while (n < splitData.length) {
+                    if (splitData[n].equals(END_OF_BATCHES)) {
+                        if (++n != splitData.length) {
+                            loge("didn't consume " + (splitData.length-n));
+                        }
+                        if (mBatchedScanResults.size() > 0) {
+                            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
+                        }
+                        return nextCount;
+                    }
+                    if ((splitData[n].equals(END_OF_SCAN)) || splitData[n].equals(END_OF_BATCH)) {
+                        if (bssid != null) {
+                            batchedScanResult.scanResults.add(new ScanResult(
+                                    wifiSsid, bssid, "", level, freq, tsf, dist, distSd));
+                            wifiSsid = null;
+                            bssid = null;
+                            level = 0;
+                            freq = 0;
+                            tsf = 0;
+                            dist = distSd = ScanResult.UNSPECIFIED;
+                        }
+                        if (splitData[n].equals(END_OF_BATCH)) {
+                            if (batchedScanResult.scanResults.size() != 0) {
+                                mBatchedScanResults.add(batchedScanResult);
+                                batchedScanResult = new BatchedScanResult();
+                            } else {
+                                logd("Found empty batch");
+                            }
+                        }
+                        n++;
+                    } else if (splitData[n].equals(BSSID_STR)) {
+                        bssid = splitData[n++].substring(BSSID_STR.length());
+                    } else if (splitData[n].equals(FREQ_STR)) {
+                        try {
+                            freq = Integer.parseInt(splitData[n++].substring(FREQ_STR.length()));
+                        } catch (NumberFormatException e) {
+                            loge("Invalid freqency: " + splitData[n-1]);
+                            freq = 0;
+                        }
+                    } else if (splitData[n].equals(AGE)) {
+                        try {
+                            tsf = now - Long.parseLong(splitData[n++].substring(AGE.length()));
+                        } catch (NumberFormatException e) {
+                            loge("Invalid timestamp: " + splitData[n-1]);
+                            tsf = 0;
+                        }
+                    } else if (splitData[n].equals(SSID_STR)) {
+                        wifiSsid = WifiSsid.createFromAsciiEncoded(
+                                splitData[n++].substring(SSID_STR.length()));
+                    } else if (splitData[n].equals(LEVEL_STR)) {
+                        try {
+                            level = Integer.parseInt(splitData[n++].substring(LEVEL_STR.length()));
+                            if (level > 0) level -= 256;
+                        } catch (NumberFormatException e) {
+                            loge("Invalid level: " + splitData[n-1]);
+                            level = 0;
+                        }
+                    } else if (splitData[n].equals(DIST)) {
+                        try {
+                            dist = Integer.parseInt(splitData[n++].substring(DIST.length()));
+                        } catch (NumberFormatException e) {
+                            loge("Invalid distance: " + splitData[n-1]);
+                            dist = ScanResult.UNSPECIFIED;
+                        }
+                    } else if (splitData[n].equals(DISTSD)) {
+                        try {
+                            distSd = Integer.parseInt(splitData[n++].substring(DISTSD.length()));
+                        } catch (NumberFormatException e) {
+                            loge("Invalid distanceSd: " + splitData[n-1]);
+                            distSd = ScanResult.UNSPECIFIED;
+                        }
+                    }
+                }
+                rawData = mWifiNative.getBatchedScanResults();
+                if (rawData == null) {
+                    loge("Unexpected null BatchedScanResults");
+                    return nextCount;
+                }
+                splitData = rawData.split("\n");
+                if (splitData.length == 0 || splitData[0].equals("ok")) {
+                    loge("batch scan results just ended!");
+                    if (mBatchedScanResults.size() > 0) {
+                        mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
+                    }
+                    return nextCount;
+                }
+                n = 0;
+            }
+        }
+    }
+
     // If workSource is not null, blame is given to it, otherwise blame is given to callingUid.
     private void noteScanStart(int callingUid, WorkSource workSource) {
         if (mScanWorkSource == null && (callingUid != UNKNOWN_SCAN_SOURCE || workSource != null)) {
@@ -1979,6 +2266,12 @@
                         sendMessageAtFrontOfQueue(CMD_SET_COUNTRY_CODE, countryCode);
                     }
                     break;
+                case CMD_SET_BATCH_SCAN:
+                    recordBatchedScanSettings((BatchedScanSettings)message.obj);
+                    break;
+                case CMD_START_NEXT_BATCHED_SCAN:
+                    startNextBatchedScan();
+                    break;
                     /* Discard */
                 case CMD_START_SCAN:
                 case CMD_START_SUPPLICANT:
@@ -2470,6 +2763,10 @@
                 mWifiNative.stopFilteringMulticastV4Packets();
             }
 
+            if (mBatchedScanSettings != null) {
+                startBatchedScan();
+            }
+
             if (mOperationalMode != CONNECT_MODE) {
                 mWifiNative.disconnect();
                 transitionTo(mScanModeState);
@@ -2511,6 +2808,10 @@
                     noteScanStart(message.arg1, (WorkSource) message.obj);
                     startScanNative(WifiNative.SCAN_WITH_CONNECTION_SETUP);
                     break;
+                case CMD_SET_BATCH_SCAN:
+                    recordBatchedScanSettings((BatchedScanSettings)message.obj);
+                    startBatchedScan();
+                    break;
                 case CMD_SET_COUNTRY_CODE:
                     String country = (String) message.obj;
                     if (DBG) log("set country code " + country);
@@ -2639,6 +2940,10 @@
             updateBatteryWorkSource(null);
             mScanResults = new ArrayList<ScanResult>();
 
+            if (mBatchedScanSettings != null) {
+                stopBatchedScan();
+            }
+
             final Intent intent = new Intent(WifiManager.WIFI_SCAN_AVAILABLE);
             intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
             intent.putExtra(WifiManager.EXTRA_SCAN_AVAILABLE, WIFI_STATE_DISABLED);