效果图:

封装好的工具类:TimeUtils.java
package com.xiao7.pump.Utils;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
import java.util.Timer;
import java.util.TimerTask;
public class TimeUtils {
public static int COUNT = 20*60;
private static int CURR_COUNT = 0;
private static long TIME_END = 0;
private static Timer countdownTimer;
private static TextView txtCountdown;
public static void startCountdown(boolean isFirst,int second,TextView textView) {
COUNT = second;
long data = System.currentTimeMillis();
long time = TIME_END;
if(isFirst){
CURR_COUNT = COUNT;
time = data + COUNT * 1000;
TIME_END = time;
}else {
int the_difference = ((int) (time - data)) / 1000;
CURR_COUNT = the_difference;
}
txtCountdown = textView;
if (countdownTimer == null) {
countdownTimer = new Timer();
countdownTimer.schedule(new TimerTask() {
@Override
public void run() {
Message msg = new Message();
msg.what = CURR_COUNT--;
handler.sendMessage(msg);
}
}, 0, 1000);
}
}
public static void stopCountdown() {
Message message = new Message();
message.what = 0;
handler.sendMessage(message);
}
private static Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what <= 0) {
if (countdownTimer != null) {
countdownTimer.cancel();
countdownTimer = null;
}
txtCountdown.setText("剩余:00:00:00");
txtCountdown.setEnabled(true);
} else {
String txtTime = formatSecondTime(msg.what);
txtCountdown.setText(txtTime);
txtCountdown.setEnabled(false);
}
super.handleMessage(msg);
}
};
private static String formatSecondTime(int second) {
int hour = 0;
int minute = 0;
if (second > 60) {
minute = second / 60;
second = second % 60;
}
if (minute > 60) {
hour = minute / 60;
minute = minute % 60;
}
String strtime = "剩余:"+hour+"小时"+minute+"分"+second+"秒";
return strtime;
}
}
TimeUtils调用方式:
buttonStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int secondTime=20*60;
TimeUtils.startCountdown(true,secondTime,txtCountDown);
}
});
活动的生命周期onRestart()上重新调用,如下:
@Override
protected void onRestart() {
super.onRestart();
TimeUtils.startCountdown(false,secondTime,txtCountDown);
}