MattBlack MattBlack - 4 months ago 19
Android Question

Prevent Multiple Shakes Android

I'm using seismic with the below android code.

When the user shakes the message box appears multiple times. How would I go about modifying the code to make it so that after the shake it 'stops detecting' and waits until the message box is dismissed before detecting shakes again?

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.util.Log;
import android.app.AlertDialog;
import android.content.DialogInterface;
import com.squareup.seismic.ShakeDetector;
import com.squareup.seismic.ShakeDetector.Listener;

import android.hardware.SensorManager;


public class MainActivity extends AppCompatActivity implements Listener {





public void clickFunction(View view) {


new AlertDialog.Builder(this)
.setTitle("Not Signed In")
.setMessage("You need to be signed in to use this feature.")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Log.i("Hello", "created!");

SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
ShakeDetector sd = new ShakeDetector(this);
sd.start(sensorManager);




}



public void hearShake() {







Log.i("wooo", "Shaken!");





new AlertDialog.Builder(this)
.setTitle("Not Signed In")
.setMessage("SHAKEN!.")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();

}




}

Answer

Instead of new AlertDialog.Builder...show(); I would suggest assigning an AlertDialog variable (ex. mDialog) and in hearShake() simply add

if(mDialog.isShowing()) return;

UPDATE: Make sd a global variable instead

ShakeDetector sd = new ShakeDetector(this);
//...
protected void onCreate(...){
    //...
    sd = new ShakeDetector(this);
    sd.start(sensorManager);
}

public void hearShake(){
    //...
    sd.stop();
    //...
}