SoFunction
Updated on 2025-03-11

Android uses handler to implement countdown function

This example shares the specific code for Android using handler to implement countdown for your reference. The specific content is as follows

xml

<?xml version="1.0" encoding="utf-8"?>
< xmlns:andro
 xmlns:app="/apk/res-auto"
 xmlns:tools="/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context=".MainActivity">

 <TextView
  android:
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="Hello World!"
  app:layout_constraintBottom_toBottomOf="parent"
  app:layout_constraintLeft_toLeftOf="parent"
  app:layout_constraintRight_toRightOf="parent"
  app:layout_constraintTop_toTopOf="parent" />

</>

java

package ;

import ;
import ;

import ;
import ;
import ;
import ;

import ;

public class MainActivity extends AppCompatActivity {

 /**
   * Countdown mark handler code
   */
 public static final int COUNT_DOWN_CODE = 10001;
 /**
   * Countdown maximum value
   */
 public static final int MAX_COUNT = 10;
 /**
   * Countdown time interval
   */
 public static final int DELAY_MILLIS = 1000;
 TextView textView;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  (savedInstanceState);
  setContentView(.activity_main);
  textView = findViewById();


  CountdownTimeHandler handler = new CountdownTimeHandler(this);
  Message message = ();
   = COUNT_DOWN_CODE;
  message.arg1 = MAX_COUNT;
  (message, DELAY_MILLIS);


 }

 public static class CountdownTimeHandler extends Handler {
  //Waste references are added to the context  final WeakReference&lt;MainActivity&gt; weakReference;

  //This method needs to be changed so that the context can be directly transmitted to the  public CountdownTimeHandler(MainActivity activity) {
    = new WeakReference&lt;&gt;(activity);
  }

  @Override
  public void handleMessage(@NonNull Message msg) {
   (msg);

   //Get the context   MainActivity activity = ();

   switch () {
    case COUNT_DOWN_CODE:
     int value = msg.arg1;
     ((value--));


     if (value &gt;= 0) {
      //Send the value out again      Message message = ();
       = COUNT_DOWN_CODE;
      message.arg1 = value;
      sendMessageDelayed(message, DELAY_MILLIS);
     }


     break;
   }
  }
 }
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.