今天利用Timer來完成計時器的APP練習
Timer是一個普通的類,其中有幾個重要的方法;
而TimerTask則是一個抽象類,其中有一個抽象方法run(),
類似執行緒中的run()方法,我們使用Timer建立一個他的物件,
然後使用這物件的schedule方法來完成這種間隔的操作。
Timer就是一個執行緒,使用schedule方法完成對TimerTask的排程,
多個TimerTask可以共用一個Timer,也就是說Timer物件呼叫一次schedule方法就是建立了一個執行緒,
並且呼叫一次schedule後TimerTask是無限制的迴圈下去的,
使用Timer的cancel()停止操作。當然同一個Timer執行一次cancel()方法後,所有Timer執行緒都被終止。
先來設計xml:
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/grey">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RESET"
android:background="@null"
android:textColor="@color/red"
android:textSize="30sp"
android:onClick="resetTapped"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TIMER"
android:textColor="@color/black"
android:layout_gravity="center"
android:textSize="30sp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="START"
android:id="@+id/startStopButton"
android:background="@null"
android:textColor="@color/green"
android:textSize="30sp"
android:layout_gravity="end"
android:layout_marginRight="15dp"
android:onClick="startStopTapped"/>
</androidx.appcompat.widget.Toolbar>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/timerText"
android:textSize="60sp"
android:text="00 : 00 : 00"
android:textColor="@color/black"
android:layout_gravity="center"
android:layout_marginTop="40dp"/>
</LinearLayout>
接著設定MainActivity.java
package codewithcal.au.timer;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity
{
TextView timerText;
Button stopStartButton;
Timer timer;
TimerTask timerTask;
Double time = 0.0;
boolean timerStarted = false;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timerText = (TextView) findViewById(R.id.timerText);
stopStartButton = (Button) findViewById(R.id.startStopButton);
timer = new Timer();
}
public void resetTapped(View view)
{
AlertDialog.Builder resetAlert = new AlertDialog.Builder(this);
resetAlert.setTitle("Reset Timer");
resetAlert.setMessage("Are you sure you want to reset the timer?");
resetAlert.setPositiveButton("Reset", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialogInterface, int i)
{
if(timerTask != null)
{
timerTask.cancel();
setButtonUI("START", R.color.green);
time = 0.0;
timerStarted = false;
timerText.setText(formatTime(0,0,0));
}
}
});
resetAlert.setNeutralButton("Cancel", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialogInterface, int i)
{
//do nothing
}
});
resetAlert.show();
}
public void startStopTapped(View view)
{
if(timerStarted == false)
{
timerStarted = true;
setButtonUI("STOP", R.color.red);
startTimer();
}
else
{
timerStarted = false;
setButtonUI("START", R.color.green);
timerTask.cancel();
}
}
private void setButtonUI(String start, int color)
{
stopStartButton.setText(start);
stopStartButton.setTextColor(ContextCompat.getColor(this, color));
}
private void startTimer()
{
timerTask = new TimerTask()
{
@Override
public void run()
{
runOnUiThread(new Runnable()
{
@Override
public void run()
{
time++;
timerText.setText(getTimerText());
}
});
}
};
timer.scheduleAtFixedRate(timerTask, 0 ,1000);
}
private String getTimerText()
{
int rounded = (int) Math.round(time);
int seconds = ((rounded % 86400) % 3600) % 60;
int minutes = ((rounded % 86400) % 3600) / 60;
int hours = ((rounded % 86400) / 3600);
return formatTime(seconds, minutes, hours);
}
private String formatTime(int seconds, int minutes, int hours)
{
return String.format("%02d",hours) + " : " + String.format("%02d",minutes) + " : " + String.format("%02d",seconds);
}
}
這樣就完成啦
此篇Timer以及TimerTask參考至
https://codertw.com/%E7%A8%8B%E5%BC%8F%E8%AA%9E%E8%A8%80/314240/