Android 实现抢购倒计时功能的示例

一、效果图

二、思路

算多少秒,秒数取余60,(满足分后剩下的秒数)
算多少分,秒数除60,再取余60 (总分数满足小时后剩下的分数)
算多少时,秒数除60,除60,再取余24 (总小时满足天后剩下的小时)
算多少天,秒数除60,除60,除24 等到的整数就是天数

三、实现步骤:

我们这里的时间格式为后台返回,格式为:

2021-12-24 00:00:00

1、时间转换的工具类

 //将年-月-天 时:分:秒转化为毫秒格式
 public static long residueTimeout(String endDate, String newDate) throws ParseException {

  SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  Date d1 = df.parse(endDate);
  Date d2 = df.parse(newDate);
  long diff = d1.getTime() - d2.getTime();

  return diff;
 }

 /*
  * 将毫秒转换成时间戳
  */
 public static String stampToDate(Long s) {
  String res;
  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  Date date = new Date(s);
  res = simpleDateFormat.format(date);
  return res;
 }

2、时间倒计时工具类

package com.sjl.keeplive.huawei;
import android.os.CountDownTimer;

/**
 * 倒计时工具类
 */
public class CountDownTimerUtils {
 /**
  * 倒计时结束的回调接口
  */
 public interface FinishDelegate {
  void onFinish();
 }

 /**
  * 定期回调的接口
  */
 public interface TickDelegate {
  void onTick(long pMillisUntilFinished);
 }

 private final static long ONE_SECOND = 1000;
 /**
  * 总倒计时时间
  */
 private long mMillisInFuture = 0;
 /**
  * 定期回调的时间 必须大于0 否则会出现ANR
  */
 private long mCountDownInterval;
 /**
  * 倒计时结束的回调
  */
 private FinishDelegate mFinishDelegate;
 /**
  * 定期回调
  */
 private TickDelegate mTickDelegate;
 private MyCountDownTimer mCountDownTimer;

 /**
  * 获取 CountDownTimerUtils
  *
  * @return CountDownTimerUtils
  */
 public static CountDownTimerUtils getCountDownTimer() {
  return new CountDownTimerUtils();
 }

 /**
  * 设置定期回调的时间 调用{@link #setTickDelegate(TickDelegate)}
  *
  * @param pCountDownInterval 定期回调的时间 必须大于0
  * @return CountDownTimerUtils
  */
 public CountDownTimerUtils setCountDownInterval(long pCountDownInterval) {
  this.mCountDownInterval = pCountDownInterval;
  return this;
 }

 /**
  * 设置倒计时结束的回调
  *
  * @param pFinishDelegate 倒计时结束的回调接口
  * @return CountDownTimerUtils
  */
 public CountDownTimerUtils setFinishDelegate(FinishDelegate pFinishDelegate) {
  this.mFinishDelegate = pFinishDelegate;
  return this;
 }

 /**
  * 设置总倒计时时间
  *
  * @param pMillisInFuture 总倒计时时间
  * @return CountDownTimerUtils
  */
 public CountDownTimerUtils setMillisInFuture(long pMillisInFuture) {
  this.mMillisInFuture = pMillisInFuture;
  return this;
 }

 /**
  * 设置定期回调
  *
  * @param pTickDelegate 定期回调接口
  * @return CountDownTimerUtils
  */
 public CountDownTimerUtils setTickDelegate(TickDelegate pTickDelegate) {
  this.mTickDelegate = pTickDelegate;
  return this;
 }

 public void create() {
  if (mCountDownTimer != null) {
   mCountDownTimer.cancel();
   mCountDownTimer = null;
  }
  if (mCountDownInterval <= 0) {
   mCountDownInterval = mMillisInFuture + ONE_SECOND;
  }
  mCountDownTimer = new MyCountDownTimer(mMillisInFuture, mCountDownInterval);
  mCountDownTimer.setTickDelegate(mTickDelegate);
  mCountDownTimer.setFinishDelegate(mFinishDelegate);
 }

 /**
  * 开始倒计时
  */
 public void start() {
  if (mCountDownTimer == null) {
   create();
  }
  mCountDownTimer.start();
 }

 /**
  * 取消倒计时
  */
 public void cancel() {
  if (mCountDownTimer != null) {
   mCountDownTimer.cancel();
  }
 }

 private static class MyCountDownTimer extends CountDownTimer {
  private FinishDelegate mFinishDelegate;
  private TickDelegate mTickDelegate;

  /**
   * @param millisInFuture The number of millis in the future from the call
   *       to {@link #start()} until the countdown is done and {@link #onFinish()}
   *       is called.
   * @param countDownInterval The interval along the way to receive
   *       {@link #onTick(long)} callbacks.
   */
  public MyCountDownTimer(long millisInFuture, long countDownInterval) {
   super(millisInFuture, countDownInterval);
  }

