Android实现计时与倒计时(限时抢购)的几种方法
在购物网站的促销活动中一般都有倒计时限制购物时间或者折扣的时间,这些都是如何实现的呢?
在最近的一个安卓客户端项目中恰好遇到了类似的问题,一开始使用的是Timer与 TimerTask, 虽然此方法通用,但后来考虑在安卓中是否有更佳的方案,于是乎共找到以下五种实现方案,最终我使用了方案五完成了此功能.
效果如图:
方法一
Timer与TimerTask(Java实现)
[java]
public class timerTask extends Activity{
private int recLen = 11;
private TextView txtView;
Timer timer = new Timer();
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.timertask);
txtView = (TextView)findViewById(R.id.txttime);
timer.schedule(task, 1000, 1000); // timeTask
}
TimerTask task = new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() { // UI thread
@Override
public void run() {
recLen--;
txtView.setText(""+recLen);
if(recLen < 0){
timer.cancel();
txtView.setVisibility(View.GONE);
}
}
});
}
};
}
public class timerTask extends Activity{
private int recLen = 11;
private TextView txtView;
Timer timer = new Timer();
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.timertask);
txtView = (TextView)findViewById(R.id.txttime);
timer.schedule(task, 1000, 1000); // timeTask
}
TimerTask task = new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() { // UI thread
@Override
public void run() {
recLen--;
txtView.setText(""+recLen);
if(recLen < 0){
timer.cancel();
txtView.setVisibility(View.GONE);
}
}
});
}
};
}
方法二
TimerTask与Handler(不用Timer的改进型)
[java]
public class timerTask extends Activity{
private int recLen = 11;
private TextView txtView;
Timer timer = new Timer();
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.timertask);
txtView = (TextView)findViewById(R.id.txttime);
timer.schedule(task, 1000, 1000); // timeTask
}
final Handler handler = new Handler(){
@Override
public void handleMessage(Message msg){
switch (msg.what) {
case 1:
&n
补充:移动开发 , Android ,