我正在尝试在用户摇动设备10次时调用API。我尝试了许多git示例和stackoverflow解决方案,但它们都没有解决我的问题。其中一些在10次之前或之后检测到摇晃。我尝试了Seiamic和ShakeDetector库。请给我一些有价值的解决方案。
我正在尝试在用户摇动设备10次时调用API。我尝试了许多git示例和stackoverflow解决方案,但它们都没有解决我的问题。其中一些在10次之前或之后检测到摇晃。我尝试了Seiamic和ShakeDetector库。请给我一些有价值的解决方案。
我使用这个库完成了这件事:
在你的build.gradle文件中添加依赖项:(*) 可选步骤:如果您将在后台运行,请创建广播接收器
public class ShakeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (null != intent && intent.getAction().equals("shake.detector")) {
...
}
}
}
有一个静态变量,每次检测到摇晃时都会递增。
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
}
}
}
}