如果用户摇动手机,如何设置持续时间

时间:2017-08-02 23:28:29

标签: java android android-studio

我希望振动和下面代码中的GIF视图与用户摇动手机的持续时间相同。一旦用户停止摇动他们的电话,我想去另一个活动。这是我的代码(包括评论): {

private SensorManager shakeEvent;
private float acelVal;
private float acelLast;
private float shake;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Fresco.initialize(this);
    setContentView(R.layout.activity_animation);

    shakeEvent = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
    shakeEvent.registerListener(sensorListener, shakeEvent.getDefaultSensor
            (Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);

    acelVal = SensorManager.GRAVITY_EARTH;
    acelLast = SensorManager.GRAVITY_EARTH;
    shake = 0.00f;

}

private final SensorEventListener sensorListener = new SensorEventListener() {
    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {

        float x = sensorEvent.values[0];
        float y = sensorEvent.values[1];
        float z = sensorEvent.values[2];

        acelLast = acelVal;
        acelVal = (float)Math.sqrt((double)(x*x + y*y + z*z));
        float delta = acelVal - acelLast;
        shake = shake * 0.9f + delta;

这是用户摇动手机时执行的代码:

        if (shake > 12){
            SimpleDraweeView gifAnimation = (SimpleDraweeView) findViewById(R.id.gifAnimation);

            DraweeController controller = Fresco.newDraweeControllerBuilder()
                    .setUri("http://i.imgur.com/XHpujBO.gif")
                    .setAutoPlayAnimations(true)
                    .build();

            gifAnimation.setController(controller);

            //I want this GIF to last as long as the user shakes their phone

            Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            vibrator.vibrate(2000); //Want to change duration to be the same as the shaking

            //I want this code to be executed once the shaking stops
            /*Intent intent = new Intent(getApplicationContext(),MainActivity.class);
            startActivityForResult(intent,0);*/

        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }
};

}

0 个答案:

没有答案