3

I am new to android application development.

I developed one android application, in this application when the user presses back or exit buttons I call the finish() method. This method closes the current activity only.

My requirement is when i click on the exit button, it should close all activities and it show the menu page. Is this possible?

David
  • 19,577
  • 28
  • 108
  • 128
user1761208
  • 81
  • 2
  • 11

3 Answers3

3

When you go from A activity to B activity, call finish().so in android stack A activity ll get finish() or get killed. when you press back or exit button on top activity then stacks gets empty, then you ll go to menu screen or home screen.

for example : when your going from A activity to B activity perform below step:

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

so your A activity gets finish, & your new B activity gets started. Here when you press back button or exit button you ll go to home screen or menu screen.

Here we have two methods to finish or kill the app on back button pressed.

  1. Using finish() which closes or finishes the current activity on android screen.

    for example : you have 2 activities i.e A & B. You ll go from A activity to B activity using intent, now foreground acitivity is B, you want to go back & kill B activity & goto A acitivity use finish() onclick of backbutton. If your on A activity then it closes the app. see below code.

    public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
    finish();
    }
    return super.onKeyDown(keyCode, event);
    }
    
  2. Using android.os.Process.killProcess(android.os.Process.myPid()); which kills the app i.e force close the app & goto the home screen.see below code.

    public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
    // Kills & force closes the app 
    android.os.Process.killProcess(android.os.Process.myPid());
    }
    return super.onKeyDown(keyCode, event);
    }
    
Rahul Baradia
  • 11,802
  • 17
  • 73
  • 121
3

This subject has received some discussion, here is one that should contain most of the information you're looking for.

Also, see Activity Lifecycle and Process Lifecycle in the Android Documentation on Activities to understand the hows and whys of closing apps.

Community
  • 1
  • 1
Ernir
  • 333
  • 1
  • 8
  • 17
1

My requirement is when i click on the exit button, it should close all activities and it show the menu page.

Assuming "the menu page" is an activity of yours, call startActivity(), with an Intent identifying your "menu page", and include FLAG_ACTIVITY_CLEAR_TOP and FLAG_ACTIVITY_SINGLE_TOP as flags on your Intent. That will clear all activities from your task and bring your existing "menu page" to the foreground (or create an instance of the "menu page" if there is none).

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491