在android中检测Shake [英] detect Shake in android
问题描述
当用户摇晃设备 10 次时,我试图点击 API.我尝试了许多 git 示例和堆栈溢出解决方案,但没有一个确实解决了我的问题.其中一些在 10 次之前或 10 次之后检测到抖动.我试过 Seiamic 和 ShakeDetector 库.请给我一些有价值的解决方案.
I am trying to hit an API when user shake a device 10 times. I have tried many git sample and stack overflow solution but non of them did solve my problem. Some of them detecting shake before 10 times or after 10 times. I have tried Seiamic and ShakeDetector libraries. Please give me some valuable solution.
推荐答案
我已经使用这个库做到了:
1) 在 build.gridle 文件中添加依赖
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) 授予您的应用清单文件权限
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) 在 onCreate 方法中开始,像这样:
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) 覆盖 onStop 方法并停止该方法
4) override onStop method and stop that
@Override
protected void onStop() {
super.onStop();
shakeDetector.stopShakeDetector(getBaseContext());
}
5) 像这样覆盖 onDistroy 方法和 distroy :
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")) {
...
}
}
}
这篇关于在android中检测Shake的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!