android 利用重力感应检测摇晃手机的速度(音乐播放器实现甩歌)

这是一段网上找的利用重力感应检测摇晃手机的速度代码,结合前几天写的音乐播放器,成功实现了甩歌功能。


package com.pocketdigi;   
import android.app.Activity;   
import android.os.Bundle;   
import android.util.Log;
import android.widget.Toast;
import android.hardware.SensorListener;
import android.hardware.SensorManager;   
import android.hardware.Sensor;   
 
 
@SuppressWarnings("deprecation")
public class main extends Activity implements SensorListener {   
    private float x, y, z,last_x,last_y,last_z;
    private long lastUpdate;
   
    protected void onCreate(Bundle savedInstanceState) {   
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main);
        SensorManager sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE); 
        Sensor sensor = sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

        sensorMgr.registerListener(this,SensorManager.SENSOR_ACCELEROMETER,SensorManager.SENSOR_DELAY_GAME);  

    }

	@Override
	public void onAccuracyChanged(int sensor, int accuracy) {
		// TODO Auto-generated method stub
		
	}
	private static final int SHAKE_THRESHOLD = 5000;
	//这个控制精度,越小表示反应越灵敏
	@Override
	public void onSensorChanged(int sensor, float[] values) {
		// TODO Auto-generated method stub
		if (sensor == SensorManager.SENSOR_ACCELEROMETER) {   
			long curTime = System.currentTimeMillis();   
			// 每100毫秒检测一次   
			if ((curTime - lastUpdate) > 100) { 
			long diffTime = (curTime - lastUpdate);  
			lastUpdate = curTime;   	  
			x = values[SensorManager.DATA_X];   
			y = values[SensorManager.DATA_Y];   
			z = values[SensorManager.DATA_Z];   		  
			float speed = Math.abs(x+y+z - last_x - last_y - last_z) / diffTime * 10000;   			  
			if (speed > SHAKE_THRESHOLD) {   
                                         //检测到摇晃后执行的代码
			}  
			last_x = x;   
			last_y = y;   
			last_z = z;   
			}   
			}
		
	}
 
}

© 2010, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记