How to cancel a specific thread in android studio?

Viewed 40

How can I cancel this thread in case a button is pressed under those 15 seconds?

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    try {
                        sound1.setVolume(1, 1);
                    } catch (Exception e) {
                        Log.e("Exception", e.getMessage());
                    }                    }
            },15000);

What if I have 2 treads each one same like the above? How can I refer to one of them?

1 Answers

You can create your own thread class, so you can access them by their name.


public class Sound extends Thread {

   public boolean stop = false;
    public void run() {
        try {
            for (int i = 0; i < 150; i++) {
                if (stop) {
                    return;
                }
                sleep(100);
                System.out.println(i);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


Then you can stop thread like this;

Sound s = new Sound();
s.start();
.
.
.
s.stop = true;
Related