160

I want to close my application, so that it no longer runs in the background.

How to do that? Is this good practice on Android platform?

If I rely on the "back" button, it closes the app, but it stays in background. There is even application called "TaskKiller" just to kill those apps in the background.

Danail
  • 10,443
  • 12
  • 54
  • 76
  • 4
    This question has already been asked. Have a look at http://stackoverflow.com/questions/2033914/quitting-an-application-is-that-frowned-upon/2034238#2034238 or http://stackoverflow.com/questions/2042222/android-close-application – David Webb Jan 19 '10 at 11:14
  • wondering why one would not want his app running even in background? – Darpan Oct 08 '14 at 12:56

22 Answers22

141

Android has a mechanism in place to close an application safely per its documentation. In the last Activity that is exited (usually the main Activity that first came up when the application started) just place a couple of lines in the onDestroy() method. The call to System.runFinalizersOnExit(true) ensures that all objects will be finalized and garbage collected when the the application exits. You can also kill an application quickly via android.os.Process.killProcess(android.os.Process.myPid()) if you prefer. The best way to do this is put a method like the following in a helper class and then call it whenever the app needs to be killed. For example in the destroy method of the root activity (assuming that the app never kills this activity):

Also Android will not notify an application of the HOME key event, so you cannot close the application when the HOME key is pressed. Android reserves the HOME key event to itself so that a developer cannot prevent users from leaving their application. However you can determine with the HOME key is pressed by setting a flag to true in a helper class that assumes that the HOME key has been pressed, then changing the flag to false when an event occurs that shows the HOME key was not pressed and then checking to see of the HOME key pressed in the onStop() method of the activity.

Don't forget to handle the HOME key for any menus and in the activities that are started by the menus. The same goes for the SEARCH key. Below is some example classes to illustrate:

Here's an example of a root activity that kills the application when it is destroyed:

package android.example;

/**
 * @author Danny Remington - MacroSolve
 */

public class HomeKey extends CustomActivity {

    public void onDestroy() {
        super.onDestroy();

        /*
         * Kill application when the root activity is killed.
         */
        UIHelper.killApp(true);
    }

}

Here's an abstract activity that can be extended to handle the HOME key for all activities that extend it:

package android.example;

/**
 * @author Danny Remington - MacroSolve
 */

import android.app.Activity;
import android.view.Menu;
import android.view.MenuInflater;

/**
 * Activity that includes custom behavior shared across the application. For
 * example, bringing up a menu with the settings icon when the menu button is
 * pressed by the user and then starting the settings activity when the user
 * clicks on the settings icon.
 */
public abstract class CustomActivity extends Activity {
    public void onStart() {
        super.onStart();

        /*
         * Check if the app was just launched. If the app was just launched then
         * assume that the HOME key will be pressed next unless a navigation
         * event by the user or the app occurs. Otherwise the user or the app
         * navigated to this activity so the HOME key was not pressed.
         */

        UIHelper.checkJustLaunced();
    }

    public void finish() {
        /*
         * This can only invoked by the user or the app finishing the activity
         * by navigating from the activity so the HOME key was not pressed.
         */
        UIHelper.homeKeyPressed = false;
        super.finish();
    }

    public void onStop() {
        super.onStop();

        /*
         * Check if the HOME key was pressed. If the HOME key was pressed then
         * the app will be killed. Otherwise the user or the app is navigating
         * away from this activity so assume that the HOME key will be pressed
         * next unless a navigation event by the user or the app occurs.
         */
        UIHelper.checkHomeKeyPressed(true);
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.settings_menu, menu);

        /*
         * Assume that the HOME key will be pressed next unless a navigation
         * event by the user or the app occurs.
         */
        UIHelper.homeKeyPressed = true;

        return true;
    }

    public boolean onSearchRequested() {
        /*
         * Disable the SEARCH key.
         */
        return false;
    }
}

Here's an example of a menu screen that handles the HOME key:

/**
 * @author Danny Remington - MacroSolve
 */

package android.example;

import android.os.Bundle;
import android.preference.PreferenceActivity;

/**
 * PreferenceActivity for the settings screen.
 * 
 * @see PreferenceActivity
 * 
 */
