简体   繁体   中英

Back button goes to the parent activity instead going to the phone home screen

I have two activities, A y B. A is the parent activity of B.

A initialise the second one with this code:

Intent intent = new Intent( this, B.class );
startActivity( intent );
this.finish();

and the B goes back to A (like a logout) with this code:

Intent intent = new Intent( B.this, A.class );
intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
startActivity( intent );

Giving you some more context, the app has a sliding menu and each list item shows a ListFragment within a ListView. On each of those views the back stack has been cleaned and the idea is when the user press onto the back button, he should go to the phone home screen as Google documentation says and when the user press on the app icon from the phone home screen, it needs to re-init where the user was working on.

What the app is currently doing is going to the phone home screen, but when you press onto the app icon, it starts again from the activity A, which is the launch and main activity.

Any idea why?

Try adding after startActivity() finish() . That will make the provius activity to safely close itself.

You use this code to go to phone Home screen

        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);

Override onBackPressed and write the above code. It should work.

According to my understanding, You have 2 activities A & B.

You are starting Activity A & moving to Activity B same timing calling A.this.finish()

It means there is only 1 activity present in your stack which is Activity B.

And when you press "Back" button, it means its closing your app that removing remaining Activity B from stack, so your stack gets empty. So you need to press "Center" button of your device which will keep your app activity B in background (in onStop() state) & when you start your app again so it will open activity B only (by calling onRestart()).

I hope above explanation is highly sufficient to understand above problem.

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