我正在尝试开发一个应用程序,用户可以在其中使用手机的动作敲击隐形鼓。因此,当手机向下轻弹时,在轻弹结束时会响起鼓声。
通过检测大型快速运动何时突然停止,我已经成功完成了 90% 的工作。但是,尽管在轻弹(好)之后鼓会响起,但在拉动结束时也会响起(不理想)。
轻弹是指手机正在向前和向下轻弹,就好像你正在用它敲击鼓一样,而拉动我的意思是你正在将你的手臂放回起始位置。
有谁知道确定何时发生轻弹而不是推送的有效方法?
任何想法将不胜感激。
谢谢
现有代码:
package com.example.testaccelerometer;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity implements SensorEventListener{
public static TextView results;
public static TextView clickresults;
StringBuilder builder = new StringBuilder();
private float mAccelNoGrav;
private float mAccelWithGrav;
private float mLastAccelWithGrav;
public static boolean shakeIsHappening;
public static int beatnumber = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
results = (TextView) findViewById(R.id.results);
clickresults = (TextView) findViewById(R.id.clickresults);
SensorManager manager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor accelerometer = manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if(!manager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_FASTEST)){
builder.append("Problem with Accelerometer - Shaking will not work");
};
mAccelNoGrav = 0.00f;
mAccelWithGrav = SensorManager.GRAVITY_EARTH;
mLastAccelWithGrav = SensorManager.GRAVITY_EARTH;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
builder.setLength(0);
builder.append("X " + event.values[0] + "\nY " + event.values[1] + "\nZ " + event.values[2]);
results.setText(builder.toString());
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
mLastAccelWithGrav = mAccelWithGrav;
mAccelWithGrav = android.util.FloatMath.sqrt(x*x + y*y + z*z);
float delta = mAccelWithGrav - mLastAccelWithGrav;
mAccelNoGrav = mAccelNoGrav * 0.9f + delta;
if (mAccelNoGrav >8.5) {
shakeIsHappening = true;
//clickresults.append(" click " + mAccel);
}
if (shakeIsHappening == true && mAccelNoGrav <2) {
beatnumber++;
clickresults.append(" click number: " + beatnumber + "\n" + "PA: " + mLastAccelWithGrav + " CA:" + mAccelNoGrav + "\n ");
shakeIsHappening = false;
}
}
@Override
protected void onResume() {
super.onResume();
// YOU DO NEED TO TRY AND REREGISTER IT NOW
}
@Override
protected void onPause() {
// YOU DO NEED TO TRY AND UNREGISTER IT NOW
super.onPause();
}
}