摇动手机的事件步骤和功能封装

public class RockService {



	private static RockListener rockListener;

	private static int MaxScope = 14;

	private static SensorManager mSensorManager;

	private static long lastRockTime;

	private static SensorEventListener listener = new SensorEventListener() {



		@Override

		public void onAccuracyChanged(Sensor sensor, int accuracy) {



		}



		@Override

		public void onSensorChanged(SensorEvent event) {

			int sensorType = event.sensor.getType();

			if (sensorType != Sensor.TYPE_ACCELEROMETER) {

				return;

			}



			float[] values = event.values;

			boolean isRock = Math.abs(values[0]) > MaxScope

					|| Math.abs(values[1]) > MaxScope

					|| Math.abs(values[2]) > MaxScope;



			if (isRock && null != rockListener) {

				

				//2秒之内不允许摇动两次

				long currentTime = System.currentTimeMillis();

				if (currentTime - lastRockTime > 2000) {

					rockListener.rock();

					lastRockTime = currentTime;

				}

			}

		}

	};



	/**

	 * 在activity的onResume调用

	 * 

	 * @author carlos [email protected]

	 * @version 创建时间:2012-1-15 上午7:25:47

	 * @param context

	 */

	public static void startService(Context context, RockListener rockListener) {

		stopService();

		

		RockService.rockListener = rockListener;



		mSensorManager = (SensorManager) context

				.getSystemService(Context.SENSOR_SERVICE);



		mSensorManager.registerListener(listener,

				mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),

				SensorManager.SENSOR_DELAY_NORMAL);



	}

	

	/**

	 * 在activity的onPause里调用

	 * 

	 * @author carlos [email protected]

	 * @version 创建时间:2012-1-15 上午7:25:13

	 */

	public static void stopService() {

		if (null != mSensorManager) {

			mSensorManager.unregisterListener(listener);

		}

		rockListener = null;

	}



	/**

	 * 设置摇动的范围

	 * 

	 * @author carlos [email protected]

	 * @version 创建时间:2012-1-15 上午7:41:12

	 * @param maxScope

	 */

	public static void setMaxScope(int maxScope) {

		MaxScope = maxScope;

	}



	public interface RockListener {

		public void rock();

	}

}

  

你可能感兴趣的:(事件)