Android 使用 CountDownTimer
05 Sep 2013在onResume()方法中构造CountDownTimer
的好处是,onResume()是在onRestoreInstanceState()
之后执行的, 这样就可以在onRestoreInstanceState()
中恢复上次倒计时后的剩余时间,这样在手机屏幕旋转后,倒计时不会重置。
MainActivity.java
package com.example.countdowntimeexample;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView mTimeLabel;
CountDownTimer myTimer;
long myTime = 30000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTimeLabel = (TextView) findViewById(R.id.text);
}
@Override
protected void onResume() {
myTimer = new CountDownTimer(myTime, 1000) {
@Override
public void onTick(long arg0) {
mTimeLabel.setText("second remaining: " + arg0 / 1000);
myTime = arg0;
}
@Override
public void onFinish() {
mTimeLabel.setText("done!");
myTime = 0;
}
}.start();
super.onResume();
}
@Override
protected void onStop() {
myTimer.cancel(); // 取消计时器
super.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
// 保存本次倒计时余下的时间,以便在acitivity再次激活的时候能从上次的断点继续倒计时
outState.putLong("time", myTime);
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// 恢复上次倒计时断点,onResume函数将使用这个值来构造CountDownTimer
myTime = savedInstanceState.getLong("time");
super.onRestoreInstanceState(savedInstanceState);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>