android uses handler to realize countdown function
- 2021-12-09 10:16:24
- OfStack
In this paper, we share the specific code of android using handler to realize countdown for your reference. The specific contents are as follows
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/text"
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" />
</androidx.constraintlayout.widget.ConstraintLayout>
java
package com.tcy.handlertest;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
import java.lang.ref.WeakReference;
public class MainActivity extends AppCompatActivity {
/**
* Countdown mark handler code
*/
public static final int COUNT_DOWN_CODE = 10001;
/**
* Maximum countdown
*/
public static final int MAX_COUNT = 10;
/**
* Countdown interval
*/
public static final int DELAY_MILLIS = 1000;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
CountdownTimeHandler handler = new CountdownTimeHandler(this);
Message message = Message.obtain();
message.what = COUNT_DOWN_CODE;
message.arg1 = MAX_COUNT;
handler.sendMessageDelayed(message, DELAY_MILLIS);
}
public static class CountdownTimeHandler extends Handler {
// Weak references are added to the context
final WeakReference<MainActivity> weakReference;
// This method needs to be changed 1 So that you can pass in the context directly
public CountdownTimeHandler(MainActivity activity) {
this.weakReference = new WeakReference<>(activity);
}
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
// Get the context
MainActivity activity = weakReference.get();
switch (msg.what) {
case COUNT_DOWN_CODE:
int value = msg.arg1;
activity.textView.setText(String.valueOf(value--));
if (value >= 0) {
// Put again value Send out
Message message = Message.obtain();
message.what = COUNT_DOWN_CODE;
message.arg1 = value;
sendMessageDelayed(message, DELAY_MILLIS);
}
break;
}
}
}
}