0

So activity starts and I create a Thread which checks when to go to the next activity. But sometimes I need this activity to kill itself. onPause does this, but after that Thread is still alive and after time runs out it start a new activity. Is it possible to kill this Thread and stop goToFinals intent?

 public class Questions extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String in = getIntent().getStringExtra("time");         
        long tmp = Long.parseLong(in);
        endTime = (long) System.currentTimeMillis() + tmp;

        Thread progress = new Thread(new Runnable() {

            public void run() {
                while(endTime > System.currentTimeMillis()) {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                Intent goToFinals = new Intent(Questions.this,End.class);
                        startActivity(goToFinals);
            }

        });
        progress.start();

    }

    @Override
    protected void onPause() {
        super.onPause();
        finish();
    }
}
Gray
  • 115,027
  • 24
  • 293
  • 354
Justinas R.
  • 271
  • 1
  • 4
  • 17

3 Answers3

2

There are a couple of ways you can stop your thread. If you store your Thread object then you can call interrupt() on it:

 progress.interrupt();

This would cause the sleep() to throw an InterruptedException which you should return from, not just print the stack trace. You should also do the loop like:

 while(endTime > System.currentTimeMillis()
     && !Thread.currentThread().isInterrupted()) {

You could also set some sort of shutdown flag:

// it must be volatile if used in multiple threads
private volatile boolean shutdown;

// in your thread loop you do:
while (!shutdown && endTime > System.currentTimeMillis()) {
    ...
}

// when you want the thread to stop:
shutdown = true;
Gray
  • 115,027
  • 24
  • 293
  • 354
0

In order to safely quit the thread you must first call thread_instance.interrupt() and then you can check if it is interrupted or not. Refer this LINK

Shankar Agarwal
  • 34,573
  • 7
  • 66
  • 64
0

see this post for kill java thread.The way they recomend is to use a shared variable as a flag which asks the background thread to stop. This variable can then be set by a different object requesting the thread terminate.

Community
  • 1
  • 1
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213