如何在特定条件下停止可运行的计时器?

时间:2016-04-03 06:56:37

标签: java android timer handler alarm

我想制作一个定时器应用程序,它会在特定时间过后发出警报。我是Android开发人员的新手,所以我从互联网上选择了一个示例计时器代码,并尝试根据我的需要进行修改。

我已经完成了计时器在1分钟过后发出警报的部分,但警报声并没有停止我该怎么做。

我的代码如下:

package com.example.aditya.timerapp;

import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.api.GoogleApiClient;

public class MainActivity extends AppCompatActivity {

private ProgressBar progress;
private TextView timerValue;
private long startTime = 0L;
private Handler customHandler = new Handler();
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
int progressStatus = 0;
private boolean stopped = false;


@Override
public void onCreate(Bundle savedInstanceState) {
    //final CountDown timer = new CountDown();
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    timerValue = (TextView) findViewById(R.id.timerVal);
    Button startButton = (Button) findViewById(R.id.startButton);
    startButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            //timer.start();
            startTime = SystemClock.uptimeMillis();
            customHandler.postDelayed(updateTimerThread, 0);

        }
    });
    Button pauseButton = (Button) findViewById(R.id.stopButton);
    pauseButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            /*try {
                timer.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }*/
            timeSwapBuff += timeInMilliseconds;
            customHandler.removeCallbacks(updateTimerThread);
        }
    });
    Button resetButton = (Button) findViewById(R.id.resetButton);
    resetButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            //timeSwapBuff += timeInMilliseconds;
            timeInMilliseconds = 0L;
            timeSwapBuff = 0L;
            updatedTime = 0L;
            int secs = (int) (updatedTime / 1000);
            int mins = secs / 60;
            secs = secs % 60;
            int milliseconds = (int) (updatedTime % 1000);
            timerValue.setText("" + mins + ":"
                    + String.format("%02d", secs) + ":"
                    + String.format("%03d", milliseconds));
            customHandler.removeCallbacks(updateTimerThread);
            onStop();

        }
    });
    progress = (ProgressBar) findViewById(R.id.progressBar);
}

/*public void stopRun() {
    //if (updatedTime == 0) {
    //Toast.makeText(new MainActivity(), "StopRun",Toast.LENGTH_LONG).show();
    timeSwapBuff = 0;
    timerValue.setText("00:00:000");
    //updateTimerThread.
    customHandler.removeCallbacks(updateTimerThread);
    //}
}*/

private Runnable updateTimerThread = new Runnable() {
    @Override
    public void run() {
        //long totalMilliseconds = 1500000;
        //while (!stopped){
        //long totalMilliseconds = 15000;
        //updatedTime = totalMilliseconds - SystemClock.currentThreadTimeMillis();
        timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
        updatedTime = timeSwapBuff + timeInMilliseconds;

        int secs = (int) (updatedTime / 1000);
        int mins = secs / 60;
        secs = secs % 60;
        int milliseconds = (int) (updatedTime % 1000);
        timerValue.setText("" + mins + ":"
                + String.format("%02d", secs) + ":"
                + String.format("%03d", milliseconds));
        customHandler.postDelayed(this, 0);

        if (mins == 1 && secs == 0) {
            playTimer();
        }
    }
};

public ProgressBar getProgress() {
    return progress;
}

public void setProgress(ProgressBar progress) {
    this.progress = progress;
}
public void playTimer(){
    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
    Ringtone ring = RingtoneManager.getRingtone(getApplicationContext(), notification);
    ring.play();
    timeSwapBuff += timeInMilliseconds;
    customHandler.removeCallbacks(updateTimerThread);

}
protected void onStop() {
    customHandler.removeCallbacks(updateTimerThread);
    super.onStop();
}
}

所以现在我需要一种方法来在用户按下重置按钮时停止闹钟。请建议。

2 个答案:

答案 0 :(得分:1)

一种方法如下:

  1. Runnable中定义一个布尔值并在run()中执行任何操作之前进行检查。

  2. 使用Runnable内的方法翻转它。

  3. 以下是代码段:

    private Runnable updateTimerThread = new Runnable() {
        private volatile boolean flag = true;
    
        public void stopTimer() {
            this.flag = false;
        }
    
        @Override
        public void run() {
            while(flag) {
                //long totalMilliseconds = 1500000;
                //while (!stopped){
                //long totalMilliseconds = 15000;
                //updatedTime = totalMilliseconds - SystemClock.currentThreadTimeMillis();
                timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
                updatedTime = timeSwapBuff + timeInMilliseconds;
    
                int secs = (int) (updatedTime / 1000);
                int mins = secs / 60;
                secs = secs % 60;
                int milliseconds = (int) (updatedTime % 1000);
                timerValue.setText("" + mins + ":"
                    + String.format("%02d", secs) + ":"
                    + String.format("%03d", milliseconds));
                customHandler.postDelayed(this, 0);
    
                if (mins == 1 && secs == 0) {
                    playTimer();
                }
            }
        }
    };
    

    现在,您只需致电stopTimer()即可停止Runnable

    另一种方法是处理InterruptedException中的Runnable并从主程序发送中断。

答案 1 :(得分:0)

如果我理解了问题,您可以通过在private Ringtone ring方法中声明ring.stop()并调用onStop()方法来尝试停止闹钟声音。

private Ringtone ring; //...// public void playTimer(){ Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); ring = RingtoneManager.getRingtone(getApplicationContext(), notification); ring.play(); timeSwapBuff += timeInMilliseconds; customHandler.removeCallbacks(updateTimerThread); } protected void onStop() { customHandler.removeCallbacks(updateTimerThread); ring.stop(); super.onStop(); }