实现倒计时想到了三个方案
1.countDownTimer
sdk较高版本有bug 计时不精准
2.timer 和timer task的方式
但是在timertask不可以直接更新页面,还是需要用handler去更新界面。
3.handler可以用 sendEmptyMessageDelayed可以实现倒计时
而且倒计时本身没有耗时操作也不要开子线程
Handler 实现
private static class MyHandler extends Handler {
WeakReference<MyFragment> mWeakReference;
MyHandler(MyFragment fragment) {
mWeakReference = new WeakReference<>(fragment);
}
@Override
public void handleMessage(Message msg) {
final MyFragment fragment = mWeakReference.get();
if (fragment == null)
return;
switch (msg.what) {
case RESTART_COUNT_DOWN:
mHandler.removeCallbacksAndMessages(null);
fragment.countDownCount = 300;
sendEmptyMessage(START_COUNT_DOWN);
break;
case START_COUNT_DOWN:
if (fragment.countDownCount > 0) {
String time = fragment.converterToTime(fragment.countDownCount);
fragment.timeTv.setText(time);
sendEmptyMessageDelayed(START_COUNT_DOWN, 1000);
fragment.countDownCount--;
} else {
sendEmptyMessage(RESTART_COUNT_DOWN);
}
break;
}
}
}
//转换成 分钟:秒的形式 例如 05:00
private String converterToTime(int countDownCount) {
int minute = countDownCount / 60;
int second = countDownCount % 60;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(0);
stringBuilder.append(minute);
stringBuilder.append(":");
if (second < 10) {
stringBuilder.append(0);
}
stringBuilder.append(second);
return stringBuilder.toString();
}
fragment中调用
mHandler = new MyHandler(this);
移除所有信息
@Override
public void onDestroy() {
super.onDestroy();
if (mHandler != null) {
mHandler.removeCallbacksAndMessages(null);
}
}
网友评论