检测安卓设备的晃动

3

我正在尝试在用户摇动设备10次时调用API。我尝试了许多git示例和stackoverflow解决方案,但它们都没有解决我的问题。其中一些在10次之前或之后检测到摇晃。我尝试了SeiamicShakeDetector库。请给我一些有价值的解决方案。


2
多次连续摇晃并不是那么简单。我相信你需要自己定义什么是“摇晃”,以及两次摇晃之间的“超时时间”,才能对解决方案满意。 - nstosic
3个回答

3

我使用这个库完成了这件事:

在你的build.gradle文件中添加依赖项:
``` allprojects { repositories { ... maven { url 'https://jitpack.io' } } }
dependencies { compile 'com.github.safetysystemtechnology:android-shake-detector:v1.2' } ```
在你的应用程序清单文件中授予权限:
``` ```
如果您将在后台运行,请注册您的广播接收器
``` ```
在onCreate方法中启动它,如下所示:
``` 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); } ```
覆盖onStop方法并停止它:
``` @Override protected void onStop() { super.onStop(); shakeDetector.stopShakeDetector(getBaseContext()); } ```
覆盖onDestroy方法并像这样销毁:
``` @Override protected void onDestroy() { shakeDetector.destroy(getBaseContext()); super.onDestroy(); } ```

(*) 可选步骤:如果您将在后台运行,请创建广播接收器

public class ShakeReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (null != intent && intent.getAction().equals("shake.detector")) {
            ...
        }
    }
}

1

0

有一个静态变量,每次检测到摇晃时都会递增。

static int count = 0;
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
    long curTime = System.currentTimeMillis();
    if ((curTime - mLastShakeTime) > MIN_TIME_BETWEEN_SHAKES_MILLISECS) {

        float x = event.values[0];
        float y = event.values[1];
        float z = event.values[2];

        double acceleration = Math.sqrt(Math.pow(x, 2) +
                Math.pow(y, 2) +
                Math.pow(z, 2)) - SensorManager.GRAVITY_EARTH;

        if (acceleration > SHAKE_THRESHOLD) {
            mLastShakeTime = curTime;
            count++;
            if(count==10){
                //your code goes here
            }
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接