android realizes countdown function (start pause end in 0 seconds)
- 2021-11-13 02:45:31
- OfStack
In this paper, we share the specific code of android to realize countdown function for your reference. The specific contents are as follows
[Thinking]: Execute the task with periodic delay through timer, update the timing information in handler, and end the periodic task of timer at the end of timing.
-Add 1 TextView and Button control to the layout file, and get id to TextView and Button in the onCreate method;
xml layout code:
<Button
android:id="@+id/button_start_timer"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center_vertical"
android:gravity="center"
android:text=" Begin "
android:textSize="12sp"
/>
<TextView
android:id="@+id/textViewTime24"
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 com.example.wlf.gamerecorder.gameon;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.os.Handler;
import com.example.wlf.gamerecorder.R;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
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) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_gameon);
textViewTime24=(TextView)findViewById(R.id.textViewTime24);//24 Seconds countdown
final Button button_start_timer = (Button)findViewById(R.id.button_start_timer);
button_start_timer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String str = button_start_timer.getText().toString();// Get button string
if(str.equals(" Begin ")){ // Toggle button text
button_start_timer.setText(" Suspend ");
initView();
}
else{
button_start_timer.setText(" Begin ");
timer.cancel();// Terminate a thread
}
}
});
}
public void initView(){
//countDown = (TextView) findViewById(R.id.textViewTime24);
timer = new Timer();
/**
* Every 1 Send in seconds 1 Secondary message to handler Update UI
* schedule(TimerTask task, long delay, long period)
*/
timer.schedule(new TimerTask() {
@Override
public void run() {
handler.sendEmptyMessage(COUNT);
}
}, 0, 1000);
}
private Handler handler = new Handler(){
int num = TOTAL_TIME_24;
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case COUNT:
textViewTime24.setText(String.valueOf(num));
if(num == 0)
timer.cancel();//0 End of seconds
num--;
break;
default:
break;
}
};
};
}