开发者

Application is starting even after closing

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();
开发者_StackOverflow中文版}

@Override
protected void onPause() {
    super.onPause();
    timer.destroy(); // tried timer.stop() as well 
    finish();
}

}


Yes, the Thread is 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, but finish() just terminates your Activity's workflow: the Activity it is still in memory and WILL be destroyed at some point, later. So the Thread keeps running. And calling Thread.stop() is not efficient as explained in the doc:

This method is deprecated. because stopping a thread in this manner is unsafe and can leave your application and the VM in an unpredictable state.

So the Thread is still runnning, and this is why the app restarts after 3 seconds. Or I should say, start a new Activity.

I don't see why you are using this Thread that starts a new Activity after 3 second, but taking this for granted, you should:

  • Use a boolean in your Thread to determine whether you can start or not:

    timer = new Thread() {
        public void run() {
            try {
                sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } 
            finally {
                if (!paused) {
                    Intent openStarting = new Intent("nik.tri.MENU");
                    startActivity(openStarting);
                }
            }
        }
    };
    
  • And handle that flag in onPause() / onResume():

    @Override
    protected void onPause() {
        paused = true;
        super.onPause();
    
        finish(); // well, I don't get that either, but I take it for granted as well.
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        paused = false;
    }
    


try to kill the application in OnDestroy method.

int pid=android.os.Process.myPid();
 android.os.Process.killProcess(pid);

try this, may it helps you

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