  @Override
  public void onTick(long millisUntilFinished) {
   if (mTickDelegate != null) {
    mTickDelegate.onTick(millisUntilFinished);
   }
  }

  @Override
  public void onFinish() {
   if (mFinishDelegate != null) {
    mFinishDelegate.onFinish();
   }
  }

  void setFinishDelegate(FinishDelegate pFinishDelegate) {
   this.mFinishDelegate = pFinishDelegate;
  }

  void setTickDelegate(TickDelegate pTickDelegate) {
   this.mTickDelegate = pTickDelegate;
  }
 }
}

3、布局文件

 <LinearLayout
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_gravity="center"
  android:orientation="horizontal">

  <TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="抢购倒计时:" />

  <TextView
   android:id="@+id/text_day"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:background="#ff0000"
   android:padding="5dp"
   android:text="00" />

  <TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text=" 天 " />

  <TextView
   android:id="@+id/text_hour"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:background="#ff0000"
   android:padding="5dp"
   android:text="00" />

  <TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text=" 时 " />

  <TextView
   android:id="@+id/text_minute"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:background="#ff0000"
   android:padding="5dp"
   android:text="00" />

  <TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text=" 分 " />

  <TextView
   android:id="@+id/text_second"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:background="#ff0000"
   android:padding="5dp"
   android:text="00" />

  <TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text=" 秒 " />

 </LinearLayout>

4、倒计时显示处理

 public static void liveDescCountTime(long ms, TextView tvDays, TextView tvHour, TextView tvMinutes, TextView tvSeconds) {
  long totalSeconds = ms / 1000;
  long seconds = totalSeconds % 60;
  long minutes = totalSeconds / 60 % 60;
  long hours = totalSeconds / 60 / 60 % 24;
  long days = totalSeconds / 60 / 60 / 24;

  String dayStr = "";
  if (days > 0) {
   if (days > 9) {
    dayStr += days + "";
   } else if (days > 0) {
    dayStr += "0" + days + "";
   } else {
    dayStr += "00";
   }
  } else {
   dayStr = "00";
  }
  tvDays.setText(dayStr);

  String hourStr = "";
  if (hours > 0) {
   if (hours > 9) {
    hourStr += hours + "";
   } else if (hours > 0) {
    hourStr += "0" + hours + "";
   } else {
    hourStr += "00";
   }
  } else {
   hourStr = "00";
  }
  tvHour.setText(hourStr);

  String minutesStr = "";
  if (minutes > 0) {
   if (minutes > 9) {
    minutesStr += minutes + "";
   } else if (minutes > 0) {
    minutesStr += "0" + minutes + "";
   } else {
    minutesStr += "00";
   }
  } else {
   minutesStr = "00";
  }
  tvMinutes.setText(minutesStr);

  String secondStr = "";
  if (minutes > 0) {
   if (seconds > 9) {
    secondStr += seconds;
   } else if (seconds > 0) {
    secondStr += "0" + seconds;
   } else {
    secondStr += "00";
   }
  } else {
   secondStr = "00";
  }
  tvSeconds.setText(secondStr);
 }

5、开始倒计时

        final TextView text_day = findViewById(R.id.text_day);
  final TextView text_hour = findViewById(R.id.text_hour);
  final TextView text_minute = findViewById(R.id.text_minute);
  final TextView text_second = findViewById(R.id.text_second);

  long residueTime = 0;
        //获取当前时间
  String stampToDate = stampToDate(System.currentTimeMillis());
  try {
            //2021-12-24 00:00:00为模拟倒计时间数据
   residueTime = residueTimeout("2021-12-24 00:00:00", stampToDate);
  } catch (ParseException e) {
   e.printStackTrace();
  }

        //倒计时
  CountDownTimerUtils.getCountDownTimer()
    .setMillisInFuture(residueTime)
    .setCountDownInterval(1000)
    .setTickDelegate(new CountDownTimerUtils.TickDelegate() {
     @Override
     public void onTick(long pMillisUntilFinished) {
      liveDescCountTime(pMillisUntilFinished, text_day, text_hour, text_minute, text_second);
     }
    })
    .setFinishDelegate(new CountDownTimerUtils.FinishDelegate() {
     @Override
     public void onFinish() {
      //倒计时完成后处理
     }
    }).start();

以上就是Android 实现抢购倒计时功能的示例的详细内容,更多关于Android 抢购倒计时功能的资料请关注我们其它相关文章!

(0)

