在Android中检测震动 [英] detect Shake in android

查看:575
本文介绍了在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文件中添加depend

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方法和发行版,如下所示:

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中检测震动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