Я использую настраиваемый TextView для частого обновления в ListView, который работает правильно. Проблема заключается в том, что таймер постоянно повторяет свою задачу, но активность заканчивается.Stop Timer() в пользовательском TextView
Пожалуйста, объясните, как остановить таймер при завершении работы.
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);
};
};
}
Timer = Thread, в TimerTask вы создаете другую тему, слава богу, вы называете th.run(); вместо th.star(); и все это для обновления простого текста, что такое отходы. вместо этого просто используйте один простой обработчик с sentEmptyMessageDelayed или даже View.postDelayed – pskink