search
尋找貓咪~QQ 地點 桃園市桃園區 Taoyuan , Taoyuan

[Android] TimeTask計時器使用

TimeTask其實就是一個時間執行緒,常被用於APP內部任何有時間機制的部分,像是馬錶、計時器、鬧鐘、遊戲一場多久時間需要結束等等....

這邊簡單的示範一下從10秒一直到數道0秒後接著重新一樣的動作

這邊廢話也不多說就直接上程式碼吧

示範

XML

xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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/t1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

android.support.constraint.ConstraintLayout>

JAVA

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {
    Timer timer;//宣告一個時間函示
    int tt=10;//設置初始秒數
    TextView t1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        t1=(TextView)findViewById(R.id.t1);
        timer = new Timer();//時間函示初始化
        //這邊開始跑時間執行緒
        final TimerTask task = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tt--;//時間倒數
                        t1.setText(tt+"second");//讓TextView元件顯示時間倒數情況
                        //if判斷示裡面放置在時間結束後想要完成的事件
                        if (tt < 1) {
                            tt = 10; //讓時間執行緒保持輪迴
                        }
                    }
                });
            }
        };
        timer.schedule(task, 1000, 1000);//時間在幾毫秒過後開始以多少毫秒執行
    }
    }

相關文章:

[Android] Android 程式設計教學



熱門推薦

本文由 kk665403pixnetnetblog 提供 原文連結

寵物協尋 相信 終究能找到回家的路
寫了7763篇文章,獲得2次喜歡
留言回覆
回覆
精彩推薦