Merge "Added the new keyword tap for the scripted monkey." into gingerbread
diff --git a/build/sdk.atree b/build/sdk.atree
index f6ba300..e2761d4 100644
--- a/build/sdk.atree
+++ b/build/sdk.atree
@@ -86,6 +86,7 @@
 # (see web_docs_sample_code_flags in frameworks/base/Android.mk)
 development/samples/source.properties        samples/${PLATFORM_NAME}/source.properties
 development/apps/GestureBuilder              samples/${PLATFORM_NAME}/GestureBuilder
+development/samples/AccessibilityService     samples/${PLATFORM_NAME}/AccessibilityService
 development/samples/BluetoothChat            samples/${PLATFORM_NAME}/BluetoothChat
 development/samples/Home                     samples/${PLATFORM_NAME}/Home
 development/samples/LunarLander              samples/${PLATFORM_NAME}/LunarLander
diff --git a/samples/AccelerometerPlay/Android.mk b/samples/AccelerometerPlay/Android.mk
index 4767271..e4b0ab9 100644
--- a/samples/AccelerometerPlay/Android.mk
+++ b/samples/AccelerometerPlay/Android.mk
@@ -25,6 +25,8 @@
 
 LOCAL_SDK_VERSION := current
 
+LOCAL_AAPT_FLAGS = -c 120dpi -c 240dpi -c 160dpi
+
 include $(BUILD_PACKAGE)
 
 # Use the following include to make our test apk.
diff --git a/samples/AccelerometerPlay/src/com/example/android/accelerometerplay/AccelerometerPlayActivity.java b/samples/AccelerometerPlay/src/com/example/android/accelerometerplay/AccelerometerPlayActivity.java
index ed0605c..c9e840f 100644
--- a/samples/AccelerometerPlay/src/com/example/android/accelerometerplay/AccelerometerPlayActivity.java
+++ b/samples/AccelerometerPlay/src/com/example/android/accelerometerplay/AccelerometerPlayActivity.java
@@ -30,7 +30,10 @@
 import android.os.PowerManager;
 import android.os.PowerManager.WakeLock;
 import android.util.DisplayMetrics;
+import android.view.Display;
+import android.view.Surface;
 import android.view.View;
+import android.view.WindowManager;
 
 /**
  * This is an example of using the accelerometer to integrate the device's
@@ -46,405 +49,412 @@
 
 public class AccelerometerPlayActivity extends Activity {
 
-	private SimulationView mSimulationView;
-	private SensorManager mSensorManager;
-	private PowerManager mPowerManager;
-	private WakeLock mWakeLock;
+    private SimulationView mSimulationView;
+    private SensorManager mSensorManager;
+    private PowerManager mPowerManager;
+    private WindowManager mWindowManager;
+    private Display mDisplay;
+    private WakeLock mWakeLock;
 
-	/** Called when the activity is first created. */
-	@Override
-	public void onCreate(Bundle savedInstanceState) {
-		super.onCreate(savedInstanceState);
+    /** Called when the activity is first created. */
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
 
-		// Get an instance of the SensorManager
-		mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
+        // Get an instance of the SensorManager
+        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
 
-		// Get an instance of the PowerManager
-		mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);
+        // Get an instance of the PowerManager
+        mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);
 
-		// Create a bright wake lock
-		mWakeLock = mPowerManager.newWakeLock(
-				PowerManager.SCREEN_BRIGHT_WAKE_LOCK, getClass().getName());
+        // Get an instance of the WindowManager
+        mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
+        mDisplay = mWindowManager.getDefaultDisplay();
 
-		// instantiate our simulation view and set it as the activity's content
-		mSimulationView = new SimulationView(this);
-		setContentView(mSimulationView);
-	}
+        // Create a bright wake lock
+        mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, getClass()
+                .getName());
 
-	@Override
-	protected void onResume() {
-		super.onResume();
-		/*
-		 * when the activity is resumed, we acquire a wake-lock so that the
-		 * screen stays on, since the user will likely not be fiddling with the
-		 * screen or buttons.
-		 */
-		mWakeLock.acquire();
+        // instantiate our simulation view and set it as the activity's content
+        mSimulationView = new SimulationView(this);
+        setContentView(mSimulationView);
+    }
 
