我有一个游戏活动,我想测量用户一直在玩的时间。
在游戏活动中,我有两个长变量,
static long stopTime = 0;
static long startTime = -99;
我试图这样设置开始时间onResume()
和结束时间onPause()
:
暂停:
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
stopTime = SystemClock.currentThreadTimeMillis();
Log.d("OnPause","stopTime: "+stopTime);
}
简历:
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (startTime == -99)
{
startTime = SystemClock.currentThreadTimeMillis();
Log.d("OnPause","THIS IS RESUME : startTime: "+startTime);
}
}
当我startTime
首先启动时,我给它一个值-99,所以只有当这是它的值时,onResume
我才会将它的值更新为 currentmillis。
然后将一个 long 传递stopTime - startTime
给
putExtra("totalTime", this.stopTime - this.startTime);
另一个获取该值并将其呈现给用户的活动。我这样做是使用一个名为 moveToEndScreen() 的方法,该方法在游戏结束时调用:
private void moveToEndScreen() {
// TODO Auto-generated method stub
Intent i = new Intent(con, EndScreen.class);
i.putExtra("err", errTimes);
i.putExtra("timeScore", stopTime - startTime);
startActivity(i);
}
这就是下一个活动发生的情况:
public class EndScreen extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Intent i = getIntent();
long timeScore = i.getLongExtra("timeScore",15);
Log.d("END SCREEN timeScore THAT I GOT IS",timeScore+"");
float timeResult = timeScore / 1000;
int errors = i.getIntExtra("err", -1);
setContentView(R.layout.endscreen);
TextView stat = (TextView) findViewById(R.id.errMsg);
stat.setText("You have completed the puzzle in "+errors+" false matches total, and it took you "+timeResult+ " seconds. Can you do better? :)");
}
}
将 Log.donResume
和onPause
具有停止和开始时间值的方法导入后,我发现这些方法运行的次数超出了我的预期,并且给了我不合理的值(负数或零)。另外,我现在看到游戏结束时,布局上的数字在 1 秒后从 0 变为 3。
我应该如何解决这个问题?