这是我的活动代码。在这里我打印文本视图上经过的时间。我想在此放置onPause和onResume方法。它应该工作,以便在应用程序处于后台时暂停时间。当再次出现在最前沿时,定时器应该从它暂停的地方开始。我尝试使用此代码,但时间没有暂停。它继续在后台运行。任何人都可以帮忙找到解决方法。
package com.example.test;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView tt1;
private Handler customHandler = new Handler();
long timeInMilliseconds = 0L,timeToGo=0L,startTime=0L;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tt1=(TextView) findViewById(R.id.textView1);
startTime=System.currentTimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
}
public Runnable updateTimerThread=new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
long timeNow = System.currentTimeMillis();
timeToGo = 30 - (timeNow - startTime) / 1000;
tt1=(TextView) findViewById(R.id.textView1);
tt1.setText(timeToGo+"");
if(timeToGo<0L){
Intent intent=new Intent(MainActivity.this,Game.class);
finish();
startActivity(intent);
}
else
customHandler.postDelayed(this, 0);
}
};
@Override
public void onPause() {
super.onPause();
customHandler.removeCallbacksAndMessages(null);
}
@Override
public void onResume() {
super.onResume(); // Always call the superclass method first
customHandler.postDelayed(updateTimerThread, 0);
}
}
答案 0 :(得分:0)
你需要在onResume中更新你的startTime,因为它还没有改变......
@Override
public void onResume() {
startTime = System.currenTimeMillis() - timeToGo * 1000;
...
}
或者只使用Chronometer类http://developer.android.com/reference/android/widget/Chronometer.html
答案 1 :(得分:0)
@Override
protected void onPause() {
customHandler.removeCallbacks(updateTimerThread);
super.onPause(); }