public class SettingsScreen extends PreferenceActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.layout.settings_screen);
    }

    public void onStart() {
        super.onStart();

        /*
         * This can only invoked by the user or the app starting the activity by
         * navigating to the activity so the HOME key was not pressed.
         */
        UIHelper.homeKeyPressed = false;
    }

    public void finish() {
        /*
         * This can only invoked by the user or the app finishing the activity
         * by navigating from the activity so the HOME key was not pressed.
         */
        UIHelper.homeKeyPressed = false;
        super.finish();
    }

    public void onStop() {
        super.onStop();

        /*
         * Check if the HOME key was pressed. If the HOME key was pressed then
         * the app will be killed either safely or quickly. Otherwise the user
         * or the app is navigating away from the activity so assume that the
         * HOME key will be pressed next unless a navigation event by the user
         * or the app occurs.
         */
        UIHelper.checkHomeKeyPressed(true);
    }

    public boolean onSearchRequested() {
        /*
         * Disable the SEARCH key.
         */
        return false;
    }

}

Here's an example of a helper class that handles the HOME key across the app:

package android.example;

/**
 * @author Danny Remington - MacroSolve
 *
 */

/**
 * Helper class to help handling of UI.
 */
public class UIHelper {
    public static boolean homeKeyPressed;
    private static boolean justLaunched = true;

    /**
     * Check if the app was just launched. If the app was just launched then
     * assume that the HOME key will be pressed next unless a navigation event
     * by the user or the app occurs. Otherwise the user or the app navigated to
     * the activity so the HOME key was not pressed.
     */
    public static void checkJustLaunced() {
        if (justLaunched) {
            homeKeyPressed = true;
            justLaunched = false;
        } else {
            homeKeyPressed = false;
        }
    }

    /**
     * Check if the HOME key was pressed. If the HOME key was pressed then the
     * app will be killed either safely or quickly. Otherwise the user or the
     * app is navigating away from the activity so assume that the HOME key will
     * be pressed next unless a navigation event by the user or the app occurs.
     * 
     * @param killSafely
     *            Primitive boolean which indicates whether the app should be
     *            killed safely or quickly when the HOME key is pressed.
     * 
     * @see {@link UIHelper.killApp}
     */
    public static void checkHomeKeyPressed(boolean killSafely) {
        if (homeKeyPressed) {
            killApp(true);
        } else {
            homeKeyPressed = true;
        }
    }

    /**
     * Kill the app either safely or quickly. The app is killed safely by
     * killing the virtual machine that the app runs in after finalizing all
     * {@link Object}s created by the app. The app is killed quickly by abruptly
     * killing the process that the virtual machine that runs the app runs in
     * without finalizing all {@link Object}s created by the app. Whether the
     * app is killed safely or quickly the app will be completely created as a
     * new app in a new virtual machine running in a new process if the user
     * starts the app again.
     * 
     * <P>
     * <B>NOTE:</B> The app will not be killed until all of its threads have
     * closed if it is killed safely.
     * </P>
     * 
     * <P>
     * <B>NOTE:</B> All threads running under the process will be abruptly
     * killed when the app is killed quickly. This can lead to various issues
     * related to threading. For example, if one of those threads was making
     * multiple related changes to the database, then it may have committed some
     * of those changes but not all of those changes when it was abruptly
     * killed.
     * </P>
     * 
     * @param killSafely
     *            Primitive boolean which indicates whether the app should be
     *            killed safely or quickly. If true then the app will be killed
     *            safely. Otherwise it will be killed quickly.
     */
    public static void killApp(boolean killSafely) {
        if (killSafely) {
            /*
             * Notify the system to finalize and collect all objects of the app
             * on exit so that the virtual machine running the app can be killed
             * by the system without causing issues. NOTE: If this is set to
             * true then the virtual machine will not be killed until all of its
             * threads have closed.
             */
            System.runFinalizersOnExit(true);

            /*
             * Force the system to close the app down completely instead of
             * retaining it in the background. The virtual machine that runs the
             * app will be killed. The app will be completely created as a new
             * app in a new virtual machine running in a new process if the user
             * starts the app again.
             */
            System.exit(0);
        } else {
            /*
             * Alternatively the process that runs the virtual machine could be
             * abruptly killed. This is the quickest way to remove the app from
             * the device but it could cause problems since resources will not
             * be finalized first. For example, all threads running under the
             * process will be abruptly killed when the process is abruptly
             * killed. If one of those threads was making multiple related
             * changes to the database, then it may have committed some of those
             * changes but not all of those changes when it was abruptly killed.
             */
            android.os.Process.killProcess(android.os.Process.myPid());
        }

    }
}
Danny Remington - OMS
  • 5,244
  • 4
  • 32
  • 21
  • you mean, if this is the only activity running at the moment? Or there can be other activities in the activity stack? – Danail Feb 18 '11 at 15:15
  • 1
    This is supposed to kill the entire application that called System.exit(0) including all activities that are running as part of the application. All other applications will continue to run. If you want to only kill one activity in the application but not all of the activities in the application then you need to call the finish() method of the activity that you want to kill. – Danny Remington - OMS Feb 18 '11 at 15:52
  • 2
    Thanks very much for this nfo. I am making a game with AndEngine and when I would call finish, even on all activities, android would still not fully clean up and when the game was re-launched, it would be completely bugged out my GL textures were all glitched out etc. So after investigating, thinking it was AndEngine, I came to realize it had to be something that was going wrong because android was trying to preserve the process when I was desiring to exit it. All the comments "oh you shouldn't call exit, it ruins user experience" is nonsense. Weather an application should remain open....... –  Jul 25 '11 at 11:35
  • ...... or not should always be a per-application/use-case question and always at the discretion and control of the developer. –  Jul 25 '11 at 11:35
  • 17
    No production application should be using this code. No production application should be calling any of the code shown in `killApp()`, as Google has indicated that it will lead to unpredictable behavior. – CommonsWare Jul 29 '11 at 11:13
  • You can detect the `HOME` key press event by inspecting the task stack in onDestroy. If the new task is in the Android launcher package, you know the home key was pressed since there's no other way to get to it. However, this will not work for all the custom home screen implementations out there that some people install. It also requires the READ_TASKS permission. – mxk Mar 19 '12 at 09:18
  • 1
    **System.runFinalizersOnExit(true);** method is deprecated, What's the another way to close an application safely(garbage collected)?. – Ajeesh Nov 27 '13 at 08:49
  • Not to my knowledge but it is not uncommon for a method to be deprecated and not replaced with another method. Deprecated methods are usually supported for years and never removed for this reason. – Danny Remington - OMS Dec 17 '13 at 18:23
  • 1
    It was not deprecated at the time that this was originally posted. Since the current AP then was 7 and the current API now is 19, there is probably another way to do this now. – Danny Remington - OMS May 06 '14 at 16:36
  • System.runFinalizersOnExit(true) - This method is inherently unsafe. It may result in finalizers being called on live objects while other threads are concurrently manipulating those objects, resulting in erratic behavior or deadlock. – Zon Apr 26 '17 at 05:59
69

YES! You can most certainly close your application so it is no longer running in the background. Like others have commented finish() is the Google recommended way that doesn't really mean your program is closed.

System.exit(0);

That right there will close your application out leaving nothing running in the background.However,use this wisely and don't leave files open, database handles open, etc.These things would normally be cleaned up through the finish() command.

I personally HATE when I choose Exit in an application and it doesn't really exit.

hasanghaforian
  • 13,858
  • 11
  • 76
  • 167
