简体   繁体   中英

Android How to prevent back button from quitting application (after home button pressed)

I have an issue whereby, the back button works fine. Unless you push the home button, then re-enter the application, then push the back button again. It then quits the App, because their is no task trail (of activities)

Here is my colleagues code, of which I am trying to fix. Android.R.id.home is the problematic soft back button, although same thing is happening with OS back button.

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent;
        switch (item.getItemId()) {
        case android.R.id.home:
            activity.finish();
            return true;
        case R.id.menu_paymentLocs:
            intent = new Intent(activity, PaymentLocationsPage.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
            activity.startActivity(intent);
            return true;
        case R.id.menu_feedback:
            intent = new Intent(activity, FeedbackPage.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
            activity.startActivity(intent);
            return true;
        case R.id.menu_about:
            intent = new Intent(activity, AboutPage.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
            activity.startActivity(intent);
            return true;
        case R.id.menu_changeconsumer:
            new SelectConsumerDialogFragment().show(getFragmentManager(), "select_consumer");
            return true;
        case R.id.menu_logout:
            intent = new Intent(activity, SplashPage.class);
            myMeter.logout();
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            activity.startActivity(intent);
            return true;
        }
        return true;
    }

To prevent the back button from doing anything predefined you need to override the onbackpressed() method

try this if you are using api level 2.0 or higher

@Override
public void onBackPressed() {
    // Do Here what ever you want do on back press;
}

删除所有intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM