`
mickey_hou
  • 浏览: 247882 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

shanke

阅读更多
public class ShakeActivity extends Activity implements SensorEventListener
{
    private SensorManager sensorManager;
   
    private ToastDeal deal = new ToastDeal();
   
    private long mLastUpdateTime;
   
    private float mLastX, mLastY, mLastZ; 
   
    private Context myContext;
   
    public int shakeThreshold = 1000;
   
    @Override
    public void onCreate(Bundle bundle)
    {
        super.onCreate(bundle);
        setContentView(R.layout.main);
        myContext = ShakeActivity.this;
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    }
   
    @Override
    protected void onResume()
    {
        super.onResume();
        sensorManager.registerListener(this,sensorManager.getDefaultSensor(
                    Sensor.TYPE_ACCELEROMETER),//TYPE_ACCELEROMETER  传感器类型 :加速度
                    SensorManager.SENSOR_DELAY_NORMAL);
    }
   
    @Override
    protected void onStop()
    {
        sensorManager.unregisterListener(this);
        super.onStop();
    }
   
    public void onAccuracyChanged(Sensor sensor, int accuracy)
    {
    }
   
    public void onSensorChanged(SensorEvent event)
    {
        long currentTime = System.currentTimeMillis();
        long diffTime = currentTime - mLastUpdateTime;
        if (diffTime < Parameters.UPDATE_INTERVAL)
        {
            return;
        }
        this.mLastUpdateTime = currentTime; 
        float x = event.values[0]; 
        float y = event.values[1]; 
        float z = event.values[2]; 
        float deltaX = x - mLastX; 
        float deltaY = y - mLastY; 
        float deltaZ = z - mLastZ; 
        this.mLastX = x; 
        this.mLastY = y; 
        this.mLastZ = z;
        float delta = FloatMath.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ  * deltaZ) / diffTime * 10000;
        /**
         * 当加速度的差值大于指定的阈值,认为这是一个摇晃 
         */
        if (delta > shakeThreshold)
        {
            deal.showToast(myContext, "手机执行了shake动作....");
        }
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics