How to destroy the application when the user touch

2019-09-06 16:47发布

问题:

I'd like to destroy my application when the user touches the home button of Android device and begin the MainActivity when the user touches the "back" button of Android. Does any ones knows how to do that?

回答1:

For close app on Back

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (keyCode) {
        case KeyEvent.KEYCODE_BACK :
            finish();

            return true;
        }
    }
    return super.onKeyDown(keyCode, event);
}

And You can't get click event of Home Button so you want to code onStop method.

@Override
    protected void onStop() {
        finish();
        super.onStop();
    }


回答2:

System.exit(0)

But it's best not to use it. Android isn't designed for this purpose.

Close application and launch home screen on Android



回答3:

You can do this by calling the finish() and finishActivity() methods. checkout the details on API guide Shutting down an Activity. From where to call these methods is based on how your application is implemented, but I guess you can do this from the current focused activity by listening to KeyEvent and filtering on Home button key event.

However you need to consider that once you have killed your activities pressing the back button will not get you back to your application activity since killing the activities will wipe them out of memory stack.

Also check out the Activity life cycle diagram and detailed description given on Android Developers site.



回答4:

You can close an Activity by calling finish(), but you'll have to do that for each Activity that is open. To have this happen upon pushing the HOME button, you'll have to register a KeyEvent. I'm not too clear on how to do this, but you can find documentation here.



回答5:

call finish() in your onStop() method. Or use android:noHistory="true" in your manifest.