简体   繁体   English

在android中摇晃手机3次后如何检测摇晃并吐司消息

[英]How to detect shake and toast a message after shaking the phone 3 times in android

package com.example.womenssafety;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private SensorManager sm;
private float acelVal,acelLast,shake;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sm=(SensorManager) getSystemService(Context.SENSOR_SERVICE);
        sm.registerListener(sensorListener,sm.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 event) {
        float x =event.values[0];
        float y =event.values[1];
        float z =event.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){
            Toast t =Toast.makeText(getApplicationContext(), "Dont Shake phone",Toast.LENGTH_LONG);
            t.show();
        }
    }
    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }
};
}

In this code it's toasting the message after shaking the phone 1 time.在这段代码中,它在摇晃手机 1 次后烘烤消息。 But I want to get the toast message after shaking the phone 3 times.但是我想在摇晃手机3次后得到toast消息。

How can I do this?我怎样才能做到这一点?

Add this as Global Var将此添加为Global Var

private static int counter = 0;

now add these lines in your onSensorChanged现在在您的onSensorChanged添加这些行

if (shake > 12) {
    counter++;
}

if (counter >= 3) {
    counter = 0;
    Toast t = Toast.makeText(getApplicationContext(), "Don't Shake phone", Toast.LENGTH_LONG);
    t.show();
}

This will show toast every 3rd time user shakes the phone, I also suggest to change Toast length to LENGTH_SHORT这将每 3 次用户摇动手机时显示吐司,我还建议将Toast长度更改为LENGTH_SHORT

Hope this will help!希望这会有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM