android倒计时

import android.os.CountDownTimer;
import android.view.MenuItem;

import java.lang.ref.WeakReference;

/**
 * Created by Administrator on 2016/4/8.
 */
public class ExerciseTimeCountUtils extends CountDownTimer {

    private WeakReference<MenuItem> weakReference;

    private ExerciseTimeListener exerciseTimeListener;

    /**
     * @param millisInFuture:45*60*1000=2700000
     * @param countDownInterval
     */
    public ExerciseTimeCountUtils(long millisInFuture, long countDownInterval, MenuItem view) {
        super(millisInFuture, countDownInterval);
        weakReference = new WeakReference<MenuItem>(view);
    }

    @Override
    public void onTick(long millisUntilFinished) {
        long time = millisUntilFinished / 1000;
        long minute = time / 60;
        long second = time % 60 + 1;
        MenuItem menuItem = weakReference.get();
        if (menuItem != null) {
            if (minute == 0) {
                if (second == 0) {
                    menuItem.setTitle("超时");
                } else {
                    second--;
                    if (second >= 10) {
                        menuItem.setTitle("0" + minute + ":" + second);
                    } else {
                        menuItem.setTitle("0" + minute + ":0" + second);
                    }
                }
            } else {
                if (second == 0) {
                    second = 59;
                    minute--;
                    if (minute >= 10) {
                        menuItem.setTitle(minute + ":" + second);
                    } else {
                        menuItem.setTitle("0" + minute + ":" + second);
                    }
                } else {
                    second--;
                    if (second >= 10) {
                        if (minute >= 10) {
                            menuItem.setTitle(minute + ":" + second);
                        } else {
                            menuItem.setTitle("0" + minute + ":" + second);
                        }
                    } else {
                        if (minute >= 10) {
                            menuItem.setTitle(minute + ":0" + second);
                        } else {
                            menuItem.setTitle("0" + minute + ":0" + second);
                        }
                    }
                }
            }
        }

    }

    @Override
    public void onFinish() {
        MenuItem menuItem = weakReference.get();
        if (menuItem != null)
            menuItem.setTitle("超时");
        if (exerciseTimeListener != null) {
            exerciseTimeListener.onExerciseTimeCountUtils();
        }
    }

    public interface ExerciseTimeListener {
        public void onExerciseTimeCountUtils();
    }

    public void setExerciseTimeListener(ExerciseTimeListener exerciseTimeListener) {
        this.exerciseTimeListener = exerciseTimeListener;
    }
}


你可能感兴趣的:(android倒计时)