我有一个应用程序,它有一个游戏中的计步器,因此可以在用户玩游戏时在后台计算他们的步数。它工作正常,我的问题如下
- 自开始玩游戏以来,用户采取的总步数
例如,在一个会话中,他有 200 个步骤,接下来有 300 个步骤。我想保存总共 500 个步骤,以便我可以向用户显示成就,例如。恭喜您自开始游戏以来已走了 1000 步。
这是我在网上找到并当前在我的应用程序中使用的计步器代码。
import android.app.Activity;
import android.content.Context;
import android.hardware.*;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class StepCounterActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private TextView count;
boolean activityRunning;
int totalSteps;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_step_counter);
count = (TextView) findViewById(R.id.count);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
}
@Override
protected void onResume() {
super.onResume();
activityRunning = true;
Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
if (countSensor != null) {
sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
} else {
Toast.makeText(this, "Count sensor not available!", Toast.LENGTH_LONG).show();
}
}
@Override
protected void onPause() {
super.onPause();
activityRunning = false;
// if you unregister the last listener, the hardware will stop detecting step events
// sensorManager.unregisterListener(this);
}
@Override
public void onSensorChanged(SensorEvent event) {
if (activityRunning) {
count.setText(String.valueOf(event.values[0]));
//maybe add to a variable the number of steps somehow?
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}