Search code examples
androidandroid-sensors

On shake action generate on android app


I want to show a message like "you made a shake" when a user shake the android mobile. That means like when we press a button some action we can create using

button.setonclicklistiner()

like that i want to do something when a user shake the device. how can i do that????


Solution

  • Check out Seismic from Square. I haven't used it yet in my own work, but from the example you can declare a shake listener like the following:

    public class Demo extends Activity implements ShakeDetector.Listener {
      @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        ShakeDetector sd = new ShakeDetector(this);
        sd.start(sensorManager);
    
        TextView tv = new TextView(this);
        tv.setGravity(CENTER);
        tv.setText("Shake me, bro!");
        setContentView(tv, new LayoutParams(MATCH_PARENT, MATCH_PARENT));
      }
    
      public void hearShake() {
        Toast.makeText(this, "Don't shake me, bro!", Toast.LENGTH_SHORT).show();
      }
    }