This is my first activity and when I press the back button in the phone , the app closes, but the second activty is popping up even after it closes! may be because the thread is still running? but i tried destroying it but of no avail! any suggestions
protected void onCreate(Bundle myclass) {
super.onCreate(myclass);
setContentView(R.layout.splash);
timer = new Thread() {
public void run() {
try {
sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
finally {
Intent openStarting = new Intent("nik.tri.MENU");
startActivity(openStarting);
}
}
};
timer.start();
}
@Override
protected void onPause() {
super.onPause();
timer.destroy(); // tried timer.stop() as well
finish();
}
}
Yes, the
Threadis involved in that process:when you press the back button, you do not destroy nor stop your app, you just make it invisible.
onPause()is called at that time, butfinish()just terminates yourActivity‘s workflow: theActivityit is still in memory and WILL be destroyed at some point, later. So theThreadkeeps running. And callingThread.stop()is not efficient as explained in the doc:So the
Threadis still runnning, and this is why the app restarts after 3 seconds. Or I should say, start a newActivity.I don’t see why you are using this
Threadthat starts a newActivityafter 3 second, but taking this for granted, you should:Use a
booleanin yourThreadto determine whether you can start or not:And handle that flag in
onPause()/onResume():