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();
}
}
There are a couple of ways you can stop your thread. If you store your
Threadobject then you can callinterrupt()on it:This would cause the
sleep()to throw anInterruptedExceptionwhich you should return from, not just print the stack trace. You should also do the loop like:You could also set some sort of shutdown flag: