SoFunction
Updated on 2025-04-09

Android implements countdown function (start, pause, end in 0 seconds)

The examples in this article share with you the specific code for Android to implement the countdown function for your reference. The specific content is as follows

【Thoughts】:The timer executes the task of cycle delay through the timer. The timing information is updated in the handler and the periodic task of the timer is ended at the end of the timer.

- Add a TextView and Button control to the layout file, and get the ids of the TextView and Button in the onCreate method;

xml layout code:

<Button
   android:
   android:layout_width="0dp"
   android:layout_height="wrap_content"
   android:layout_weight="1"
   android:layout_gravity="center_vertical"
   android:gravity="center"
   android:text="start"
   android:textSize="12sp"
   />

<TextView
   android:
   android:layout_width="0dp"
   android:layout_height="wrap_content"
   android:layout_gravity="center_vertical"
   android:layout_weight="2"
   android:gravity="center"
   android:text="24"
   android:textColor="#33ff00"
   android:textSize="60sp" />

Java code

package ;

import .;
import ;
import ;
import ;
import ;
import ;
import ;

import ;
import ;
import ;

public class SimpleGameonActivity extends AppCompatActivity {

 private final static int COUNT = 1;
 private final static int TOTAL_TIME_24 = 24;
 private TextView textViewTime24;
 Timer timer;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  (savedInstanceState);
  setContentView(.activity_simple_gameon);
  textViewTime24=(TextView)findViewById(.textViewTime24);//24 seconds countdown  final Button button_start_timer = (Button)findViewById(.button_start_timer);
  button_start_timer.setOnClickListener(new () {
   @Override
   public void onClick(View v) {
    String str = button_start_timer.getText().toString();//Get the button string    if(("start")){ //Switch button text     button_start_timer.setText("pause");
     initView();
    }
    else{
     button_start_timer.setText("start");
     ();//Terminate the thread    }
   }
  });
 }
 public void initView(){
  //countDown = (TextView) findViewById(.textViewTime24);
  timer = new Timer();
  /**
    * Send a message to handler every second to update the UI
    * schedule(TimerTask task, long delay, long period)
    */
  (new TimerTask() {
   @Override
   public void run() {
    (COUNT);
   }
  }, 0, 1000);
 }
 private Handler handler = new Handler(){
  int num = TOTAL_TIME_24;
  public void handleMessage( msg) {
   switch () {
    case COUNT:
     ((num));
     if(num == 0)
      ();//End of 0 seconds     num--;
     break;
    default:
     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.