SystemClock.uptimeMillis()
clock keeps running when the device is not in deep sleep. You only capture the start clock time once in mStartTime
, so the difference between current upTimeMillis()
and mStartTime
grows. Pausing only stops the mUpdateTimeTask
that formats the time difference to mTimerLabel
.
How to resume it when i click resume button?
-
31-03-2022 - |
Question
//Counter of time since app started ,a background task
private long mStartTime = 0L;
//Private long mPauseTime = 0L;
private TextView mTimerLabel;
//Handler to handle the message to the timer task
private Handler mHandler = new Handler();
static final int UPDATE_INTERVAL = 1000;
String timerStop1;
@Override
public void onCreate(Bundle savedInstanceState) {
mTimerLabel = (TextView) findViewById(R.id.textTimer);
if(mStartTime == 0L){
mStartTime = SystemClock.uptimeMillis();
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 100);
}
timerPauseButton.setTag(1);
timerPauseButton.setText("Pause");
final Button timerPauseButton = (Button) findViewById(R.id.btnTimerPause);
timerPauseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view){
//ChangeButtonText
final int status =(Integer) view.getTag();
if(status == 1) {
mHandler.removeCallbacks(mUpdateTimeTask);
mTimerLabel.setText(timerStop1);
timerPauseButton.setText("Resume");
view.setTag(0); //resume
} else{
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 100);
timerPauseButton.setText("Pause");
view.setTag(1); //pause
}
}
});
}
//End of OnCreate
private Runnable mUpdateTimeTask = new Runnable(){
public void run() {
{
final long start = mStartTime;
long millis = SystemClock.uptimeMillis()- start;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
mTimerLabel.setText("" + minutes + ":"
+ String.format("%02d", seconds));
timerStop1 = minutes + ":"
+ String.format("%02d", seconds);
mHandler.postDelayed(this, 200);
}
}
};
Why I click the pause button but timer also will run in background? Example when I click pause in 3sec after 5sec I click resume but it continue go on with 8sec and not 3sec? Thanks
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow