Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/220.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在特定条件下停止可运行计时器?_Java_Android_Timer_Handler_Alarm - Fatal编程技术网

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

Java 如何在特定条件下停止可运行计时器?,java,android,timer,handler,alarm,Java,Android,Timer,Handler,Alarm,我想做一个定时器应用程序,在特定时间过后播放警报。我是Android开发的新手,所以我从互联网上获取了一个示例计时器代码,并试图根据我的需要对其进行修改 我已经完成了计时器在1分钟后播放警报的部分,但警报声并没有停止,我如何才能做到这一点 我的代码如下: package com.example.aditya.timerapp; import android.media.Ringtone; import android.media.RingtoneManager; import android.

我想做一个定时器应用程序,在特定时间过后播放警报。我是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();
}
}

所以现在我需要一种方法,当用户按下重置按钮时停止报警。请建议。

一种方法如下:

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

  • 使用
    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


    另一种方法是处理
    可运行的
    中的
    中断异常
    ,并从主程序发送一个中断。

    如果我没有弄错问题,您可以通过声明您的
    私人铃声来尝试停止报警声
    ,并在
    顶部()方法中调用
    ring.stop()
    方法

    私人铃声;
    //...//
    公共无效播放计时器(){
    Uri通知=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_报警);
    ring=RingtoneManager.getRingtone(getApplicationContext(),通知);
    铃声。播放();
    timeSwapBuff+=timein毫秒;
    removeCallbacks(updateTimerThread);
    }
    受保护的void onStop(){
    removeCallbacks(updateTimerThread);
    响铃。停止();
    super.onStop();
    }