Android shake listener example | Accelerometer sensor

Android accelerometer shake detection example source code

This very interesting source code example even it is work as shake event listener. If your application is running and user shake the mobile you can do anything here in his example i added simple toast. When mobile phone is shake it will show toast. You can use it as a button click listener. Here get more latest interesting android tutorial code. Android shake listener MainActivty source code.

package write your package name here;
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.support.v7.app.AppCompatActivity;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
privateSensorManager sm;
privatefloat acelVal; // current acceleration including gravity
privatefloat acelLast; // last acceleration including gravity
privatefloat shake; // acceleration apart from gravity
@Override
protectedvoidonCreate(BundlesavedInstanceState) {
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);
shake = 0.00f;
acelVal = SensorManager.GRAVITY_EARTH;
acelLast = SensorManager.GRAVITY_EARTH;
}
privatefinalSensorEventListenersensorListener=newSensorEventListener() {
publicvoidonSensorChanged(SensorEventse) {
float x = se.values[0];
float y = se.values[1];
float z = se.values[2];
acelLast = acelVal;
acelVal = (float) Math.sqrt((double) (x*x + y*y + z*z));
float delta = acelVal – acelLast;
shake = shake * 0.9f + delta; // perform low-cut filter
if (shake >12) {
Toast toast =Toast.makeText(getApplicationContext(), “DO NOT SHAKE ME”, Toast.LENGTH_LONG);
toast.show();
}
}
publicvoidonAccuracyChanged(Sensorsensor, intaccuracy) {
}
};
}
AndroidMainfest.xml permission for shake event sensor

<?xml version=”1.0″ encoding=”utf-8″ ?>

<manifest
xmlns:android=”http://schemas.android.com/apk/res/android
package=”utube.attraction.shareapk>
<uses-feature
android:name=”android.hardware.sensor.accelerometer
android:required=”true />
<application
android:allowBackup=”true
android:icon=”@mipmap/ic_launcher
android:label=”@string/app_name
android:supportsRtl=”true
android:theme=”@style/AppTheme>
<activity
android:name=”.MainActivity>
<intent-filter>
<action
android:name=”android.intent.action.MAIN />
<category
android:name=”android.intent.category.LAUNCHER />
</intent-filter>
</activity>
</application>
</manifest>

Add a Comment

Your email address will not be published. Required fields are marked *