0

I have some activities in my app: A - Login Activity B - Main app Activity C, D ... - Inner Activities I want to implement a behaviour as follows:

  1. when a user select the app icon OR select the app from the task list I want the back stack to be cleared and show Activity A
  2. when a user passed A pressing the back on activity B will quit the application
  3. when a user in an inner app pressing back will function "normally".

for example: activity stack A -> B -> C -> D pressing the back button the first time (top activity is D) will make pop the D of the stack top and it will be: A -> B -> C clicking again (top activity is C) will move us to A -> B and clicking again will quit the app (as described in 2)

I implemented (2) by adding android:noHistory="true" to A's properties in AndroidManifest.xml and tried to implement (1) by adding android:launchMode=singleTop to A's properties in AndroidManifest.xml but when I do that (3) is breaked and clicking back when D is visible moves me directly to A.

how can I implement them all?

Thanks!

RonU
  • 5,525
  • 3
  • 16
  • 13
yossico
  • 3,421
  • 5
  • 41
  • 76

2 Answers2

0

Detect Back Key presses:

 @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
      if (keyCode == KeyEvent.KEYCODE_BACK) {
          //Do what you want, forinstance:
          finish(); //This will close the current Activity and will go back to the previous one
          }

      return super.onKeyDown(keyCode, event);
  }

To close D you can use finish(); like in in the top example. This will close D and will bring you back to C. Same with C and in B you normally shouldn close the App. But if so, you could call somtehing like System.exit(0); to close the App.

To define, which Activity is the parent Activity, go into the Manifest.xml and put things like this: This is for your 1. thing:

      <activity  
       android:name=".ActivityD" 
       android:parentActivityName="com.example.ActivityA" >
       <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.ActivityA" />
       </activity>
Grevius
  • 51
  • 9
0

You can override onbackpressed method and used intent

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

On activity b

mcd
  • 1,434
  • 15
  • 31