在 android 中摇晃 phone 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) {
    }
};
}

在此代码中,它在摇动 phone 1 次后烘烤消息。但是我想在摇动 phone 3 次后得到吐司消息。

我该怎么做?

将此添加为 Global Var

private static int counter = 0;

现在将这些行添加到您的 onSensorChanged

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

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

这将在用户每第 3 次摇动 phone 时显示吐司,我还建议将 Toast 长度更改为 LENGTH_SHORT

希望对您有所帮助!