I have done that using this library :
1) Add the dependecy in your build.gridle file
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
dependencies {
compile 'com.github.safetysystemtechnology:android-shake-detector:v1.2'
}
2) Give the permission to your app manifest file
<uses-feature android:name="android.hardware.sensor.accelerometer" android:required="true" />
if you will run in background, register your broadcast receiver
<receiver android:name=".ShakeReceiver">
<intent-filter>
<action android:name="shake.detector" />
</intent-filter>
</receiver>
3) start that in onCreate method Like this :
private ShakeDetector shakeDetector;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buildView();
ShakeOptions options = new ShakeOptions()
.background(true)
.interval(1000)
.shakeCount(2)
.sensibility(2.0f);
this.shakeDetector = new ShakeDetector(options).start(this, new ShakeCallback() {
@Override
public void onShake() {
Log.d("event", "onShake");
}
});
//IF YOU WANT JUST IN BACKGROUND
//this.shakeDetector = new ShakeDetector(options).start(this);
}
4) override onStop method and stop that
@Override
protected void onStop() {
super.onStop();
shakeDetector.stopShakeDetector(getBaseContext());
}
5) override onDistroy method and distroy like this :
@Override
protected void onDestroy() {
shakeDetector.destroy(getBaseContext());
super.onDestroy();
}
(*) Optional step : if you will run in background, create your broadcast receiver
public class ShakeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (null != intent && intent.getAction().equals("shake.detector")) {
...
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…