Android Handler Implementation of Splash Screen Page Countdown Code

  • 2021-12-05 07:27:40
  • OfStack

I won't talk too much, let's just look at the code ~


package com.zjx.todayinfomation;
import android.os.Handler;

public class CustomCountDownTimer implements Runnable{
 // 1. Real-time callback   What time is this time   What time is the countdown   Observer design pattern 
 // 2. Total incoming time supported   Dynamic incoming 
 // 3. Every passing 1 Seconds   Total seconds  -1
 // 4. The total time countdown is 0 Time   Callback completion status 
 private int time; //  Total time 
 private int countDowntime; //  Countdown event 
 private IcountDownHandler countDownHandler; //  Callback interface 
 private final Handler handler; // handler
 private boolean isRunning; //  Is it allowed 

 /**
  * @param time  Total time passed in 
  * @param countDownHandler  Interface callback 
  */
 public CustomCountDownTimer(int time,IcountDownHandler countDownHandler){
  handler = new Handler();
  this.time = time;
  this.countDowntime = time; //  Countdown time 1 Times   Is the total time 
  this.countDownHandler = countDownHandler;
 }

 @Override
 public void run() {
  if (isRunning){ //  If it is turned on 
   if (countDownHandler != null){ //  And the callback interface is not empty   Callback the current number of seconds  
    countDownHandler.onTicker(countDowntime); // countDowntime  No. 1 1 The next time you come in is the total time   For example 5
   }
   //  If the current number of seconds is 0  Callback complete 
   if (countDowntime == 0){ 
    cancel();
    if (countDownHandler != null){
     countDownHandler.onFinish();
    }
   }else{
    //  If the current number of seconds part 0  Every time   Decrease 1 Seconds   And   Post-vaccine   Re-execute this run Method 
    countDowntime = time--; // 5 4 3 2 1  Similar 
    handler.postDelayed(this,1000);
   }
  }
 }

 /**
  *  Open run Method 
  */
 public void start(){
  isRunning = true;
  handler.post(this); //  Call run Method 
 }

 /**
  *  Out of the loop   Terminate run Method 
  */
 public void cancel(){
  isRunning = false;
  handler.removeCallbacks(this);
 }

 /**
  *  Observer   Callback interface 
  */
 public interface IcountDownHandler{
  void onTicker(int time);//  Callback event   Countdown 
  void onFinish(); //  Callback complete 
 }
}

Additional knowledge: Countdown is added to every item in android list

Problem with using recyclerview: The current display of view will count down again if it slides out of sight and then slides back

The solution is to switch to listview and use viewholder multiplexing principle to write down the countdown at the first load so that the above problems will not occur


Related articles: