35

I need to finish an android application. For that i wrote

@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you sure You want to exit")
        .setCancelable(false)
        .setPositiveButton("YES"),
        new DialogInterface.OnClickListener() {
            // On
            // clicking
            // "Yes"
            // button

            public void onClick(DialogInterface dialog,int id) {
                System.out.println(" onClick ");
                closeApplication(); // Close Application method called
            }
        })
        .setNegativeButton("NO"),
        new DialogInterface.OnClickListener() {
            // On
            // clicking
            // "No"
            // button
            public void onClick(DialogInterface dialog,int id) {
                dialog.cancel();
            }
        });

        AlertDialog alert = builder.create();
        alert.show();
    }

    private void closeApplication() {
        System.out.println("closeApplication ");
        this.finish();
    }
}

But if any activity is not finished in the application, when i tried to exit the application that activity is finished first and the application is not exiting.. i tried 2 times to exit this application... How i can finish all the activities in an application when i need to exit... or is there any way to finish the entire application

Amaury Medeiros
  • 2,093
  • 4
  • 26
  • 42
jennifer
  • 8,133
  • 22
  • 69
  • 96

9 Answers9

56

To close application just call:

android.os.Process.killProcess(android.os.Process.myPid());

Otherwise due-to specific life-cycling of Android activities you can't be sure that application is closed/killed.

Barmaley
  • 16,638
  • 18
  • 73
  • 146
28

whenever you are starting a new activity use

myintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myintent);

and in manifest file mention that activity as

<activity android:name=".<Activity Name>" >
        <intent-filter>
        <action android:name="android.intent.action.VIEW"/>
     <category android:name="android.intent.category.DEFAULT" />
     </intent-filter>
       </activity>
Pinki
  • 21,723
  • 16
  • 55
  • 88
21

Put this into your onClick or in onBackPressed:

moveTaskToBack(true);
finish()
phoenix
  • 7,988
  • 6
  • 39
  • 45
Stan Malcolm
  • 2,740
  • 5
  • 32
  • 53
  • 2
    what does moveTaskToBack do? – skryshtafovych Mar 27 '18 at 20:20
  • 1
    For "moveTaskToBack", documents say: "Move the task containing this activity to the back of the activity stack. The activity's order within the task is unchanged."... By this method, no other activities stay at the back of this activity; and "finish"ing this activity finishes the whole app. – JustADeveloper Dec 31 '19 at 11:15
12

Please read first this post from Google Android Developer Advocate Reto Meier : When to Include an Exit Button in Android Apps (Hint: Never)

What is th symptom that make you want to add an exit button ? If you need to clear the activity stack and always restart with a specific Activity, maybe you just have to tweak your activity manifest declaration with attributes like : android:clearTaskOnLaunch

Vikas Patidar
  • 42,865
  • 22
  • 93
  • 106
Kevin Gaudin
  • 9,927
  • 3
  • 32
  • 34
  • 2
    I won't be so sure. There are some cases when user need to be 100% sure that application is really closed. E.g. when application is kind of secure or so. If application still is running that means - that there's a possibility for security breaching. – Barmaley Jan 19 '11 at 06:33
  • There is no "application still running". There are just Activities with state that is kept for later use or not, and tasks which are basically stacks of activities that have been launched during a usage session. Please carefully read the doc on the attributes available in the manifest for activities. android:excludeFromRecents could be useful to avoid having a "secure" activity being restored, for example. – Kevin Gaudin Jan 19 '11 at 06:42
  • 2
    This current wisdom of not really closing apps but letting them linger is far to uncertain a process that it's effects are in many cases worse than the drawbacks of a user invoked closure. I understand the need to retain apps that use back end services such as keeping track of location via GPS, playing media stream, downloading in the background or Google monitoring user behaviour. However, a core component of usability is that a user feels in control. Even with my knowledge of Android, I prefer to close some apps down and know for certain they are not utilising precious resources. – Andrew S Jun 05 '13 at 16:16
  • 1
    Running a 'kiosk' app available to public users and locking out home screen, back buttons, etc. and navigating via NFC tags requires a way to shut down the app completely for service and maintenance. Don't listen to everything Google says. They are not gods. – Chloe Sep 10 '13 at 17:59
  • Never say Never. It's very short sighted to publish guidlines that say "Never do this". – Hector Jan 15 '17 at 06:16
9

Android is made in such a way that virtually NO application that was once opened, is closed.

Before mis-interpreting the statement, understand this.

"Whenever you exit your app, Android saves all the things the app was doing (called its state) and pushes the app in the background, calling the onStop() method. this is the new state of the application then, where the app isn't running, but isn't flushed out of the memory too. whenever you start the app again, it is resumed from the frozen state. Only when the memory, where frozen apps are kept, starts getting full, the Android GC flushes the app."

So conceptually, nothing goes out. when you hit "back" button while ur on the first activity, Android bundles the app and data, and freezes it.

Aman Alam
  • 11,231
  • 7
  • 46
  • 81
  • 1
    not true. as barmaley mentioned you still can kill the process. what you're talking about is the typical lifecyle and how android deals with system resources. it dosn't mean its not possible to kill a process. otherwise shutting down the system would not be possible. – omni Feb 01 '12 at 18:29
3

according to this answer,

just write this.finishAffinity(); and done!

Hossein Yousefpour
  • 3,827
  • 3
  • 23
  • 35
1

I have an application with several Activities. I extended my Application class, and included a variable numActive. This is initialized to 0. Within each activity's onStart(), numActive is incremented, and in onStop() it is decremented. If the count reaches zero, the user has left my application entirely, and I close down my background tasks.

inquist
  • 197
  • 4
1

Shameless copy of NeTeInStEiN's answer as I found it so useful (please up-vote his answer): Sending a running application to background programmatically

You can use either:

boolean sentAppToBackground = moveTaskToBack(true);

if(!sentAppToBackground){
  Intent i = new Intent();
  i.setAction(Intent.ACTION_MAIN);
  i.addCategory(Intent.CATEGORY_HOME);
  this.startActivity(i);
}

More information here: http://developer.android.com/reference/android/app/Activity.html#moveTaskToBack(boolean)

Or simply:

Intent i = new Intent();
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
this.startActivity(i);

According to Romain Guy a Android Framework Engineer, "You cannot simulate a press on the Home key.". So beware...

Check: http://osdir.com/ml/Android-Developers/2010-03/msg01887.html

Updated this answer according to: moveTaskToBack(true) returns false always

Community
  • 1
  • 1
TheIT
  • 11,919
  • 4
  • 64
  • 56
-3

To Close the Application, you can also take "System.exit(0)" 0 is standard or use any exit code.

redestructa
  • 1,182
  • 1
  • 11
  • 11