相关推荐

  • android利用handler实现倒计时功能

    本文实例为大家分享了android利用handler实现倒计时的具体代码,供大家参考,具体内容如下 xml <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app=&qu

  • android实现圆环倒计时控件

    本文实例为大家分享了android实现圆环倒计时控件的具体代码,供大家参考,具体内容如下 1.自定义属性 <?xml version="1.0" encoding="utf-8"?> <resources> <!-- 倒计时控件属性 --> <declare-styleable name="CountDownView"> <!--颜色--> <attr name="rin

  • Android自定义view实现倒计时控件

    本文实例为大家分享了Android自定义view实现倒计时控件的具体代码,供大家参考,具体内容如下 直接上代码 自定义TextView 文字展示 public class StrokeTextView extends TextView { private TextView borderText = null;///用于描边的TextView private Context mContext; public StrokeTextView(Context context) { super(conte

  • Android 倒计时控件 CountDownView的实例代码详解

    一个精简可自定义的倒计时控件,使用 Canvas.drawArc() 绘制.实现了应用开屏页的圆环扫过的进度条效果. 代码见https://github.com/hanjx-dut/CountDownView 使用 allprojects { repositories { ... maven { url 'https://jitpack.io' } } } dependencies { implementation 'com.github.hanjx-dut:CountDownView:1.1'

  • Android限时抢购倒计时实现代码

    限时抢购倒计时实现效果图 布局: <LinearLayout android:id="@+id/ll_xsqg" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:paddingTop="8dp" android:paddin

  • android实现倒计时功能(开始、暂停、0秒结束)

    本文实例为大家分享了android实现倒计时功能的具体代码,供大家参考,具体内容如下 [思路]:通过 timer 执行周期延时的任务,handler 中将计时信息更新,并在计时结束时结束 timer 的周期任务. - 在布局文件中添加一个TextView和Button控件,并在onCreate方法中获得到TextView和Button的id: xml布局代码: <Button android:id="@+id/button_start_timer" android:layout_

  • Android实现倒计时效果

    本文实例为大家分享了Android实现倒计时效果的具体代码,供大家参考,具体内容如下 一个倒计时的效果 先看效果图: 直接上代码: 这里是关于倒计时 -天时分秒-的逻辑判断 /** * 倒计时计算 */ private void computeTime() { mSecond--; if (mSecond < 0) { mMin--; mSecond = 59; if (mMin < 0) { mMin = 59; mHour--; if (mHour < 0) { // 倒计时结束 m

  • Android计时与倒计时实现限时抢购的5种方法

    在购物网站的促销活动中一般都有倒计时限制购物时间或者折扣的时间,这些都是如何实现的呢? 在一个安卓客户端项目中恰好遇到了类似的问题,一开始使用的是Timer与 TimerTask, 虽然此方法通用,但后来考虑在安卓中是否有更佳的方案,于是乎共找到以下五种实现方案,另外还有一种使用CountDownTimer进行计时的方面,我会在单独的文章中进行介绍 效果如图: 方法一 Timer与TimerTask(Java实现) public class timerTask extends Activity{

  • Android实现自定义倒计时

    最近工作中遇到个要做倒计时60秒的进度条,经过参考别人的资料做出来需求的效果.废话少说先来个效果: 一定想知道是怎么实现的吧!下面是代码 public class CountDownView extends View { //圆轮颜色 private int mRingColor; //默认圆颜色 private int mRingNormalColor ; //圆轮宽度 private float mRingWidth; //圆轮进度值文本大小 private int mRingProgess

  • Android 简单实现倒计时功能

    在 Android 中倒计时功能是比较常用的一个功能,比如短信验证码,付款倒计时等.实现方式有Handler.Thread 等,但是实现起来都有点麻烦,其实Android已经为我们封装好了一个抽象类 CountDownTimer,可以简单的实现倒计时功能,如下图所示. CountDownTimer 实现倒计时功能的机制也是用Handler 消息控制,只是它帮我们已经封装好了,先看一下它的介绍. Schedule a countdown until a time in the future, wi

  • Android倒计时神器(CountDownTimer)

    Android倒计时神器 - CountDownTimer,供大家参考,具体内容如下 啥是CountDownTimer?​ CountDownTimer是Andorid.os包下一个谷歌为我们封装好的一个倒计时工具.我们吗.平时开发过程中像一些验证码.倒计时的功能,如果自己封装一个倒计时工具就会稍显麻烦.而谷歌这个工具使用起来非常方便. 源码 package android.os; public abstract class CountDownTimer { public CountDownTi

  • 解决Android-RecyclerView列表倒计时错乱问题

    前言 转眼间距离上次写博客已是过了一个年轮,期间发生了不少事:经历了离职.找工作,新公司的第一版项目上线.现在总算是有时间可以将遇到的问题梳理下了,后期有时间也会分享更多的东西-- 场景 今天分享的问题是当在列表里面显示倒计时,这时候滑动列表会出现时间显示不正常的问题.首先关于倒计时我们需要注意的问题有以下几方面: 在RecyclerView中ViewHolder的复用导致的时间乱跳的问题. 滑动列表时倒计时会重置的问题. 在退出页面后定时器的资源释放问题,这里我使用的是用系统自带的CountD

随机推荐