Android摇一摇代码

package com.yaoyiyao;

import android.annotation.*;
import android.app.*;
import android.hardware.*;
import android.media.*;
import android.os.*;
import android.widget.*;
import com.yaoyiyao.*;
	
    public class TestSensorActivity extends Activity {
		private SensorManager sensorManager;
		private Sensor sensor;
		private Vibrator vibrator;
	    private static final int UPTATE_INTERVAL_TIME = 70;//两次检测的时间间隔
		private static final int SPEED_SHRESHOLD = 30;//这个值调节灵敏度
		private long lastUpdateTime;
		private float lastX;
		private float lastY;
		private float lastZ;
	
	    @Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.main);
			sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
			vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
		}
		@Override
		protected void onResume() {
			// TODO Auto-generated method stub
			super.onResume();
			if (sensorManager != null) {
				sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
			}
			if (sensor != null) {
				sensorManager.registerListener(sensorEventListener,sensor,SensorManager.SENSOR_DELAY_GAME);//这里选择感应频率
			}
		}
		/**
		 * 重力感应监听
		 */	 
	private SensorEventListener sensorEventListener = new SensorEventListener()
	{
			@Override
			public void onSensorChanged(SensorEvent event) 
			{
				 // 现在检测时间
				 long currentUpdateTime = System.currentTimeMillis();
				 // 两次检测的时间间隔
				 long timeInterval = currentUpdateTime - lastUpdateTime;
				 // 判断是否达到了检测时间间隔
				 if (timeInterval < UPTATE_INTERVAL_TIME)
				 return;
				 // 现在的时间变成last时间
				 lastUpdateTime = currentUpdateTime;
				// 传感器信息改变时执行该方法
				float[] values = event.values;
				float x = values[0]; // x轴方向的重力加速度,向右为正
				float y = values[1]; // y轴方向的重力加速度,向前为正
				float z = values[2]; // z轴方向的重力加速度,向上为正
				float deltaX = x - lastX;
				float deltaY = y - lastY;
				float deltaZ = z - lastZ;
				lastX = x;
				lastY = y;
				lastZ = z;
				double speed = (Math.sqrt(deltaX * deltaX + deltaY * deltaY
										  + deltaZ * deltaZ) / timeInterval) * 100;
				if (speed >= SPEED_SHRESHOLD)
					{
					    vibrator.vibrate(200);
						Toast.makeText(TestSensorActivity.this, "检测到摇晃,执行操作!", Toast.LENGTH_SHORT).show();//事件
					}
			}
			@Override
			public void onAccuracyChanged(Sensor sensor, int accuracy){		
			}
		};
		
	@Override
	public void onBackPressed()
	{
		int pid = android.os.Process.myPid();
		android.os.Process.killProcess(pid);
	}
}

梦雪

专注于AIDE教程分享

留下你的评论

*评论支持代码高亮<pre class="prettyprint linenums">代码</pre>

相关推荐