gpt4 book ai didi

java - 如何制作一个完美的延迟时间,使其只计算一次

转载 作者:太空宇宙 更新时间:2023-11-04 12:44:39 24 4
gpt4 key购买 nike

您好,我正在使用一个跳跃应用程序,它会计算您跳跃的次数,并且我使用加速度计传感器。我遇到的问题是,我真的不知道如何设置延迟,所以它是完美的,有时一次跳跃算作 2 次跳跃,有时它不注册,有时效果很好。我希望每次计数跳跃有大约 0.4 秒的时间。

private TextView textView;
private TextView text;
private SensorManager sensorManager;
double ax,ay,az;
boolean newJumpAccepted = true;
int numbersOfJumps = 0;
long startTime = 0;
int count;
MediaPlayer mediaPlayer;
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
@Override
public void run() {
long millis = System.currentTimeMillis() - startTime;

if(millis>400){
newJumpAccepted = true;
} else {
newJumpAccepted = false;
}


int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
timerHandler.postDelayed(this,500);
}
};


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager=(SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_FASTEST);
text = (TextView) findViewById(R.id.text);
textView = (TextView) findViewById(R.id.textView);
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
}

@Override
public void onSensorChanged(SensorEvent event){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String result = "";
double d = Math.round(event.values[1]);
float threshold = preferences.getFloat("hello", 11);
if (d != 0 && d >= threshold && newJumpAccepted){
count++;
}
Log.i("hej", String.valueOf(d));
text.setText("Jump made" + " " + count + " " + d);
text.invalidate();
startTime();
}

private void startTime() {
if(newJumpAccepted) {
startTime = System.currentTimeMillis();
timerHandler.postDelayed(timerRunnable, 0);
}
newJumpAccepted = false;
}
}

最佳答案

Timer timer;
MyTimerTask myTimerTask;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager=(SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_FASTEST);
text = (TextView) findViewById(R.id.text);
textView = (TextView) findViewById(R.id.textView);

if(timer != null){
timer.cancel();
}

timer = new Timer();
myTimerTask = new MyTimerTask();

timer.schedule(myTimerTask, 400, 400);
}

class MyTimerTask extends TimerTask {

@Override
public void run() {
runOnUiThread(new Runnable() {

@Override
public void run() {

if (!newJumpAccepted) {
text.setText(String.valueOf(count));
newJumpAccepted = true;
}
}
});
}
}

关于java - 如何制作一个完美的延迟时间,使其只计算一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36452699/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com