-		// Start the simulation
-		mSimulationView.startSimulation();
-	}
+    @Override
+    protected void onResume() {
+        super.onResume();
+        /*
+         * when the activity is resumed, we acquire a wake-lock so that the
+         * screen stays on, since the user will likely not be fiddling with the
+         * screen or buttons.
+         */
+        mWakeLock.acquire();
 
-	@Override
-	protected void onPause() {
-		super.onPause();
-		/*
-		 * When the activity is paused, we make sure to stop the simulation,
-		 * release our sensor resources and wake locks
-		 */
+        // Start the simulation
+        mSimulationView.startSimulation();
+    }
 
-		// Stop the simulation
-		mSimulationView.stopSimulation();
+    @Override
+    protected void onPause() {
+        super.onPause();
+        /*
+         * When the activity is paused, we make sure to stop the simulation,
+         * release our sensor resources and wake locks
+         */
 
-		// and release our wake-lock
-		mWakeLock.release();
-	}
+        // Stop the simulation
+        mSimulationView.stopSimulation();
 
-	class SimulationView extends View implements SensorEventListener {
-		// diameter of the balls in meters
-		private static final float sBallDiameter = 0.004f;
-		private static final float sBallDiameter2 = sBallDiameter
-				* sBallDiameter;
+        // and release our wake-lock
+        mWakeLock.release();
+    }
 
-		// friction of the virtual table and air
-		private static final float sFriction = 0.1f;
+    class SimulationView extends View implements SensorEventListener {
+        // diameter of the balls in meters
+        private static final float sBallDiameter = 0.004f;
+        private static final float sBallDiameter2 = sBallDiameter * sBallDiameter;
 
-		private Sensor mAccelerometer;
-		private long mLastT;
-		private float mLastDeltaT;
+        // friction of the virtual table and air
+        private static final float sFriction = 0.1f;
 
-		private float mXDpi;
-		private float mYDpi;
-		private float mMetersToPixelsX;
-		private float mMetersToPixelsY;
-		private Bitmap mBitmap;
-		private Bitmap mWood;
-		private float mXOrigin;
-		private float mYOrigin;
-		private float mSensorX;
-		private float mSensorY;
-		private long mSensorTimeStamp;
-		private long mCpuTimeStamp;
-		private float mHorizontalBound;
-		private float mVerticalBound;
-		private final ParticleSystem mParticleSystem = new ParticleSystem();
+        private Sensor mAccelerometer;
+        private long mLastT;
+        private float mLastDeltaT;
 
-		/*
-		 * Each of our particle holds its previous and current position, its
-		 * acceleration. for added realism each particle has its own friction
-		 * coefficient.
-		 */
-		class Particle {
-			private float mPosX;
-			private float mPosY;
-			private float mAccelX;
-			private float mAccelY;
-			private float mLastPosX;
-			private float mLastPosY;
-			private float mOneMinusFriction;
+        private float mXDpi;
+        private float mYDpi;
+        private float mMetersToPixelsX;
+        private float mMetersToPixelsY;
+        private Bitmap mBitmap;
+        private Bitmap mWood;
+        private float mXOrigin;
+        private float mYOrigin;
+        private float mSensorX;
+        private float mSensorY;
+        private long mSensorTimeStamp;
+        private long mCpuTimeStamp;
+        private float mHorizontalBound;
+        private float mVerticalBound;
+        private final ParticleSystem mParticleSystem = new ParticleSystem();
 
-			Particle() {
-				// make each particle a bit different by randomizing its
-				// coefficient of friction
-				final float r = ((float) Math.random() - 0.5f) * 0.2f;
-				mOneMinusFriction = 1.0f - sFriction + r;
-			}
+        /*
+         * Each of our particle holds its previous and current position, its
+         * acceleration. for added realism each particle has its own friction
+         * coefficient.
+         */
+        class Particle {
+            private float mPosX;
+            private float mPosY;
+            private float mAccelX;
+            private float mAccelY;
+            private float mLastPosX;
+            private float mLastPosY;
+            private float mOneMinusFriction;
 
-			public void computePhysics(float sx, float sy, float dT, float dTC) {
-				// Force of gravity applied to our virtual object
-				final float m = 1000.0f; // mass of our virtual object
-				final float gx = -sx * m;
-				final float gy = -sy * m;
+            Particle() {
+                // make each particle a bit different by randomizing its
+                // coefficient of friction
+                final float r = ((float) Math.random() - 0.5f) * 0.2f;
+                mOneMinusFriction = 1.0f - sFriction + r;
+            }
 
-				/*
-				 * ·F = mA <=> A = ·F / m
-				 * 
-				 * We could simplify the code by completely eliminating "m" (the
-				 * mass) from all the equations, but it would hide the concepts
-				 * from this sample code.
-				 */
-				final float invm = 1.0f / m;
-				final float ax = gx * invm;
-				final float ay = gy * invm;
+            public void computePhysics(float sx, float sy, float dT, float dTC) {
+                // Force of gravity applied to our virtual object
+                final float m = 1000.0f; // mass of our virtual object
+                final float gx = -sx * m;
+                final float gy = -sy * m;
 
-				/*
-				 * Time-corrected Verlet integration
-				 * 
-				 * The position Verlet integrator is defined as
-				 * 
-				 * x(t+Æt) = x(t) + x(t) - x(t-Æt) + a(t)Ætö2
-				 * 
-				 * However, the above equation doesn't handle variable Æt very
-				 * well, a time-corrected version is needed:
-				 * 
-				 * x(t+Æt) = x(t) + (x(t) - x(t-Æt)) * (Æt/Æt_prev) + a(t)Ætö2
-				 * 
-				 * 
-				 * We also add a simple friction term (f) to the equation:
-				 * 
-				 * x(t+Æt) = x(t) + (1-f) * (x(t) - x(t-Æt)) * (Æt/Æt_prev) +
-				 * a(t)Ætö2
-				 */
-				final float dTdT = dT * dT;
-				final float x = mPosX + mOneMinusFriction * dTC
-						* (mPosX - mLastPosX) + mAccelX * dTdT;
-				final float y = mPosY + mOneMinusFriction * dTC
-						* (mPosY - mLastPosY) + mAccelY * dTdT;
-				mLastPosX = mPosX;
-				mLastPosY = mPosY;
-				mPosX = x;
-				mPosY = y;
-				mAccelX = ax;
-				mAccelY = ay;
-			}
+                /*
+                 * ·F = mA <=> A = ·F / m We could simplify the code by
+                 * completely eliminating "m" (the mass) from all the equations,
+                 * but it would hide the concepts from this sample code.
+                 */
+                final float invm = 1.0f / m;
+                final float ax = gx * invm;
+                final float ay = gy * invm;
 
-			/*
-			 * Resolving constraints and collisions with the Verlet integrator
-			 * can be very simple, we simply need to move a colliding or
-			 * constrained particle in such way that the constraint is
-			 * satisfied.
-			 */
-			public void resolveCollisionWithBounds() {
-				final float xmax = mHorizontalBound;
-				final float ymax = mVerticalBound;
-				final float x = mPosX;
-				final float y = mPosY;
-				if (x > xmax) {
-					mPosX = xmax;
-				} else if (x < -xmax) {
-					mPosX = -xmax;
-				}
-				if (y > ymax) {
-					mPosY = ymax;
-				} else if (y < -ymax) {
-					mPosY = -ymax;
-				}
-			}
-		}
+                /*
+                 * Time-corrected Verlet integration The position Verlet
+                 * integrator is defined as x(t+Æt) = x(t) + x(t) - x(t-Æt) +
+                 * a(t)Ætö2 However, the above equation doesn't handle variable
+                 * Æt very well, a time-corrected version is needed: x(t+Æt) =
+                 * x(t) + (x(t) - x(t-Æt)) * (Æt/Æt_prev) + a(t)Ætö2 We also add
+                 * a simple friction term (f) to the equation: x(t+Æt) = x(t) +
+                 * (1-f) * (x(t) - x(t-Æt)) * (Æt/Æt_prev) + a(t)Ætö2
+                 */
+                final float dTdT = dT * dT;
+                final float x = mPosX + mOneMinusFriction * dTC * (mPosX - mLastPosX) + mAccelX
+                        * dTdT;
+                final float y = mPosY + mOneMinusFriction * dTC * (mPosY - mLastPosY) + mAccelY
+                        * dTdT;
+                mLastPosX = mPosX;
+                mLastPosY = mPosY;
+                mPosX = x;
+                mPosY = y;
+                mAccelX = ax;
+                mAccelY = ay;
+            }
 
-		/*
-		 * A particle system is just a collection of particles
-		 */
-		class ParticleSystem {
-			static final int NUM_PARTICLES = 15;
-			private Particle mBalls[] = new Particle[NUM_PARTICLES];
+            /*
+             * Resolving constraints and collisions with the Verlet integrator
+             * can be very simple, we simply need to move a colliding or
+             * constrained particle in such way that the constraint is
+             * satisfied.
+             */
+            public void resolveCollisionWithBounds() {
+                final float xmax = mHorizontalBound;
+                final float ymax = mVerticalBound;
+                final float x = mPosX;
+                final float y = mPosY;
+                if (x > xmax) {
+                    mPosX = xmax;
+                } else if (x < -xmax) {
+                    mPosX = -xmax;
+                }
+                if (y > ymax) {
+                    mPosY = ymax;
+                } else if (y < -ymax) {
+                    mPosY = -ymax;
+                }
+            }
+        }
 
-			ParticleSystem() {
-				/*
-				 * Initially our particles have no speed or acceleration
-				 */
-				for (int i = 0; i < mBalls.length; i++) {
-					mBalls[i] = new Particle();
-				}
-			}
+        /*
+         * A particle system is just a collection of particles
+         */
+        class ParticleSystem {
+            static final int NUM_PARTICLES = 15;
+            private Particle mBalls[] = new Particle[NUM_PARTICLES];
 
-			/*
-			 * Update the position of each particle in the system using the
-			 * Verlet integrator.
-			 */
-			private void updatePositions(float sx, float sy, long timestamp) {
-				final long t = timestamp;
-				if (mLastT != 0) {
-					final float dT = (float) (t - mLastT)
-							* (1.0f / 1000000000.0f);
-					if (mLastDeltaT != 0) {
-						final float dTC = dT / mLastDeltaT;
-						final int count = mBalls.length;
-						for (int i = 0; i < count; i++) {
-							Particle ball = mBalls[i];
-							ball.computePhysics(sx, sy, dT, dTC);
-						}
-					}
-					mLastDeltaT = dT;
-				}
-				mLastT = t;
-			}
+            ParticleSystem() {
+                /*
+                 * Initially our particles have no speed or acceleration
+                 */
+                for (int i = 0; i < mBalls.length; i++) {
+                    mBalls[i] = new Particle();
+                }
+            }
 
-			/*
-			 * Performs one iteration of the simulation. First updating the
-			 * position of all the particles and resolving the constraints and
-			 * collisions.
-			 */
-			public void update(float sx, float sy, long now) {
-				// update the system's positions
-				updatePositions(sx, sy, now);
+            /*
+             * Update the position of each particle in the system using the
+             * Verlet integrator.
+             */
+            private void updatePositions(float sx, float sy, long timestamp) {
+                final long t = timestamp;
+                if (mLastT != 0) {
+                    final float dT = (float) (t - mLastT) * (1.0f / 1000000000.0f);
+                    if (mLastDeltaT != 0) {
+                        final float dTC = dT / mLastDeltaT;
+                        final int count = mBalls.length;
+                        for (int i = 0; i < count; i++) {
+                            Particle ball = mBalls[i];
+                            ball.computePhysics(sx, sy, dT, dTC);
+                        }
+                    }
+                    mLastDeltaT = dT;
+                }
+                mLastT = t;
+            }
 
-				// We do no more than a limited number of iterations
-				final int NUM_MAX_ITERATIONS = 10;
+            /*
+             * Performs one iteration of the simulation. First updating the
+             * position of all the particles and resolving the constraints and
+             * collisions.
+             */
+            public void update(float sx, float sy, long now) {
+                // update the system's positions
+                updatePositions(sx, sy, now);
 
-				/*
-				 * Resolve collisions, each particle is tested against every
-				 * other particle for collision. If a collision is detected the
-				 * particle is moved away using a virtual spring of infinite
-				 * stiffness.
-				 */
-				boolean more = true;
-				final int count = mBalls.length;
-				for (int k = 0; k < NUM_MAX_ITERATIONS && more; k++) {
-					more = false;
-					for (int i = 0; i < count; i++) {
-						Particle curr = mBalls[i];
-						for (int j = i + 1; j < count; j++) {
-							Particle ball = mBalls[j];
-							float dx = ball.mPosX - curr.mPosX;
-							float dy = ball.mPosY - curr.mPosY;
-							float dd = dx * dx + dy * dy;
-							// Check for collisions
-							if (dd <= sBallDiameter2) {
-								/*
-								 * add a little bit of entropy, after nothing is
-								 * perfect in the universe.
-								 */
-								dx += ((float) Math.random() - 0.5f) * 0.0001f;
-								dy += ((float) Math.random() - 0.5f) * 0.0001f;
-								dd = dx * dx + dy * dy;
-								// simulate the spring
-								final float d = (float) Math.sqrt(dd);
-								final float c = (0.5f * (sBallDiameter - d))
-										/ d;
-								curr.mPosX -= dx * c;
-								curr.mPosY -= dy * c;
-								ball.mPosX += dx * c;
-								ball.mPosY += dy * c;
-								more = true;
-							}
-						}
-						/*
-						 * Finally make sure the particle doesn't intersects
-						 * with the walls.
-						 */
-						curr.resolveCollisionWithBounds();
-					}
-				}
-			}
+                // We do no more than a limited number of iterations
+                final int NUM_MAX_ITERATIONS = 10;
 
-			public int getParticleCount() {
-				return mBalls.length;
-			}
+                /*
+                 * Resolve collisions, each particle is tested against every
+                 * other particle for collision. If a collision is detected the
+                 * particle is moved away using a virtual spring of infinite
+                 * stiffness.
+                 */
+                boolean more = true;
+                final int count = mBalls.length;
+                for (int k = 0; k < NUM_MAX_ITERATIONS && more; k++) {
+                    more = false;
+                    for (int i = 0; i < count; i++) {
+                        Particle curr = mBalls[i];
+                        for (int j = i + 1; j < count; j++) {
+                            Particle ball = mBalls[j];
+                            float dx = ball.mPosX - curr.mPosX;
+                            float dy = ball.mPosY - curr.mPosY;
+                            float dd = dx * dx + dy * dy;
+                            // Check for collisions
+                            if (dd <= sBallDiameter2) {
+                                /*
+                                 * add a little bit of entropy, after nothing is
+                                 * perfect in the universe.
+                                 */
+                                dx += ((float) Math.random() - 0.5f) * 0.0001f;
+                                dy += ((float) Math.random() - 0.5f) * 0.0001f;
+                                dd = dx * dx + dy * dy;
+                                // simulate the spring
+                                final float d = (float) Math.sqrt(dd);
+                                final float c = (0.5f * (sBallDiameter - d)) / d;
+                                curr.mPosX -= dx * c;
+                                curr.mPosY -= dy * c;
+                                ball.mPosX += dx * c;
+                                ball.mPosY += dy * c;
+                                more = true;
+                            }
+                        }
+                        /*
+                         * Finally make sure the particle doesn't intersects
+                         * with the walls.
+                         */
+                        curr.resolveCollisionWithBounds();
+                    }
+                }
+            }
 
-			public float getPosX(int i) {
-				return mBalls[i].mPosX;
-			}
+            public int getParticleCount() {
+                return mBalls.length;
+            }
 
-			public float getPosY(int i) {
-				return mBalls[i].mPosY;
-			}
-		}
+            public float getPosX(int i) {
+                return mBalls[i].mPosX;
+            }
 
-		public void startSimulation() {
-			/*
-			 * It is not necessary to get accelerometer events at a very high
-			 * rate, by using a slower rate (SENSOR_DELAY_UI), we get an
-			 * automatic low-pass filter, which "extracts" the gravity component
-			 * of the acceleration. As an added benefit, we use less power and
-			 * CPU resources.
-			 */
-			mSensorManager.registerListener(this, mAccelerometer,
-					SensorManager.SENSOR_DELAY_UI);
-		}
+            public float getPosY(int i) {
+                return mBalls[i].mPosY;
+            }
+        }
 
-		public void stopSimulation() {
-			mSensorManager.unregisterListener(this);
-		}
+        public void startSimulation() {
+            /*
+             * It is not necessary to get accelerometer events at a very high
+             * rate, by using a slower rate (SENSOR_DELAY_UI), we get an
+             * automatic low-pass filter, which "extracts" the gravity component
+             * of the acceleration. As an added benefit, we use less power and
+             * CPU resources.
+             */
+            mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
+        }
 
-		public SimulationView(Context context) {
-			super(context);
-			mAccelerometer = mSensorManager
-					.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
+        public void stopSimulation() {
+            mSensorManager.unregisterListener(this);
+        }
 
-			DisplayMetrics metrics = new DisplayMetrics();
-			getWindowManager().getDefaultDisplay().getMetrics(metrics);
-			mXDpi = metrics.xdpi;
-			mYDpi = metrics.ydpi;
-			mMetersToPixelsX = mXDpi / 0.0254f;
-			mMetersToPixelsY = mYDpi / 0.0254f;
+        public SimulationView(Context context) {
+            super(context);
+            mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
 
-			// rescale the ball so it's about 0.5 cm on screen
-			Bitmap ball = BitmapFactory.decodeResource(getResources(),
-					R.drawable.ball);
-			final int dstWidth = (int) (sBallDiameter * mMetersToPixelsX + 0.5f);
-			final int dstHeight = (int) (sBallDiameter * mMetersToPixelsY + 0.5f);
-			mBitmap = Bitmap
-					.createScaledBitmap(ball, dstWidth, dstHeight, true);
+            DisplayMetrics metrics = new DisplayMetrics();
+            getWindowManager().getDefaultDisplay().getMetrics(metrics);
+            mXDpi = metrics.xdpi;
+            mYDpi = metrics.ydpi;
+            mMetersToPixelsX = mXDpi / 0.0254f;
+            mMetersToPixelsY = mYDpi / 0.0254f;
 
-			Options opts = new Options();
-			opts.inDither = true;
-			opts.inPreferredConfig = Bitmap.Config.RGB_565;
-			mWood = BitmapFactory.decodeResource(getResources(),
-					R.drawable.wood, opts);
-		}
+            // rescale the ball so it's about 0.5 cm on screen
+            Bitmap ball = BitmapFactory.decodeResource(getResources(), R.drawable.ball);
+            final int dstWidth = (int) (sBallDiameter * mMetersToPixelsX + 0.5f);
+            final int dstHeight = (int) (sBallDiameter * mMetersToPixelsY + 0.5f);
+            mBitmap = Bitmap.createScaledBitmap(ball, dstWidth, dstHeight, true);
 
-		@Override
-		protected void onSizeChanged(int w, int h, int oldw, int oldh) {
-			// compute the origin of the screen relative to the origin of
-			// the bitmap
-			mXOrigin = (w - mBitmap.getWidth()) * 0.5f;
-			mYOrigin = (h - mBitmap.getHeight()) * 0.5f;
-			mHorizontalBound = ((w / mMetersToPixelsX - sBallDiameter) * 0.5f);
-			mVerticalBound = ((h / mMetersToPixelsY - sBallDiameter) * 0.5f);
-		}
+            Options opts = new Options();
+            opts.inDither = true;
+            opts.inPreferredConfig = Bitmap.Config.RGB_565;
+            mWood = BitmapFactory.decodeResource(getResources(), R.drawable.wood, opts);
+        }
 
-		@Override
-		public void onSensorChanged(SensorEvent event) {
-			if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER)
-				return;
-			/*
-			 * record the accelerometer data, the event's timestamp as well as
-			 * the current time. The latter is needed so we can calculate the
-			 * "present" time during rendering.
-			 */
-			mSensorX = event.values[0];
-			mSensorY = event.values[1];
-			mSensorTimeStamp = event.timestamp;
-			mCpuTimeStamp = System.nanoTime();
-		}
+        @Override
+        protected void onSizeChanged(int w, int h, int oldw, int oldh) {
+            // compute the origin of the screen relative to the origin of
+            // the bitmap
+            mXOrigin = (w - mBitmap.getWidth()) * 0.5f;
+            mYOrigin = (h - mBitmap.getHeight()) * 0.5f;
+            mHorizontalBound = ((w / mMetersToPixelsX - sBallDiameter) * 0.5f);
+            mVerticalBound = ((h / mMetersToPixelsY - sBallDiameter) * 0.5f);
+        }
 
-		@Override
-		protected void onDraw(Canvas canvas) {
+        @Override
+        public void onSensorChanged(SensorEvent event) {
+            if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER)
+                return;
+            /*
+             * record the accelerometer data, the event's timestamp as well as
+             * the current time. The latter is needed so we can calculate the
+             * "present" time during rendering. In this application, we need to
+             * take into account how the screen is rotated with respect to the
+             * sensors (which always return data in a coordinate space aligned
+             * to with the screen in its native orientation).
+             */
 
-			/*
-			 * draw the background
-			 */
+            switch (mDisplay.getRotation()) {
+                case Surface.ROTATION_0:
+                    mSensorX = event.values[0];
+                    mSensorY = event.values[1];
+                    break;
+                case Surface.ROTATION_90:
+                    mSensorX = -event.values[1];
+                    mSensorY = event.values[0];
+                    break;
+                case Surface.ROTATION_180:
+                    mSensorX = -event.values[0];
+                    mSensorY = -event.values[1];
+                    break;
+                case Surface.ROTATION_270:
+                    mSensorX = event.values[1];
+                    mSensorY = -event.values[0];
+                    break;
+            }
 
-			canvas.drawBitmap(mWood, 0, 0, null);
+            mSensorTimeStamp = event.timestamp;
+            mCpuTimeStamp = System.nanoTime();
+        }
 
-			/*
-			 * compute the new position of our object, based on accelerometer
-			 * data and present time.
-			 */
+        @Override
+        protected void onDraw(Canvas canvas) {
 
-			final ParticleSystem particleSystem = mParticleSystem;
-			final long now = mSensorTimeStamp
-					+ (System.nanoTime() - mCpuTimeStamp);
-			final float sx = mSensorX;
-			final float sy = mSensorY;
+            /*
+             * draw the background
+             */
 
-			particleSystem.update(sx, sy, now);
+            canvas.drawBitmap(mWood, 0, 0, null);
 
-			final float xc = mXOrigin;
-			final float yc = mYOrigin;
-			final float xs = mMetersToPixelsX;
-			final float ys = mMetersToPixelsY;
-			final Bitmap bitmap = mBitmap;
-			final int count = particleSystem.getParticleCount();
-			for (int i = 0; i < count; i++) {
-				/*
-				 * We transform the canvas so that the coordinate system matches
-				 * the sensors coordinate system with the origin in the center
-				 * of the screen and the unit is the meter.
-				 */
+            /*
+             * compute the new position of our object, based on accelerometer
+             * data and present time.
+             */
 
-				final float x = xc + particleSystem.getPosX(i) * xs;
-				final float y = yc - particleSystem.getPosY(i) * ys;
-				canvas.drawBitmap(bitmap, x, y, null);
-			}
+            final ParticleSystem particleSystem = mParticleSystem;
+            final long now = mSensorTimeStamp + (System.nanoTime() - mCpuTimeStamp);
+            final float sx = mSensorX;
+            final float sy = mSensorY;
 
-			// and make sure to redraw asap
-			invalidate();
-		}
+            particleSystem.update(sx, sy, now);
 
-		@Override
-		public void onAccuracyChanged(Sensor sensor, int accuracy) {
-		}
-	}
+            final float xc = mXOrigin;
+            final float yc = mYOrigin;
+            final float xs = mMetersToPixelsX;
+            final float ys = mMetersToPixelsY;
+            final Bitmap bitmap = mBitmap;
+            final int count = particleSystem.getParticleCount();
+            for (int i = 0; i < count; i++) {
+                /*
+                 * We transform the canvas so that the coordinate system matches
+                 * the sensors coordinate system with the origin in the center
+                 * of the screen and the unit is the meter.
+                 */
+
+                final float x = xc + particleSystem.getPosX(i) * xs;
+                final float y = yc - particleSystem.getPosY(i) * ys;
+                canvas.drawBitmap(bitmap, x, y, null);
+            }
+
+            // and make sure to redraw asap
+            invalidate();
+        }
+
+        @Override
+        public void onAccuracyChanged(Sensor sensor, int accuracy) {
+        }
+    }
 }
