Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>From the code point of view, you need to implement the SensorListener:</p> <pre><code>public class ShakeActivity extends Activity implements SensorListener </code></pre> <p>You will need to acquire a SensorManager:</p> <pre><code>sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE); </code></pre> <p>And register this sensor with desired flags:</p> <pre><code>sensorMgr.registerListener(this, SensorManager.SENSOR_ACCELEROMETER, SensorManager.SENSOR_DELAY_GAME); </code></pre> <p>In your onSensorChange() method, you determine whether it’s a shake or not:</p> <pre><code>public void onSensorChanged(int sensor, float[] values) { if (sensor == SensorManager.SENSOR_ACCELEROMETER) { long curTime = System.currentTimeMillis(); // only allow one update every 100ms. if ((curTime - lastUpdate) &gt; 100) { long diffTime = (curTime - lastUpdate); lastUpdate = curTime; x = values[SensorManager.DATA_X]; y = values[SensorManager.DATA_Y]; z = values[SensorManager.DATA_Z]; float speed = Math.abs(x+y+z - last_x - last_y - last_z) / diffTime * 10000; if (speed &gt; SHAKE_THRESHOLD) { Log.d("sensor", "shake detected w/ speed: " + speed); Toast.makeText(this, "shake detected w/ speed: " + speed, Toast.LENGTH_SHORT).show(); } last_x = x; last_y = y; last_z = z; } } } </code></pre> <p>The shake threshold is defined as:</p> <pre><code>private static final int SHAKE_THRESHOLD = 800; </code></pre> <p>There are some other methods too, to detect shake motion. look at this <a href="http://www.codeshogun.com/blog/2009/04/17/how-to-detect-shake-motion-in-android-part-i/" rel="noreferrer">link.</a>(If that link does not work or link is dead, <a href="http://web.archive.org/web/20100324212856/http://www.codeshogun.com/blog/2009/04/17/how-to-detect-shake-motion-in-android-part-i/" rel="noreferrer">look at this web archive</a>.).</p> <p>Have a look at this <a href="http://android.hlidskialf.com/blog/code/android-shake-detection-listener" rel="noreferrer">example</a> for android shake detect listener. </p> <p><strong>Note:</strong> <code>SensorListener</code> is deprecated. we can use <code>SensorEventListener</code> instead. <a href="http://jasonmcreynolds.com/?p=388" rel="noreferrer">Here is a quick example using SensorEventListener.</a></p> <p>Thanks.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload