سؤال

I am currently writing a chat app. It is basically very similar to WhatsApp: On Startup there is last conversation overview.

When I want to start a new conversation with somebody I have to do/pass

  1. last conversations overview activity (click on + to look for conversation partner)
  2. courses activity (choose a course)
  3. course participants activity (chooser partner)
  4. Conversation Activity

So that is Basically the stack: [A1, A2, A3, A4]

Now the user had a nice chat with some course member and wants to get back to the last conversation overview but when he presses the back button he will get to A3, the "course participants activity".

I want the user to get back to A1 by pressing the back button in A4.

WRONG: [A1, A2, A3 , A4] -> back -> [A1, A2, A3]
RIGHT: [A1, A2, A3 , A4] -> back -> [A1]

alternatively I could imagine

RIGHT: [A1, A2, A3] -> start A4 -> [A1, A4]

Thanks in advance.

[edit]

THE ANSWER

It turned out to be a combination of these two.

in onOptionsItemSelected() I put this (in a switch case of course) because of the given google conventions.

final Intent intent = new Intent(this, MainPage.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

and

Define Activity A1's android:launchMode as singleTop at your manifest.

Why a combination? Just adding the Flat Intent.FLAG_ACTIVITY_CLEAR_TOP kills activity A1. As this was my fist activity it had some registration/checking implementation included. When I started this activity again after it has been destroyed onCreate was called unnecessarily.

The launchmode singletop prevents this.

هل كانت مفيدة؟

المحلول

Define Activity A1's android:launchMode as singleTop at your manifest. Handle back button press at Activity A4 and start your Activity A1 like below:

Intent intent = new Intent(A4.this,  A1.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent); 

With this your A2, A3 will be cleared from stack.

See more for intents.

Edit: This will work for your [A1, A2, A3 , A4] -> back -> [A1] requirement

نصائح أخرى

Try to do it consistent with the Android design. The back button goes back one activity.

Instead use the home button of the Action Bar.

Android design pattern for navigation;

Create the ActionBar:

final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayHomeAsUpEnabled(true);

Go back to top intent when HomeButton got clicked:

final Intent intent = new Intent(this, MainPage.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top