为什么80%的码农都做不了架构师?>>>
原文地址:http://my.oschina.net/reone/blog/710003
多谢touch_ping 的回应. 原来api有这个类 android.os.CountDownTimer , 具体实现很下面的差不多.
import android.content.Context;
import android.os.Handler;/*** Created by wangxingsheng on 16/7/11.*/public class CalculatorUtil {private Context mContext;public CalculatorUtil(Context context){mContext = context;}public void startTimer(final int delay,final OnOverListener listener){final Handler handler = new Handler(mContext.getMainLooper());Runnable runnable = new Runnable(){private int count = 0;@Overridepublic void run() {count++;if(count < delay){listener.onTick(delay - count);handler.postDelayed(this,1000);}else{listener.onOver();}}};handler.post(runnable);}public interface OnOverListener{void onOver();//数字跳到0时调用此方法void onTick(int tick);//第一次调用为总数 - 1,最后一次调用是1}
}
这段程序可能存在问题(例如handler生命周期丶线程继续运行等因素导致的问题),因为用途简单 没有深究.欢迎提出问题
上面的代码没有停止功能,下面是改善之后的代码.
import android.content.Context;
import android.os.Handler;/*** Created by wangxingsheng on 16/7/11.*/public class CalculatorUtil {private Context mContext;private boolean requestStop;private Handler handler;private int mDelay;private OnOverListener mListener;public CalculatorUtil(Context context,int delay,OnOverListener listener){mContext = context;handler = new Handler(mContext.getMainLooper());mDelay = delay;mListener = listener;}public void startTimer(){requestStop = false;handler.post(runnable);}private Runnable runnable = new Runnable(){private int count = 0;@Overridepublic void run() {if(requestStop){return;}count++;if(count < mDelay){mListener.onTick(mDelay - count);handler.postDelayed(runnable,1000);}else{mListener.onOver();}}};public void stopTimer(){requestStop = true;handler.removeCallbacks(runnable);}public interface OnOverListener{void onOver();//数字跳到0时调用此方法void onTick(int tick);//第一次调用为总数 - 1,最后一次调用是1}
}
本博客原地址:http://my.oschina.net/reone/blog/710003