简体   繁体   中英

How to stop a runnable timer at a specific condition?

I want to make a Timer Application which plays an alarm after a specific time has elapsed. I am new to Android Development so i picked up an example timer code from the Internet and am trying to modify it to my needs.

I have completed part where the timer plays the alarm when 1 minute has elapsed, but the alarm sound does not stop how can i do that.

My code is given below:

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

So now i need a method to stop the alarm when the user presses the Reset Button. Please suggest.

One way to do it is as follows:

  1. Define a boolean inside your Runnable and check it before doing anything in run() .

  2. Flip it using a method inside your Runnable .

Here is the code snippet:

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

Now, you just have to call stopTimer() to stop the Runnable .

Another way could be to handle the InterruptedException in the Runnable and send an interrupt from the main program.

如果我理解正确,您可以尝试通过声明您的private Ringtone ring并在您的onStop()方法中调用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(); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM