CountDown计时器获取时间

时间:2016-08-10 09:23:22

标签: android multithreading timer

我在Android中为Count Down Timer制作了一个程序,但我无法使用Stop Button停止计时器。 还有另一个问题。当我再次单击“开始”按钮时,它会崩溃。

MainActivity.java

import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;


public class ThreadTimer extends Thread {

    private int      seconds;
    private int      counter;
    private TextView textView;


    public void setSeconds(int value) {
        seconds = value;
        counter = seconds;
    }


    public void setTextView(TextView value) {
        textView = value;
    }


    @Override
    public void run() {
        super.run();
        while (counter > 0) {
            try {
                Thread.sleep(1000);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
            counter--;
            if (textView != null) {
                G.HANDLER.post(new Runnable() {

                    @Override
                    public void run() {
                        int min = (int) Math.floor(counter / 60);
                        int sec = counter % 60;

                        String minPrefix = "";
                        if (min < 10) {
                            minPrefix = "0";
                        }

                        String secPrefix = "";
                        if (sec < 10) {
                            secPrefix = "0";
                        }

                        textView.setText(minPrefix + min + ":" + secPrefix + sec);
                    }
                });
            }
            Log.i("LOG", "Counter: " + counter);
        }

        G.HANDLER.post(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(G.context, "Alarm ! ! !", Toast.LENGTH_SHORT).show();
            }
        });
    }

}

ThreadTimer.java

import android.app.Application;
import android.content.Context;
import android.os.Handler;


public class G extends Application {

    public static Context context;

    public static final Handler HANDLER = new Handler();


    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();

    }
}

G.java

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" android:background="@drawable/layout_background">

    <EditText
        android:id="@+id/edtNumber"
        android:layout_width="fill_parent"
        android:layout_height="72dip"
        android:ems="10"
        android:inputType="number" android:hint="Enter Your Time" android:layout_margin="8dip" android:background="@drawable/txt_counter_style"/>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="48dip"
        android:layout_weight="0" >


    </LinearLayout>

       <Button
        android:id="@+id/btnStart"
        android:layout_width="fill_parent"
        android:layout_height="48dip"
        android:layout_margin="8dip"
        android:background="@drawable/button_style"
        android:text="Start"
           android:gravity="center_horizontal|center"
           android:textStyle="bold"/>

    <Button
        android:id="@+id/btnStop"
        android:layout_width="fill_parent"
        android:layout_height="48dip"
        android:layout_margin="8dip"
        android:background="@drawable/button_style"
        android:text="Stop"
        android:gravity="center_horizontal|center"
        android:textStyle="bold"/>

    <TextView
        android:id="@+id/txtCounter"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="--:--"
        android:textColor="#ffffff"
        android:textSize="48dip"
        android:typeface="monospace" />

</LinearLayout>

timer.xml

{{1}}

1 个答案:

答案 0 :(得分:0)

如果您重复使用专门为此目的而创建的现有Android组件,那可能会更好。您可以使用Android中包含的CountDownTimer

int countDownLength = 30000; // counts down 30 seconds
int countDownInterval = 1000; // updates the timer every second
CountDownTimer timer = new CountDownTimer(countDownLength, countDownInterval) {
    @Override
    public void onTick(long millisUntilFinished) {
        // called when the timer is updated
    }

    @Override
    public void onFinish() {
        // called when the timer has finished
    }
};
timer.start();
// ...
timer.cancel();

要修复代码,您应该记住以下几点:

  1. 停止计时器:要正确取消计时器,您需要保留对runnable的引用,然后使用以下命令取消该runnable:

    timer = new Runnable() {...};
    G.HANDLER.removeCallbacks(timer);
    

    我还建议您为runnables使用延迟(出于性能原因,这里有一秒延迟有意义):

    G.HANDLER.postDelayed(timer, 1000);
    
  2. 重新启动计时器:第二次单击按钮时代码崩溃,因为文本已更改,无法再转换为整数。最好在计时器运行时禁用按钮:

    btnStart.setEnabled(false);