How to implement timed loop tasks in Android

1. Use Handler to implement timing loop

1. Set the timing cycle time

public static final int REGULAR_TIME = 60 * 60 * 1000;  //1小时

2. Obtain the global handler

mHandler = new Handler(Looper.getMainLooper(), this);

3. Set the timed loop task method Runnable

Runnable runnable = new Runnable() {
	//要执行的任务
	aaa();
	mUiHandler.postDelayed(this , REGULAR_TIME); //循环执行
}

4. Call the corresponding place and start the timed loop

//可以先执行一次
aaa();  
//1小时后开启定时循环执行
mUiHandler.postDelayed(runnable,REGULAR_TIME); 

2. Timer timer

1. Set the timer

Timer timer;
TimerTask timerTask;
//设置定时器和任务的方法
protected void initTimer(){
    timer = new Timer();
    timerTask = new TimerTask() {
        @Override
        public void run() {
            //要执行的任务
            //TODO
            Log.i(TAG, "执行任务");
        }
    };
}

2. Start execution

//5秒后执行,然后每隔5秒执行一次(任务是打印“执行任务”)
timer.schedule(timerTask,5*1000,5*1000);

3. Stop canceling the timer

timer.cancel();
timer = null;
timerTask.cancel();
timerTask = null;

4. Restart the timer

//重新设置定时器,并开启
initTimer();
timer.schedule(timerTask,5*1000,5*1000);

5. Test results
Insert image description here
6. Test demo

Insert image description here

(1)MainActivity

package com.example.test;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;

/**
 * @author
 */
public class MainActivity extends AppCompatActivity {

    String TAG = "my";

    TextView tvStart, tvStop, tvRestart,gotoLauncher;
    Timer timer;
    TimerTask timerTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initViewAndListener();
        //设置定时器
        initTimer();

    }

    /**
     * 设置定时器
     */
    protected void initTimer(){
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                Log.i(TAG, "执行任务");
            }
        };
    }

    protected void initViewAndListener(){
        tvStart = findViewById(R.id.tv_start);
        tvStop = findViewById(R.id.tv_stop);
        tvRestart = findViewById(R.id.tv_restart);
        gotoLauncher = findViewById(R.id.textView);

        tvStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e(TAG, "onClick: 开始");
                //开始定时器,每隔5秒打印一次“执行任务”
                timer.schedule(timerTask,5*1000,5*1000);
            }
        });
        tvStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e(TAG, "onClick: 取消定时器");
                timer.cancel();
                timer = null;
                timerTask.cancel();
                timerTask = null;
            }
        });
        tvRestart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e(TAG, "onClick: 重新开启");
                //重新设置定时器,并开启
                initTimer();
                timer.schedule(timerTask,5*1000,5*1000);
            }
        });
        gotoLauncher.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }
}

(2)activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv_start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/start"
        android:paddingStart="20dp"
        android:paddingEnd="20dp"
        android:paddingTop="20dp"
        android:paddingBottom="20dp"
        android:background="@drawable/textview_shape"
        app:layout_constraintBottom_toTopOf="@+id/textView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/tv_stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/stop"
        android:paddingStart="20dp"
        android:paddingEnd="20dp"
        android:paddingTop="20dp"
        android:paddingBottom="20dp"
        android:background="@drawable/textview_shape"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/textView"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/tv_restart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/restart"
        android:paddingStart="20dp"
        android:paddingEnd="20dp"
        android:paddingTop="20dp"
        android:paddingBottom="20dp"
        android:background="@drawable/textview_shape"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/textView"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

(3) TextView background, set borders and rounded corners

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <corners android:radius="10dp"/>

    <stroke
        android:width="1dp"
        android:color="@color/black"/>

</shape>

3. Continuously updating

Guess you like

Origin blog.csdn.net/qq_46269365/article/details/128836485