我正在使用自定义的 TextView 在 ListView 中频繁更新时间,它工作正常。问题是计时器不断重复其任务,但活动已经完成。
请解释如何在活动完成后停止计时器。
public class TextViewTimerUpdate extends TextView {
private TimerTask mTimerTask;
private Timer mTimer;
private CharSequence mRelativeTime;
public TextViewTimerUpdate(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TextViewTimerUpdate(Context context) {
super(context);
}
public TextViewTimerUpdate(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
private CharSequence mText;
public void setTextForTime(final CharSequence text) {
mText = text;
startTimer();
}
public void startTimer() {
Logger.i("startTimer", "startTimer");
stopTimer();
mTimer = new Timer();
mTimerTask = new TimerTask() {
@Override
public void run() {
// postInvalidate();
Logger.i("timer", "timer");
Thread th = new Thread(new Runnable() {
@Override
public void run() {
Logger.i("thread", "thread");
mRelativeTime = DateUtils.getRelativeTimeSpanString(
Long.parseLong(mText + ""),
System.currentTimeMillis()
, 0);
handler.sendEmptyMessage(0);
}
});
th.run();
}
};
mTimer.scheduleAtFixedRate(mTimerTask, 0, 8000);
}
public void stopTimer() {
if (mTimer != null) {
mTimer.cancel();
mTimer = null;
}
}
private void justSetText(CharSequence text) {
Logger.e("justSetText", text + "");
super.setText(text + "", null);
}
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
justSetText(mRelativeTime);
};
};
}