Cameron McBride
  • 6,779
  • 11
  • 40
  • 52
  • 45
    Using System.exit() is absolutely not recommended. – CommonsWare Jan 19 '10 at 13:54
  • 16
    I won't argue that it's not the recommended way but can you please provide a solution that will guarantee that the application is exited from the background immediatly? If not then System.exit is the way to go until Google provides a better method. – Cameron McBride Jan 19 '10 at 14:17
  • 3
    uhm, no. You're not *supposed* to. Resorting to hacks or dirty workarounds doesn't seem like a thing I would encourage. – mxk Jan 19 '10 at 14:28
  • 75
    Who decides that you're not "supposed" to, the same people that created a method that doesn't actually exit? If users didn't want their applications closed then the 5th most popular paid app wouldn't be a task killer. People need memory freed up and the core OS doesn't do the job. – Cameron McBride Jan 19 '10 at 14:41
  • 20
    Agreed that it's ill-advised, but up-voted for providing an actual answer the the question asked. I'm getting very tired of hearing "you don't really want to do that", with no followup explanation. Android is an absolute nightmare regarding documentation for these types of things compared to iPhone. – DougW Sep 29 '10 at 18:38
  • 12
    There is no memory benefit in using task killers with Android. Android will destroy and clean out all applications that are not in the foreground if the foreground app needs more memory. In some cases Android even reopens an App that was closed with the task killer. Android will fill up all not needed memory with recent used applications to decrease the app switch time. DO NOT BUILD APPS WITH AN EXIT BUTTON. DO NOT USE A TASK MANAGER ON ANDROID. http://geekfor.me/faq/you-shouldnt-be-using-a-task-killer-with-android/ http://android-developers.blogspot.com/2010/04/multitasking-android-way.html – Janusz Jan 31 '12 at 12:55
  • finish is a piece of garbage, it almost never works on closing the application and freeing up memory. Android did this to make running apps easier but it is a memory killer especially if you have a run away application. There should always be a way to close and stop an application. – JPM Feb 03 '12 at 20:14
  • I prefer your solution, very simple and direct – peterretief Sep 03 '14 at 14:34
  • there's plenty of reasons to want to quit your app so that some other app doesn't get killed or not quit your app. it all depends on the app. really sometimes it feels that the android guys had no experience whatsoever from other mobile os's that were tight and provided flexibility at the same time. there's no point to be about arguing about the philsophies behind it if you just want your app to die. and funny that you shouldn't use task killers when android added a built in task killer(swipe on taskswitcher). they just say don't use what they havent added at a time and sheep invent reasons – Lassi Kinnunen Sep 23 '14 at 07:29
  • I have the a solution without using System.exit(0) I have added the answer http://stackoverflow.com/a/27126939/2915785 – Naveed Ahmad Nov 25 '14 at 12:37
  • `system.exit(0)` does not even work, the app still runs. – Black Nov 04 '19 at 09:48
23

This is the way I did it:

I just put

Intent intent = new Intent(Main.this, SOMECLASSNAME.class);
Main.this.startActivityForResult(intent, 0);

inside of the method that opens an activity, then inside of the method of SOMECLASSNAME that is designed to close the app I put:

setResult(0);
finish();

And I put the following in my Main class:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(resultCode == 0) {
        finish();
    }
}
Stephen
  • 7,994
  • 9
  • 44
  • 73
19

Just to answer my own question now after so much time (since CommonsWare commented on the most popular answer telling we should NOT do this):

When I want to quit the app:

  1. I start my first activity (either splash screen, or whatever activity is currently at the bottom of the activity stack) with FLAG_ACTIVITY_CLEAR_TOP (which will quit all the other activities started after it, which means - all of them). Just make to have this activity in the activity stack (not finish it for some reason in advance).
  2. I call finish() on this activity

This is it, works quite well for me.

Reno
  • 33,594
  • 11
  • 89
  • 102
Danail
  • 10,443
  • 12
  • 54
  • 76
  • 4
    This actually doesn't kill your app. It will still show up in the app list. I just kills all your activities. – Joris Weimar Mar 20 '12 at 20:00
  • 1
    FLAG_ACTIVITY_CLEAN_TOP doesn't work for Sony smartphones. You can workaround that by adding android:clearTaskOnLaunch="true" attribute to activity at AndroidManifest.xml – Rusfearuth Apr 09 '15 at 03:57
12

Just write this code on your button EXIT click.

Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("LOGOUT", true);
startActivity(intent);

And in the onCreate() method of your MainActivity.class write below code as a first line,

if (getIntent().getBooleanExtra("LOGOUT", false))
{
    finish();
}
Lalit Jawale
  • 1,216
  • 9
  • 19
9

It's not possible using the framework APIs. It's at the discretion of the operating system (Android) to decide when a process should be removed or remain in memory. This is for efficiency reasons: if the user decides to relaunch the app, then it's already there without it having to be loaded into memory.

So no, it's not only discouraged, it's impossible to do so.

mxk
  • 43,056
  • 28
  • 105
  • 132
  • 4
    You can always do something like Integer z = null; z.intValue(); // worst answer – Joe Plante Sep 28 '12 at 19:43
  • 6
    True that. You could also smash your phone against the wall, that will terminate all open applications if enough pressure is applied. I still wouldn't recommend it. I've updated my post accordingly. – mxk Sep 28 '12 at 21:03
  • @JoePlante that also leaves the app in the background when you open the apps menu. It seems it is impossible. – peresisUser Sep 02 '15 at 12:01
8

For exiting app ways:

Way 1 :

call finish(); and override onDestroy();. Put the following code in onDestroy():

System.runFinalizersOnExit(true)

or

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

Way 2 :

public void quit() {
    int pid = android.os.Process.myPid();
    android.os.Process.killProcess(pid);
    System.exit(0);
}

Way 3 :

Quit();

protected void Quit() {
    super.finish();
}

Way 4 :

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);

if (getIntent().getBooleanExtra("EXIT", false)) {
     finish();
}

Way 5 :

Sometimes calling finish() will only exit the current activity, not the entire application. However, there is a workaround for this. Every time you start an activity, start it using startActivityForResult(). When you want to close the entire app, you can do something like the following:

setResult(RESULT_CLOSE_ALL);
finish();

Then define every activity's onActivityResult(...) callback so when an activity returns with the RESULT_CLOSE_ALL value, it also calls finish():

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(resultCode){
        case RESULT_CLOSE_ALL:{
            setResult(RESULT_CLOSE_ALL);
            finish();
        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}
Lennon Spirlandelli
  • 3,131
  • 5
  • 26
  • 51
hitesh141
  • 963
  • 12
  • 25
  • Intent intent = new Intent(getApplicationContext(), LoginActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra("EXIT", true); startActivity(intent); is working super fine. – hitesh141 Apr 15 '15 at 09:31
  • I have started Activity A->B->C->D. When the back button is pressed on Activity D I want to go to Activity A. Since A is my starting point and therefore already on the stack all the activities in top of A is cleared and you can't go back to any other Activity from A. @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { Intent a = new Intent(this,A.class); a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(a); return true; } return super.onKeyDown(keyCode, event); } – hitesh141 Apr 15 '15 at 09:52
5

This is how Windows Mobile has worked for... well... ever! Here's what Microsoft have to say on the matter:

http://blogs.msdn.com/windowsmobile/archive/2006/10/05/The-Emperor-Has-No-Close.aspx (is it sad that I remembered the title of the blog post all the way from 2006? I found the article on Google by searching "the emperor has no close" lol)

In short:

If the system needs more memory while the app is in the background, it’ll close the app. But, if the system doesn’t need more memory, the app will stay in RAM and be ready to come back quickly the next time the user needs it.

Many comments in this question at O'Reilly suggest that Android behaves in much the same way, closing applications that haven't been used for a while only when Android needs the memory they're using.

Since this is a standard feature, then changing the behavior to forcefully close would be changing the user experience. Many users would be used to the gentle dismissal of their Android apps so when they dismiss one with the intention of returning to it after performing some other tasks, they may be rather frustrated that the state of the application is reset, or that it takes longer to open. I would stick with the standard behavior because it is what is expected.

Andy E
  • 338,112
  • 86
  • 474
  • 445
5

Calling the finish() method on an Activity has your desired effect on that current activity.

r1k0
  • 1,406
  • 1
  • 11
  • 26
  • 14
    No it doesn't. It finishes the current Activity, not the application. If you finish() the bottom-most Activity on the task stack, your application will appear to exit, but Android may decide to actually keep it around for as long as it sees fit. – mxk Jan 19 '10 at 14:23
  • Indeed, however if you need to fully exit your application, you need to call the finish method for each activity and also think about any services you might have started. I've edited the initial answer also - sorry for the omission. – r1k0 Jan 20 '10 at 10:06
3

Copy below code and paste AndroidManifest.xml file in under First Activity Tag.

<activity                        
            android:name="com.SplashActivity"
            android:clearTaskOnLaunch="true" 
            android:launchMode="singleTask"
            android:excludeFromRecents="true">              
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER"
                />
            </intent-filter>
        </activity>     

Also Add this below code in all under Activity Tag in AndroidManifest.xml file

 android:finishOnTaskLaunch="true"
Android
  • 2,383
  • 1
  • 26
  • 44
3

none of all above answers working good on my app

here is my working code

on your exit button:

Intent intent = new Intent(getApplicationContext(), MainActivity.class);
ComponentName cn = intent.getComponent();
Intent mainIntent = IntentCompat.makeRestartActivityTask(cn);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
mainIntent.putExtra("close", true);
startActivity(mainIntent);
finish();

that code is to close any other activity and bring MainActivity on top now on your MainActivity:

if( getIntent().getBooleanExtra("close", false)){
    finish();
}
3

Use "this.FinishAndRemoveTask();" - it closes application properly

Nitika Chopra
  • 1,281
  • 17
  • 22
2
@Override
    protected void onPause() {
        super.onPause();
        System.exit(0);
    }
Haris
  • 4,130
  • 3
  • 30
  • 47
2

Simply write the following code in onBackPressed:

@Override
public void onBackPressed() {
    // super.onBackPressed();

    //Creating an alert dialog to logout
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    alertDialogBuilder.setMessage("Do you want to Exit?");
    alertDialogBuilder.setPositiveButton("Yes",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    Intent intent = new Intent(Intent.ACTION_MAIN);
                    intent.addCategory(Intent.CATEGORY_HOME);
                    startActivity(intent);
                }
            });

    alertDialogBuilder.setNegativeButton("No",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface arg0, int arg1) {

                }
            });

    //Showing the alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();
    alertDialog.show();
}
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
2