diff --git a/samples/AccessibilityService/Android.mk b/samples/AccessibilityService/Android.mk
new file mode 100644
index 0000000..e47b6f6
--- /dev/null
+++ b/samples/AccessibilityService/Android.mk
@@ -0,0 +1,12 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := samples
+
+LOCAL_SRC_FILES := $(call all-subdir-java-files)
+
+LOCAL_PACKAGE_NAME := AccessibilityService
+
+LOCAL_SDK_VERSION := current
+
+include $(BUILD_PACKAGE)
diff --git a/samples/AccessibilityService/AndroidManifest.xml b/samples/AccessibilityService/AndroidManifest.xml
new file mode 100644
index 0000000..1b5f794
--- /dev/null
+++ b/samples/AccessibilityService/AndroidManifest.xml
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<!-- Copyright (C) 2010 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+      package="com.example.android.clockback"
+      android:versionCode="1"
+      android:versionName="1.0">
+
+    <uses-permission android:name="android.permission.VIBRATE" />
+
+    <application android:label="@string/clockback_setup_title">
+
+        <!-- We declare our service here -->
+        <service android:name=".ClockBackService">
+            <!-- This intent filter is a clue for the system that this is an accessibility service -->
+            <intent-filter>
+                <action android:name="android.accessibilityservice.AccessibilityService" />
+            </intent-filter>
+        </service>
+
+    </application>
+
+    <!-- Accessibility API appeared in SDK version 4 (Android 1.6) -->
+    <uses-sdk android:minSdkVersion="4" />
+
+</manifest>
diff --git a/samples/AccessibilityService/_index.html b/samples/AccessibilityService/_index.html
new file mode 100644
index 0000000..d6adbf2
--- /dev/null
+++ b/samples/AccessibilityService/_index.html
@@ -0,0 +1,120 @@
+<p>
+  This is an example of an accessibility service that provides custom feedback for the Clock application which comes by default with Android devices. It demonstrates the following key features of the Android accessibility APIs:
+</p>
+<ol>
+  <li>
+    Simple demonstration of how to use the accessibility APIs.
+  </li>
+  <li>
+    Hands-on example of various ways to utilize the accessibility API for providing alternative and complementary feedback.
+  </li>
+  <li>
+    Providing application specific feedback &mdash; the service handles only accessibility events from the Clock application.
+  </li>
+  <li>
+    Providing dynamic, context-dependent feedback &mdash; feedback type changes depending on the ringer mode.
+  </li>
+  <li>
+    Application specific UI enhancement &mdash; application domain knowledge is utilized to enhance the provided feedback.
+  </li>
+</ol>
+<p>
+  <strong>
+    Note: This code sample will work only on devices shipped with the default Clock application. If you are
+    running Android 1.6 of Android 2.0 you should enable first ClockBack and then TalkBack since in these
+    releases accessibility services are notified in the order of registration.
+  </strong>
+</p>
+<p>
+  Steps to exercise the ClockBack example:
+</p>
+<ol>
+  <li>
+    <ul>
+      <li>
+        <strong>Action:</strong> Enable accessibility and all default accessibility services:<br/>
+        Settings &rarr; Accessibility &rarr; select the Accessibility, TalkBack, KickBack, and SoundBack checkboxes
+      </li>
+      <li>
+        <strong>Result:</strong> The system provides spoken, audible, and haptic feedback.
+      </li>
+    </ul>
+  </li>
+  <li>
+    <ul>
+      <li>
+        <strong>Action:</strong> Explore the feedback provided by the system:<br/>
+        Poke around with the trackball.
+      </li>
+      <li>
+        <strong>Result:</strong> You are somehow familiar with the type of the provided feedback.
+      </li>
+    </ul>
+  </li>
+  <li>
+    <ul>
+      <li>
+        <strong>Action:</strong> Go to the Clock application and try to change the time of an alarm:<br/>
+        All applications &rarr; Clock &rarr; Alarms (left corner) &rarr; Select an alarm &rarr; Time &mdash; explore the plus, minus buttons, hour and minute edit boxes.
+      </li>
+      <li>
+        <strong>Result:</strong> The hour and minute edit boxes are announced without any clue which is the hour and which is the minute one (you can guess from the arrangement).
+      </li>
+    </ul>
+  </li>
+  <li>
+    <ul>
+      <li>
+        <strong>Action:</strong> Enable ClockBack:<br>
+        Settings &rarr; Accessibility &rarr; ClockBack &mdash; select the checkbox (assuming you have installed the APK).
+      </li>
+      <li>
+        <strong>Result:</strong> We have active accessibility service for providing application specific feedback for the Clock application.
+      </li>
+    </ul>
+  </li>
+  <li>
+    <ul>
+      <li>
+        <strong>Action:</strong> Go to the Clock application and try to change the time of an alarm:<br/>
+        All applications &rarr; Clock &rarr; Alarms (left corner) &rarr; Select an alarm &rarr; Time &mdash; explore the hour and minute edit boxes.
+      </li>
+      <li>
+        <strong>Result:</strong> The hour and minute edit boxes are now spoken. This is an example of application specific feedback that utilizes domain information to enhance the user experience.
+      </li>
+    </ul>
+  </li>
+  <li>
+    <ul>
+      <li>
+        <strong>Action:</strong> Set the ringer to vibration mode and explore the provided feedback:<br/>
+        Use the device button for reducing the ringer volume until it is in vibration mode. Move around the Clock application and outside of that application.
+      </li>
+      <li>
+        <strong>Result:</strong> The Clock application provides custom audible and default haptic feedback. The rest of the system provides the default feedback.
+      </li>
+    </ul>
+  </li>
+  <li>
+    <ul>
+      <li>
+        <strong>Action:</strong> Set the ringer to muted mode and explore the provided feedback:<br/>
+        Use the device button for reducing the ringer volume until it is in muted mode. Move around the Clock application and outside of that application.
+      </li>
+      <li>
+        <strong>Result:</strong> The Clock application provides only custom haptic feedback. The rest of the system provides the default feedback. Now we are providing custom context dependent feedback based on the device state (ringer mode).
+      </li>
+    </ul>
+  </li>
+  <li>
+    <ul>
+      <li>
+        <strong>Action:</strong> Write an accessibility service:<br/>
+        The <a href="http://code.google.com/p/eyes-free/">Eyes-Free open source project</a> has more accessibility-related resources. To contribute, visit the project page or post to the <a href="http://groups.google.com/group/eyes-free">mailing list</a>.
+      </li>
+      <li>
+        <strong>Result:</strong> One more cool application has been written.
+      </li>
+    </ul>
+  </li>
+</ol>
diff --git a/samples/AccessibilityService/res/raw/sound_ringer_normal.ogg b/samples/AccessibilityService/res/raw/sound_ringer_normal.ogg
new file mode 100644
index 0000000..959e398
--- /dev/null
+++ b/samples/AccessibilityService/res/raw/sound_ringer_normal.ogg
Binary files differ
diff --git a/samples/AccessibilityService/res/raw/sound_ringer_silent.ogg b/samples/AccessibilityService/res/raw/sound_ringer_silent.ogg
new file mode 100644
index 0000000..d3bb25e
--- /dev/null
+++ b/samples/AccessibilityService/res/raw/sound_ringer_silent.ogg
Binary files differ
diff --git a/samples/AccessibilityService/res/raw/sound_ringer_vibrate.ogg b/samples/AccessibilityService/res/raw/sound_ringer_vibrate.ogg
new file mode 100644
index 0000000..761e10f
--- /dev/null
+++ b/samples/AccessibilityService/res/raw/sound_ringer_vibrate.ogg
Binary files differ
diff --git a/samples/AccessibilityService/res/raw/sound_screen_off.ogg b/samples/AccessibilityService/res/raw/sound_screen_off.ogg
new file mode 100644
index 0000000..342733a
--- /dev/null
+++ b/samples/AccessibilityService/res/raw/sound_screen_off.ogg
Binary files differ
diff --git a/samples/AccessibilityService/res/raw/sound_screen_on.ogg b/samples/AccessibilityService/res/raw/sound_screen_on.ogg
new file mode 100644
index 0000000..bf3632e
--- /dev/null
+++ b/samples/AccessibilityService/res/raw/sound_screen_on.ogg
Binary files differ
diff --git a/samples/AccessibilityService/res/raw/sound_view_clicked.ogg b/samples/AccessibilityService/res/raw/sound_view_clicked.ogg
new file mode 100644
index 0000000..3fe25cf
--- /dev/null
+++ b/samples/AccessibilityService/res/raw/sound_view_clicked.ogg
Binary files differ
diff --git a/samples/AccessibilityService/res/raw/sound_view_focused_or_selected.ogg b/samples/AccessibilityService/res/raw/sound_view_focused_or_selected.ogg
new file mode 100644
index 0000000..0100d27
--- /dev/null
+++ b/samples/AccessibilityService/res/raw/sound_view_focused_or_selected.ogg
Binary files differ
diff --git a/samples/AccessibilityService/res/raw/sound_window_state_changed.ogg b/samples/AccessibilityService/res/raw/sound_window_state_changed.ogg
new file mode 100644
index 0000000..0fec9de
--- /dev/null
+++ b/samples/AccessibilityService/res/raw/sound_window_state_changed.ogg
Binary files differ
diff --git a/samples/AccessibilityService/res/values/strings.xml b/samples/AccessibilityService/res/values/strings.xml
new file mode 100644
index 0000000..a9913c2
--- /dev/null
+++ b/samples/AccessibilityService/res/values/strings.xml
@@ -0,0 +1,50 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+
+    <!-- VALUES -->
+
+    <!-- Setting up the user interface vibration feedback service -->
+    <string name="clockback_setup_title">ClockBack</string>
+
+    <!-- String value for announcing the increase hours buttons -->
+    <string name="value_increase_hours">Increase hours</string>
+
+    <!-- String value for announcing the increase minutes buttons -->
+    <string name="value_increase_minutes">Increase minutes</string>
+
+    <!-- String value for announcing the decrease hours buttons -->
+    <string name="value_decrease_hours">Decrease hours</string>
+
+    <!-- String value for announcing the decrease minutes buttons -->
+    <string name="value_decrease_minutes">Decrease minutes</string>
+
+    <!-- String value for announcing one hour input -->
+    <string name="value_hour">hour</string>
+
+    <!-- String value for announcing the hours input -->
+    <string name="value_hours">hours</string>
+
+    <!-- String value for announcing one minute input -->
+    <string name="value_minute">minute</string>
+
+    <!-- String value for announcing the minutes input -->
+    <string name="value_minutes">minutes</string>
+
+    <!-- String value for announcing audible ringer mode -->
+    <string name="value_ringer_audible">Ringer audible</string>
+
+    <!-- String value for announcing vibrating ringer mode -->
+    <string name="value_ringer_vibrate">Ringer vibrate</string>
+
+    <!-- String value for announcing silent ringer mode-->
+    <string name="value_ringer_silent">Ringer silent</string>
+
+    <!-- TEMPLATES -->
+
+    <!-- String template for announcing the screen on -->
+    <string name="template_screen_on">Screen on. Volume %1$s percent.</string>
+
+    <!-- String template for announcing the screen off -->
+    <string name="template_screen_off">Screen off. Volume %1$s percent.</string>
+
+</resources>
diff --git a/samples/AccessibilityService/src/com/example/android/clockback/ClockBackService.java b/samples/AccessibilityService/src/com/example/android/clockback/ClockBackService.java
new file mode 100644
index 0000000..5746716
--- /dev/null
+++ b/samples/AccessibilityService/src/com/example/android/clockback/ClockBackService.java
@@ -0,0 +1,701 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.example.android.clockback;
+
+import android.accessibilityservice.AccessibilityService;
+import android.accessibilityservice.AccessibilityServiceInfo;
+import android.app.Service;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.media.AudioManager;
+import android.os.Handler;
+import android.os.Message;
+import android.os.Vibrator;
+import android.speech.tts.TextToSpeech;
+import android.util.Log;
+import android.util.SparseArray;
+import android.view.accessibility.AccessibilityEvent;
+
+import java.util.List;
+
+/**
+ * This class is an {@link AccessibilityService} that provides custom feedback
+ * for the Clock application that comes by default with Android devices. It
+ * demonstrates the following key features of the Android accessibility APIs:
+ * <ol>
+ *   <li>
+ *     Simple demonstration of how to use the accessibility APIs.
+ *   </li>
+ *   <li>
+ *     Hands-on example of various ways to utilize the accessibility API for
+ *     providing alternative and complementary feedback.
+ *   </li>
+ *   <li>
+ *     Providing application specific feedback &mdash; the service handles only
+ *     accessibility events from the clock application.
+ *   </li>
+ *   <li>
+ *     Providing dynamic, context-dependent feedback &mdash; feedback type changes
+ *     depending on the ringer state.
+ *   </li>
+ *   <li>
+ *     Application specific UI enhancement - application domain knowledge is
+ *     utilized to enhance the provided feedback.
+ *   </li>
+ * </ol>
+ * <p>
+ *   <strong>
+ *     Note: This code sample will work only on devices shipped with the default Clock
+ *     application. If you are running Android 1.6 of Android 2.0 you should enable first
+ *     ClockBack and then TalkBack since in these releases accessibility services are
+ *     notified in the order of registration.
+ *   </strong>
+ * </p>
+ */
+public class ClockBackService extends AccessibilityService {
+
+    /** Tag for logging from this service. */
+    private static final String LOG_TAG = "ClockBackService";
+
+    // Fields for configuring how the system handles this accessibility service.
+
+    /** Minimal timeout between accessibility events we want to receive. */
+    private static final int EVENT_NOTIFICATION_TIMEOUT_MILLIS = 80;
+
+    /** Packages we are interested in.
+     * <p>
+     *   <strong>
+     *   Note: This code sample will work only on devices shipped with the
+     *   default Clock application.
+     *   </strong>
+     * </p>
+     */
+    // This works with AlarmClock and Clock whose package name changes in different releases
+    private static final String[] PACKAGE_NAMES = new String[] {
+            "com.android.alarmclock", "com.google.android.deskclock", "com.android.deskclock"
+    };
+
+    // Message types we are passing around.
+
+    /** Speak. */
+    private static final int MESSAGE_SPEAK = 1;
+
+    /** Stop speaking. */
+    private static final int MESSAGE_STOP_SPEAK = 2;
+
+    /** Start the TTS service. */
+    private static final int MESSAGE_START_TTS = 3;
+
+    /** Stop the TTS service. */
+    private static final int MESSAGE_SHUTDOWN_TTS = 4;
+
+    /** Play an earcon. */
+    private static final int MESSAGE_PLAY_EARCON = 5;
+
+    /** Stop playing an earcon. */
+    private static final int MESSAGE_STOP_PLAY_EARCON = 6;
+
+    /** Vibrate a pattern. */
+    private static final int MESSAGE_VIBRATE = 7;
+
+    /** Stop vibrating. */
+    private static final int MESSAGE_STOP_VIBRATE = 8;
+
+    // Screen state broadcast related constants.
+
+    /** Feedback mapping index used as a key for the screen-on broadcast. */
+    private static final int INDEX_SCREEN_ON = 0x00000100;
+
+    /** Feedback mapping index used as a key for the screen-off broadcast. */
+    private static final int INDEX_SCREEN_OFF = 0x00000200;
+
+    // Ringer mode change related constants.
+
+    /** Feedback mapping index used as a key for normal ringer mode. */
+    private static final int INDEX_RINGER_NORMAL = 0x00000400;
+
+    /** Feedback mapping index used as a key for vibration ringer mode. */
+    private static final int INDEX_RINGER_VIBRATE = 0x00000800;
+
+    /** Feedback mapping index used as a key for silent ringer mode. */
+    private static final int INDEX_RINGER_SILENT = 0x00001000;
+
+    // Speech related constants.
+
+    /**
+     * The queuing mode we are using - interrupt a spoken utterance before
+     * speaking another one.
+     */
+    private static final int QUEUING_MODE_INTERRUPT = 2;
+
+    /** The space string constant. */
+    private static final String SPACE = " ";
+
+    /**
+     * The class name of the number picker buttons with no text we want to
+     * announce in the Clock application.
+     */
+    private static final String CLASS_NAME_NUMBER_PICKER_BUTTON_CLOCK = "android.widget.NumberPickerButton";
+
+    /**
+     * The class name of the number picker buttons with no text we want to
+     * announce in the AlarmClock application.
+     */
+    private static final String CLASS_NAME_NUMBER_PICKER_BUTTON_ALARM_CLOCK = "com.android.internal.widget.NumberPickerButton";
+
+    /**
+     * The class name of the edit text box for hours and minutes we want to
+     * better announce.
+     */
+    private static final String CLASS_NAME_EDIT_TEXT = "android.widget.EditText";
+
+    /**
+     * Mapping from integer to string resource id where the keys are generated
+     * from the {@link AccessibilityEvent#getText()},
+     * {@link AccessibilityEvent#getItemCount()} and
+     * {@link AccessibilityEvent#getCurrentItemIndex()} properties.
+     * <p>
+     * Note: In general, computing these mappings includes the widget position on
+     * the screen. This is fragile and should be used as a last resort since
+     * changing the layout could potentially change the widget position. This is
+     * a workaround since the widgets of interest are image buttons that do not
+     * have contentDescription attribute set (plus/minus buttons) or no other
+     * information in the accessibility event is available to distinguish them
+     * aside of their positions on the screen (hour/minute inputs).<br/>
+     * If you are owner of the target application (Clock in this case) you
+     * should add contentDescription attribute to all image buttons such that a
+     * screen reader knows how to speak them. For input fields (while not
+     * applicable for the hour and minute inputs since they are not empty) a
+     * hint text should be set to enable better announcement.
+     * </p>
+     */
+    private static final SparseArray<Integer> sEventDataMappedStringResourceIds = new SparseArray<Integer>();
+    static {
+        sEventDataMappedStringResourceIds.put(110, R.string.value_increase_hours);
+        sEventDataMappedStringResourceIds.put(1140, R.string.value_increase_minutes);
+        sEventDataMappedStringResourceIds.put(1120, R.string.value_decrease_hours);
+        sEventDataMappedStringResourceIds.put(1160, R.string.value_decrease_minutes);
+        sEventDataMappedStringResourceIds.put(1111, R.string.value_hour);
+        sEventDataMappedStringResourceIds.put(1110, R.string.value_hours);
+        sEventDataMappedStringResourceIds.put(1151, R.string.value_minute);
+        sEventDataMappedStringResourceIds.put(1150, R.string.value_minutes);
+    }
+
+    /** Mapping from integers to vibration patterns for haptic feedback. */
+    private static final SparseArray<long[]> sVibrationPatterns = new SparseArray<long[]>();
+    static {
+        sVibrationPatterns.put(AccessibilityEvent.TYPE_VIEW_CLICKED, new long[] {
+                0L, 100L
+        });
+        sVibrationPatterns.put(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED, new long[] {
+                0L, 100L
+        });
+        sVibrationPatterns.put(AccessibilityEvent.TYPE_VIEW_SELECTED, new long[] {
+                0L, 15L, 10L, 15L
+        });
+        sVibrationPatterns.put(AccessibilityEvent.TYPE_VIEW_FOCUSED, new long[] {
+                0L, 15L, 10L, 15L
+        });
+        sVibrationPatterns.put(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED, new long[] {
+                0L, 25L, 50L, 25L, 50L, 25L
+        });
+        sVibrationPatterns.put(INDEX_SCREEN_ON, new long[] {
+                0L, 10L, 10L, 20L, 20L, 30L
+        });
+        sVibrationPatterns.put(INDEX_SCREEN_OFF, new long[] {
+                0L, 30L, 20L, 20L, 10L, 10L
+        });
+    }
+
+    /** Mapping from integers to raw sound resource ids. */
+    private static SparseArray<Integer> sSoundsResourceIds = new SparseArray<Integer>();
+    static {
+        sSoundsResourceIds.put(AccessibilityEvent.TYPE_VIEW_CLICKED, R.raw.sound_view_clicked);
+        sSoundsResourceIds.put(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED, R.raw.sound_view_clicked);
+        sSoundsResourceIds.put(AccessibilityEvent.TYPE_VIEW_SELECTED, R.raw.sound_view_focused_or_selected);
+        sSoundsResourceIds.put(AccessibilityEvent.TYPE_VIEW_FOCUSED, R.raw.sound_view_focused_or_selected);
+        sSoundsResourceIds.put(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED, R.raw.sound_window_state_changed);
+        sSoundsResourceIds.put(INDEX_SCREEN_ON, R.raw.sound_screen_on);
+        sSoundsResourceIds.put(INDEX_SCREEN_OFF, R.raw.sound_screen_off);
+        sSoundsResourceIds.put(INDEX_RINGER_SILENT, R.raw.sound_ringer_silent);
+        sSoundsResourceIds.put(INDEX_RINGER_VIBRATE, R.raw.sound_ringer_vibrate);
+        sSoundsResourceIds.put(INDEX_RINGER_NORMAL, R.raw.sound_ringer_normal);
+    }
+
+    // Sound pool related member fields.
+
+    /** Mapping from integers to earcon names - dynamically populated. */
+    private final SparseArray<String> mEarconNames = new SparseArray<String>();
+
+    // Auxiliary fields.
+
+    /**
+     * Handle to this service to enable inner classes to access the {@link Context}.
+     */
+    Context mContext;
+
+    /** The feedback this service is currently providing. */
+    int mProvidedFeedbackType;
+
+    /** Reusable instance for building utterances. */
+    private final StringBuilder mUtterance = new StringBuilder();
+
+    // Feedback providing services.
+
+    /** The {@link TextToSpeech} used for speaking. */
+    private TextToSpeech mTts;
+
+    /** The {@link AudioManager} for detecting ringer state. */
+    private AudioManager mAudioManager;
+
+    /** Vibrator for providing haptic feedback. */
+    private Vibrator mVibrator;
+
+    /** Flag if the infrastructure is initialized. */
+    private boolean isInfrastructureInitialized;
+
+    /** {@link Handler} for executing messages on the service main thread. */
+    Handler mHandler = new Handler() {
+        @Override
+        public void handleMessage(Message message) {
+            switch (message.what) {
+                case MESSAGE_SPEAK:
+                    String utterance = (String) message.obj;
+                    mTts.speak(utterance, QUEUING_MODE_INTERRUPT, null);
+                    return;
+                case MESSAGE_STOP_SPEAK:
+                    mTts.stop();
+                    return;
+                case MESSAGE_START_TTS:
+                    mTts = new TextToSpeech(mContext, new TextToSpeech.OnInitListener() {
+                        public void onInit(int status) {
+                            // Register here since to add earcons the TTS must be initialized and
+                            // the receiver is called immediately with the current ringer mode.
+                            registerBroadCastReceiver();
+                        }
+                    });
+                    return;
+                case MESSAGE_SHUTDOWN_TTS:
+                    mTts.shutdown();
+                    return;
+                case MESSAGE_PLAY_EARCON:
+                    int resourceId = message.arg1;
+                    playEarcon(resourceId);
+                    return;
+                case MESSAGE_STOP_PLAY_EARCON:
+                    mTts.stop();
+                    return;
+                case MESSAGE_VIBRATE:
+                    int key = message.arg1;
+                    long[] pattern = sVibrationPatterns.get(key);
+                    mVibrator.vibrate(pattern, -1);
+                    return;
+                case MESSAGE_STOP_VIBRATE:
+                    mVibrator.cancel();
+                    return;
+            }
+        }
+    };
+
+    /**
+     * {@link BroadcastReceiver} for receiving updates for our context - device
+     * state.
+     */
+    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            String action = intent.getAction();
+
+            if (AudioManager.RINGER_MODE_CHANGED_ACTION.equals(action)) {
+                int ringerMode = intent.getIntExtra(AudioManager.EXTRA_RINGER_MODE,
+                        AudioManager.RINGER_MODE_NORMAL);
+                configureForRingerMode(ringerMode);
+            } else if (Intent.ACTION_SCREEN_ON.equals(action)) {
+                provideScreenStateChangeFeedback(INDEX_SCREEN_ON);
+            } else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
+                provideScreenStateChangeFeedback(INDEX_SCREEN_OFF);
+            } else {
+                Log.w(LOG_TAG, "Registered for but not handling action " + action);
+            }
+        }
+
+        /**
+         * Provides feedback to announce the screen state change. Such a change
+         * is turning the screen on or off.
+         *
+         * @param feedbackIndex The index of the feedback in the statically
+         *            mapped feedback resources.
+         */
+        private void provideScreenStateChangeFeedback(int feedbackIndex) {
+            // We take a specific action depending on the feedback we currently provide.
+            switch (mProvidedFeedbackType) {
+                case AccessibilityServiceInfo.FEEDBACK_SPOKEN:
+                    String utterance = generateScreenOnOrOffUtternace(feedbackIndex);
+                    mHandler.obtainMessage(MESSAGE_SPEAK, utterance).sendToTarget();
+                    return;
+                case AccessibilityServiceInfo.FEEDBACK_AUDIBLE:
+                    mHandler.obtainMessage(MESSAGE_PLAY_EARCON, feedbackIndex, 0).sendToTarget();
+                    return;
+                case AccessibilityServiceInfo.FEEDBACK_HAPTIC:
+                    mHandler.obtainMessage(MESSAGE_VIBRATE, feedbackIndex, 0).sendToTarget();
+                    return;
+                default:
+                    throw new IllegalStateException("Unexpected feedback type "
+                            + mProvidedFeedbackType);
+            }
+        }
+    };
+
+    @Override
+    public void onServiceConnected() {
+        if (isInfrastructureInitialized) {
+            return;
+        }
+
+        mContext = this;
+
+        // Send a message to start the TTS.
+        mHandler.sendEmptyMessage(MESSAGE_START_TTS);
+
+        // Get the vibrator service.
+        mVibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
+
+        // Get the AudioManager and configure according the current ring mode.
+        mAudioManager = (AudioManager) getSystemService(Service.AUDIO_SERVICE);
+        // In Froyo the broadcast receiver for the ringer mode is called back with the
+        // current state upon registering but in Eclair this is not done so we poll here.
+        int ringerMode = mAudioManager.getRingerMode();
+        configureForRingerMode(ringerMode);
+
+        // We are in an initialized state now.
+        isInfrastructureInitialized = true;
+    }
+
+    @Override
+    public boolean onUnbind(Intent intent) {
+        if (isInfrastructureInitialized) {
+            // Stop the TTS service.
+            mHandler.sendEmptyMessage(MESSAGE_SHUTDOWN_TTS);
+
+            // Unregister the intent broadcast receiver.
+            if (mBroadcastReceiver != null) {
+                unregisterReceiver(mBroadcastReceiver);
+            }
+
+            // We are not in an initialized state anymore.
+            isInfrastructureInitialized = false;
+        }
+        return false;
+    }
+
+    /**
+     * Registers the phone state observing broadcast receiver.
+     */
+    private void registerBroadCastReceiver() {
+        // Create a filter with the broadcast intents we are interested in.
+        IntentFilter filter = new IntentFilter();
+        filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION);
+        filter.addAction(Intent.ACTION_SCREEN_ON);
+        filter.addAction(Intent.ACTION_SCREEN_OFF);
+        // Register for broadcasts of interest.
+        registerReceiver(mBroadcastReceiver, filter, null, null);
+    }
+
+    /**
+     * Generates an utterance for announcing screen on and screen off.
+     *
+     * @param feedbackIndex The feedback index for looking up feedback value.
+     * @return The utterance.
+     */
+    private String generateScreenOnOrOffUtternace(int feedbackIndex) {
+        // Get the announce template.
+        int resourceId = (feedbackIndex == INDEX_SCREEN_ON) ? R.string.template_screen_on
+                : R.string.template_screen_off;
+        String template = mContext.getString(resourceId);
+
+        // Format the template with the ringer percentage.
+        int currentRingerVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_RING);
+        int maxRingerVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_RING);
+        int volumePercent = (100 / maxRingerVolume) * currentRingerVolume;
+
+        // Let us round to five so it sounds better.
+        int adjustment = volumePercent % 10;
+        if (adjustment < 5) {
+            volumePercent -= adjustment;
+        } else if (adjustment > 5) {
+            volumePercent += (10 - adjustment);
+        }
+
+        return String.format(template, volumePercent);
+    }
+
+    /**
+     * Configures the service according to a ringer mode. Possible
+     * configurations:
+     * <p>
+     *   1. {@link AudioManager#RINGER_MODE_SILENT}<br/>
+     *   Goal:     Provide only custom haptic feedback.<br/>
+     *   Approach: Take over the haptic feedback by configuring this service to provide
+     *             such and do so. This way the system will not call the default haptic
+     *             feedback service KickBack.<br/>
+     *             Take over the audible and spoken feedback by configuring this
+     *             service to provide such feedback but not doing so. This way the system
+     *             will not call the default spoken feedback service TalkBack and the
+     *             default audible feedback service SoundBack.
+     * </p>
+     * <p>
+     *   2. {@link AudioManager#RINGER_MODE_VIBRATE}<br/>
+     *   Goal:     Provide custom audible and default haptic feedback.<br/>
+     *   Approach: Take over the audible feedback and provide custom one.<br/>
+     *             Take over the spoken feedback but do not provide such.<br/>
+     *             Let some other service provide haptic feedback (KickBack).
+     * </p>
+     * <p>
+     *   3. {@link AudioManager#RINGER_MODE_NORMAL}
+     *   Goal:     Provide custom spoken, default audible and default haptic feedback.<br/>
+     *   Approach: Take over the spoken feedback and provide custom one.<br/>
+     *             Let some other services provide audible feedback (SounBack) and haptic
+     *             feedback (KickBack).
+     * </p>
+     * Note: In the above description an assumption is made that all default feedback
+     *       services are enabled. Such services are TalkBack, SoundBack, and KickBack.
+     *       Also the feature of defining a service as the default for a given feedback
+     *       type will be available in Android 2.2 and above. For previous releases the package
+     *       specific accessibility service must be registered first i.e. checked in the
+     *       settings.
+     *
+     * @param ringerMode The device ringer mode.
+     */
+    private void configureForRingerMode(int ringerMode) {
+        if (ringerMode == AudioManager.RINGER_MODE_SILENT) {
+            // When the ringer is silent we want to provide only haptic feedback.
+            mProvidedFeedbackType = AccessibilityServiceInfo.FEEDBACK_HAPTIC;
+
+            // Take over the spoken and sound feedback so no such feedback is provided.
+            setServiceInfo(AccessibilityServiceInfo.FEEDBACK_HAPTIC
+                    | AccessibilityServiceInfo.FEEDBACK_SPOKEN
+                    | AccessibilityServiceInfo.FEEDBACK_AUDIBLE);
+
+            // Use only an earcon to announce ringer state change.
+            mHandler.obtainMessage(MESSAGE_PLAY_EARCON, INDEX_RINGER_SILENT, 0).sendToTarget();
+        } else if (ringerMode == AudioManager.RINGER_MODE_VIBRATE) {
+            // When the ringer is vibrating we want to provide only audible feedback.
+            mProvidedFeedbackType = AccessibilityServiceInfo.FEEDBACK_AUDIBLE;
+
+            // Take over the spoken feedback so no spoken feedback is provided.
+            setServiceInfo(AccessibilityServiceInfo.FEEDBACK_AUDIBLE
+                    | AccessibilityServiceInfo.FEEDBACK_SPOKEN);
+
+            // Use only an earcon to announce ringer state change.
+            mHandler.obtainMessage(MESSAGE_PLAY_EARCON, INDEX_RINGER_VIBRATE, 0).sendToTarget();
+        } else if (ringerMode == AudioManager.RINGER_MODE_NORMAL) {
+            // When the ringer is ringing we want to provide spoken feedback
+            // overriding the default spoken feedback.
+            mProvidedFeedbackType = AccessibilityServiceInfo.FEEDBACK_SPOKEN;
+            setServiceInfo(AccessibilityServiceInfo.FEEDBACK_SPOKEN);
+
+            // Use only an earcon to announce ringer state change.
+            mHandler.obtainMessage(MESSAGE_PLAY_EARCON, INDEX_RINGER_NORMAL, 0).sendToTarget();
+        }
+    }
+
+    /**
+     * Sets the {@link AccessibilityServiceInfo} which informs the system how to
+     * handle this {@link AccessibilityService}.
+     *
+     * @param feedbackType The type of feedback this service will provide.
+     * <p>
+     *   Note: The feedbackType parameter is an bitwise or of all
+     *   feedback types this service would like to provide.
+     * </p>
+     */
+    private void setServiceInfo(int feedbackType) {
+        AccessibilityServiceInfo info = new AccessibilityServiceInfo();
+        // We are interested in all types of accessibility events.
+        info.eventTypes = AccessibilityEvent.TYPES_ALL_MASK;
+        // We want to provide specific type of feedback.
+        info.feedbackType = feedbackType;
+        // We want to receive events in a certain interval.
+        info.notificationTimeout = EVENT_NOTIFICATION_TIMEOUT_MILLIS;
+        // We want to receive accessibility events only from certain packages.
+        info.packageNames = PACKAGE_NAMES;
+        setServiceInfo(info);
+    }
+
+    @Override
+    public void onAccessibilityEvent(AccessibilityEvent event) {
+        Log.i(LOG_TAG, mProvidedFeedbackType + " " + event.toString());
+
+        // Here we act according to the feedback type we are currently providing.
+        if (mProvidedFeedbackType == AccessibilityServiceInfo.FEEDBACK_SPOKEN) {
+            mHandler.obtainMessage(MESSAGE_SPEAK, formatUtterance(event)).sendToTarget();
+        } else if (mProvidedFeedbackType == AccessibilityServiceInfo.FEEDBACK_AUDIBLE) {
+            mHandler.obtainMessage(MESSAGE_PLAY_EARCON, event.getEventType(), 0).sendToTarget();
+        } else if (mProvidedFeedbackType == AccessibilityServiceInfo.FEEDBACK_HAPTIC) {
+            mHandler.obtainMessage(MESSAGE_VIBRATE, event.getEventType(), 0).sendToTarget();
+        } else {
+            throw new IllegalStateException("Unexpected feedback type " + mProvidedFeedbackType);
+        }
+    }
+
+    @Override
+    public void onInterrupt() {
+        // Here we act according to the feedback type we are currently providing.
+        if (mProvidedFeedbackType == AccessibilityServiceInfo.FEEDBACK_SPOKEN) {
+            mHandler.obtainMessage(MESSAGE_STOP_SPEAK).sendToTarget();
+        } else if (mProvidedFeedbackType == AccessibilityServiceInfo.FEEDBACK_AUDIBLE) {
+            mHandler.obtainMessage(MESSAGE_STOP_PLAY_EARCON).sendToTarget();
+        } else if (mProvidedFeedbackType == AccessibilityServiceInfo.FEEDBACK_HAPTIC) {
+            mHandler.obtainMessage(MESSAGE_STOP_VIBRATE).sendToTarget();
+        } else {
+            throw new IllegalStateException("Unexpected feedback type " + mProvidedFeedbackType);
+        }
+    }
+
+    /**
+     * Formats an utterance from an {@link AccessibilityEvent}.
+     *
+     * @param event The event from which to format an utterance.
+     * @return The formatted utterance.
+     */
+    private String formatUtterance(AccessibilityEvent event) {
+        StringBuilder utterance = mUtterance;
+
+        // Clear the utterance before appending the formatted text.
+        utterance.setLength(0);
+
+        List<CharSequence> eventText = event.getText();
+
+        // We try to get the event text if such.
+        if (!eventText.isEmpty()) {
+            for (CharSequence subText : eventText) {
+                // Make 01 pronounced as 1
+                if (subText.charAt(0) =='0') {
+                    subText = subText.subSequence(1, subText.length());
+                }
+                utterance.append(subText);
+                utterance.append(SPACE);
+            }
+
+            // Here we do a bit of enhancement of the UI presentation by using the semantic
+            // of the event source in the context of the Clock application.
+            if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED
+                    && CLASS_NAME_EDIT_TEXT.equals(event.getClassName())) {
+                // If the source is an edit text box and we have a mapping based on
+                // its position in the items of the container parent of the event source
+                // we append that value as well. We say "XX hours" and "XX minutes".
+                String resourceValue = getEventDataMappedStringResource(event);
+                if (resourceValue != null) {
+                    utterance.append(resourceValue);
+                }
+            }
+
+            return utterance.toString();
+        }
+
+        // There is no event text but we try to get the content description which is
+        // an optional attribute for describing a view (typically used with ImageView).
+        CharSequence contentDescription = event.getContentDescription();
+        if (contentDescription != null) {
+            utterance.append(contentDescription);
+            return utterance.toString();
+        }
+
+        // No text and content description for the plus and minus buttons, so we lookup
+        // custom values based on the event's itemCount and currentItemIndex properties.
+        CharSequence className = event.getClassName();
+
+        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED
+                && (CLASS_NAME_NUMBER_PICKER_BUTTON_ALARM_CLOCK.equals(className)
+                || CLASS_NAME_NUMBER_PICKER_BUTTON_CLOCK.equals(className))) {
+            String resourceValue = getEventDataMappedStringResource(event);
+            utterance.append(resourceValue);
+        }
+
+        return utterance.toString();
+    }
+
+    /**
+     * Returns a string resource mapped based on the accessibility event
+     * data, specifically the
+     * {@link AccessibilityEvent#getText()},
+     * {@link AccessibilityEvent#getItemCount()}, and
+     * {@link AccessibilityEvent#getCurrentItemIndex()} properties.
+     *
+     * @param event The {@link AccessibilityEvent} to process.
+     * @return The mapped string if such exists, null otherwise.
+     */
+    private String getEventDataMappedStringResource(AccessibilityEvent event) {
+        int lookupIndex = computeLookupIndex(event);
+        int resourceId = sEventDataMappedStringResourceIds.get(lookupIndex);
+        return getString(resourceId);
+    }
+
+    /**
+     * Computes an index for looking up the custom text for views which either
+     * do not have text/content description or the position information
+     * is the only oracle for deciding from which widget was an accessibility
+     * event generated. The index is computed based on
+     * {@link AccessibilityEvent#getText()},
+     * {@link AccessibilityEvent#getItemCount()}, and
+     * {@link AccessibilityEvent#getCurrentItemIndex()} properties.
+     *
+     * @param event The event from which to compute the index.
+     * @return The lookup index.
+     */
+    private int computeLookupIndex(AccessibilityEvent event) {
+        int lookupIndex = event.getItemCount();
+        int divided = event.getCurrentItemIndex();
+
+        while (divided > 0) {
+            lookupIndex *= 10;
+            divided /= 10;
+        }
+
+        lookupIndex += event.getCurrentItemIndex();
+        lookupIndex *= 10;
+
+        // This is primarily for handling the zero hour/zero minutes cases
+        if (!event.getText().isEmpty()
+                && ("1".equals(event.getText().get(0).toString()) || "01".equals(event.getText()
+                        .get(0).toString()))) {
+            lookupIndex++;
+        }
+
+        return lookupIndex;
+    }
+
+    /**
+     * Plays an earcon given its id.
+     *
+     * @param earconId The id of the earcon to be played.
+     */
+    private void playEarcon(int earconId) {
+        String earconName = mEarconNames.get(earconId);
+        if (earconName == null) {
+            // We do not know the sound id, hence we need to load the sound.
+            int resourceId = sSoundsResourceIds.get(earconId);
+            earconName = "[" + earconId + "]";
+            mTts.addEarcon(earconName, getPackageName(), resourceId);
+            mEarconNames.put(earconId, earconName);
+        }
+
+        mTts.playEarcon(earconName, QUEUING_MODE_INTERRUPT, null);
+    }
+}