Search code examples
javaandroidandroid-studioaccelerometer

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. But I want to get the toast message after shaking the phone 3 times.

How can I do this?


Solution

  • Add this as Global Var

    private static int counter = 0;
    

    now add these lines in your 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

    Hope this will help!