Android implements timer function

Time:2021-11-28

This example shares the specific code of Android timer function for your reference. The specific contents are as follows

Timer tool class

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
 
import androidx.annotation.NonNull;
 
import java.util.Timer;
import java.util.TimerTask;
 
/**
 *For timing, use this method in the main thread
 */
public class ChjTimer {
 
    private int time;// Set countdown x seconds
    private int interval = 1000;// Set interval
    private ChjTimerInter chjTimerInter; // Callback
    private Timer timer; //  timer
    private static final int WHAT_ REFREH = 0;// Refresh
 
    /**
     *When an object is created, timing begins
     *
     *@ param chjtimerinter interface callback
     */
    public ChjTimer(ChjTimerInter chjTimerInter) {
        this.chjTimerInter = chjTimerInter;
    }
 
    /**
     *Create object start timing
     *@ param interval interval notification (use the first method, refresh once every 1 second by default)
     *@ param chjtimerinter interface callback
     */
    public ChjTimer(int interval, ChjTimerInter chjTimerInter) {
        this.chjTimerInter = chjTimerInter;
        this.interval = interval;
    }
 
    /**
     *Start timing
     */
    public void start(int time) {
        this.time = time;
        if (timer == null){
            timer = new Timer();
        } else {
            stop();
            return;
        }
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                timesss.sendMessage(new Message());
            }
        }, interval);
    }
 
    /**
     *Stop timing
     */
    public void stop() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timesss != null) timesss.removeMessages(WHAT_REFREH);
        if (chjTimerInter != null)chjTimerInter.stop(time);
    }
 
    @SuppressLint("HandlerLeak")
    private Handler timesss = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what != WHAT_REFREH) return;
            time -= 1;
            if (chjTimerInter != null) chjTimerInter.second(time);
            if (time == 0) {
                if (timer == null) return;
                timer.cancel();
                timer = null;
                if (chjTimerInter != null) chjTimerInter.expire();
            } else if (time > 0) {
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        timesss.sendMessage(new Message());
                    }
                }, interval);
            }
        }
    };
 
    /**
     *Interface
     */
    public interface ChjTimerInter {
 
        /**
         *Callback in interval
         */
        void second(int time);
 
        /**
         *Completion callback
         */
        void expire();
 
        /**
         *Stop timing
         */
        void stop(int time);
 
    }
 
}

Use demo

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
 
public class MainActivity extends Activity implements View.OnClickListener, ChjTimer.ChjTimerInter {
 
    private TextView tiems,timnew;
    private ChjTimer chjTimer;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tiems = findViewById(R.id.time);
        timnew = findViewById(R.id.timnew);
        findViewById(R.id.but).setOnClickListener(this);
        findViewById(R.id.buts).setOnClickListener(this);
 
        chjTimer = new ChjTimer(this);
    }
 
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.but:
                tiems.setText("10");
                Timnew.settext ("timing");
                chjTimer.start(10);
                break;
            case R.id.buts:
                chjTimer.stop();
                break;
        }
    }
 
    @Override
    public void second(int time) {
        tiems.setText(time + "");
    }
 
    @Override
    public void expire() {
        Timnew.settext ("timing complete");
    }
 
    @Override
    public void stop(int time) {
        Timnew.settext ("timing termination" + time);
    }
}

Page layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_gravity="center"
    android:gravity="center"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <TextView
        android:id="@+id/timnew"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        Android: text = "timing complete"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
    <TextView
        android:id="@+id/time"
        android:text="0"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
 
 
    <Button
        android:id="@+id/but"
        Android: text = "start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
 
    <Button
        android:id="@+id/buts"
        Android: text = "terminate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
 
</LinearLayout>

Demonstration effect

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support developpaer.