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

How to stop a runnable timer at a specific condition?

我想制作一个定时器应用程序,它会在特定时间过去后播放警报。我是 Android 开发的新手,所以我从 Internet 上获取了一个示例计时器代码,并试图根据我的需要对其进行修改。

我已经完成了计时器在 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();
}
}

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

一种方法如下:

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

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

这是代码片段:

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

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

如果我理解正确,您可以尝试通过在 onStop() 方法中声明 private Ringtone ring 并调用 ring.stop() 方法来停止警报声。

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(); }