Put a finish(); statement as below:

myIntent.putExtra("key1", editText2.getText().toString());

finish();

LoginActivity.this.startActivity(myIntent);

In every activity.

beginner
  • 21
  • 1
1

Not possible with 2.3. I search alot, and tried many apps. The best solution is to install both (go taskmanager) and (fast reboot). When use them together it will work, and will free the memory. Another option is to upgrade to android ice cream sandwich 4.0.4 which allow control (close) of apps.

Pablo Claus
  • 5,886
  • 3
  • 29
  • 38
ali
  • 19
  • 1
1

i wanted to return to the home screen of my android device, so i simply used :

moveTaskToBack(true);
1

Use of finishAffinity() may be an good option if you want to close all Activity of the app. As per the Android Docs-

Finish this activity as well as all activities immediately below it in the current task that have the same affinity.
Sanjeet A
  • 5,171
  • 3
  • 23
  • 40
1
public class CloseAppActivity extends AppCompatActivity
{
    public static final void closeApp(Activity activity)
    {
        Intent intent = new Intent(activity, CloseAppActivity.class);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
                IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        finish();
    }
}

and in manifest:

<activity
     android:name=".presenter.activity.CloseAppActivity"
     android:noHistory="true"
     android:clearTaskOnLaunch="true"/>

Then you can call CloseAppActivity.closeApp(fromActivity) and application will be closed.

Artyom
  • 1,099
  • 15
  • 18
0

by calling finish(); in OnClick button or on menu

case R.id.menu_settings:

      finish();
     return true;
Community
  • 1
  • 1
Kosh
  • 6,140
  • 3
  • 36
  • 67
  • As stated in other answer's comments, `finish()` does not kill the App. It may go back to previous Intent or background the App. – Raptor Jan 14 '14 at 03:04
0

I think it will close your activity and all Sub activity related to it.

public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();]
        if (id == R.id.Exit) {
            this.finishAffinity();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
Lakshay Jain
  • 446
  • 1
  • 3
  • 17
0

The best and shortest way to use the table System.exit.

System.exit(0);

The VM stops further execution and program will exit.

Rasoul Miri
  • 11,234
  • 1
  • 68
  • 78