By Ted


2010-01-09 15:59:46 8 Comments

Moving on in my attempt to learn Android, I just read the following:

Question: Does the user have a choice to kill the application unless we put a menu option in to kill it? If no such option exists, how does the user terminate the application?

Answer: (Romain Guy): The user doesn't, the system handles this automatically. That's what the activity lifecycle (especially onPause/onStop/onDestroy) is for. No matter what you do, do not put a "quit" or "exit" application button. It is useless with Android's application model. This is also contrary to how core applications work.

Hehe, for every step I take in the Android world I run into some sort of problem =(

Apparently, you cannot quit an application in Android (but the Android system can very well totally destroy your app whenever it feels like it). What's up with that? I am starting to think that it's impossible to write an app that functions as a "normal app" - that the user can quit the app when he/she decides to do so. That is not something that should be relied upon the OS to do.

The application I am trying to create is not an application for the Android Market. It is not an application for "wide use" by the general public, it is a business app that is going to be used in a very narrow business field.

I was actually really looking forward to developing for the Android platform, since it addresses a lot of issues that exist in Windows Mobile and .NET. However, the last week has been somewhat of a turnoff for me... I hope I don't have to abandon Android, but it doesn't look very good right now =(

Is there a way for me to really quit the application?

30 comments

@Jawad Zeb 2018-04-11 08:14:57

Another Option can be Android Accessibility Services Which Greenify Application is using to Force close applications to speedup memory. With having your application accessibility service access you can click on buttons so basically Greenify Application clicks on the force close Button found in settings of an application:

Here you can study accessibility services: https://developer.android.com/reference/android/accessibilityservice/AccessibilityService.html

Here is the Setting Button which accessibility service clicks programitically: enter image description here

So You can Achieve Killing any Application Including Yours By the following Steps:

1) Register Application for Accessibility Services 2) Depending on your requirements if you want to kill all application get list of All Packages 3) Navigate to their Settings Screen And Click Force Close Button Thats It. I can Share a sample code I also created an application like greenify as an home assignment. Thank you

Update: "The user doesn't, the system handles this automatically." So Basically with this solution we are indirectly using system force close but on the User Demand. So That Both Stay Happy :-)

@Dominic Cerisano 2015-01-24 08:55:53

The Android application life cycle is designed for mobile phone users, not computer users.

The app life-cycle is the brutally simplistic paradigm required to turn a Linux server into a consumer appliance.

Android is Java over Linux, a real cross-platform server OS. That is how it spread so quickly. The app life-cycle encapsulates the underlying reality of the OS.

To mobile users, apps are just installed or not installed. There is no concept of running or exiting. In fact, app processes are meant to run until the OS releases them for their held resources.

Since this is Stack Overflow, anyone reading this is a computer user and must turn off 90% of their knowledge to understand the mobile app lifecycle.

@Don Hatch 2018-02-20 16:48:41

I don't follow your leap to "computer users must turn off 90% of their knowledge". Yes, that's what Romain Guy says, but that doesn't make it true. It seems to me an "Advanced options for computer users" section, with a "Quit" button, would serve everyone's needs.

@Dominic Cerisano 2018-03-09 09:46:01

I have no idea who this "Romain Guy" is, or why he is quoting me. Closing recent tasks will quit the app, as does stopping from app info. ADB allows shell access for advanced users.

@Harer 2014-09-16 03:49:00

You can use Process.killProcess(Process.myPid()); to kill your app, but maybe it is not safe? I didn't encounter any problem or crash after I used this method and after I used this, the process of my app in the DDMS list disappeared.

@raguM.tech. 2014-03-26 10:32:22

Currently I implemented the following in my app. May these helps to move out from the application from whereever you want. I am calling this function from action bar Menus.

public static void exitApplication(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        exitApplicationHC(context);
    }
    else {
        exitApplicationPreHC(context);
    }
}

private static void exitApplicationPreHC(Context context) {
    Intent i = new Intent(context, LoginActivity.class);
    i.putExtra(EXTRA_EXIT, true);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(i);
    if (context instanceof Activity) {
        ((Activity) context).finish();
    }
}

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private static void exitApplicationHC(Context context) {
    Intent i = new Intent(context, LoginActivity.class);
    i.putExtra(EXTRA_EXIT, true);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    context.startActivity(i);
}

@Jesse Gordon 2013-09-09 04:25:29

Answer: (Romain Guy): The user doesn't, the system handles this automatically. That's what the activity lifecycle (especially onPause/onStop/onDestroy) is for. No matter what you do, do not put a "quit" or "exit" application button. It is useless with Android's application model. This is also contrary to how core applications work.

1: Totally exiting an application may be generally unmandatory, but it is not useless. What if windows had no exit option? System would be doggy slow as memory was full and the OS had to guess at which programs you were done with. I don't care what Romain Guy or even Larry Page and Sergey Brin say - these are unquestionable facts: Systems run slower when they have to kill tasks to get their memory before a new app can be launched. You just can't tell me that it doesn't take time to kill an app! Even the light from distant stars take time... There is some use in allowing the user to fully close apps.

2: Contrary to how core applications work? What's that supposed to mean? When I'm done running an app for now, it is no longer doing any work...It's just waiting to be killed by the OS when its memory is needed.

In summary, there is a distinct difference between minimizing and exiting, and neither pinch hits well for the other. Do we leave a screwdriver in every screw? Or a key in every door? Do we leave all of our appliances on high until the breaker blows and we need to turn on another appliance? Do we leave the dish washer full of dishes, and only take out enough each time to make room for some new dirty ones? Do we leave all the cars running in the driveway until -- oh never mind.

If the user wants to minimize an app, then the best thing is to minimize it. If a user wants to exit an app, then by all means it is best to exit.

Is it frowned on? That's Android's view - they frown on it. And many many independent rookie Android developers frown on it.

But when it comes right down to it, there is good coding and bad coding. There is good program flow models and there are bad program flow models.

Leaving programs in memory when the user knows they are done with them simply is not good program flow. It serves absolutely no purpose whatsoever, and it slows things down when launching new apps or when running apps allocate more memory.

It is sort of like your car: There are times when you leave it running, like stopping at a stop light, or perhaps the fast food drive through, or stopping at the ATM. But there are other situations where you do want to shut it off - like when you get to work, or the grocery store or even home.

Similarly, if you're playing a game and the phone rings, yes. Pause the game and keep it running. But if the user is done with the game for a while, then by all means let them exit.

The exit button on some applications should be more out in front than others. Games, for example, or programs where the user is likely to want to fully exit, should have an obvious exit. Other programs, like, perhaps, email programs, where exiting is an unlikely desire (so that it can keep checking for email) -- these programs should not waste prime control input screen space with an exit option, but for good program flow, it should have an exit option. What if someone decides they don't want their mail program trying to check email when they are in poor coverage area, or maybe in a Skype call or whatever? Let them exit the email program if they want!

Suspending and exiting are two vital tasks and neither fulfills the role of the other.

@HoGo 2017-02-02 20:53:14

"If the user wants to minimize an app, then the best thing is to minimize it. If a user wants to exit an app, then by all means it is best to exit." - There is a thing (based on more that decade of experience): users rarely knows, what they want. If you do not help them, you will have to change it. About samples above: let me give you other sample: you are working on a car and have a table at hand for things. Do you always put away to correct place all necessary tools to cabinet or keep the most used ones at hand? And just put away a big late used one to have place for new ones?

@Jesse Gordon 2017-02-03 22:42:19

HoGo, thanks for your comment. Naturally, I do disagree. Specifically, as best as I can tell, your view is that since some users don't know what they should do, therefore don't let any users do what they should do, not even the ones that know what they should do. If android had a way to accurately know whether it should terminate an app instead of minimizing it, then fine. But it doesn't, and forcing all users to always live with minimization when they want to exit leads to poor device performance.

@Husnain Iqbal 2013-04-14 11:31:45

For the first (starting ) activity of the application,

@Override
public void onBackPressed(){

    // Exit
    moveTaskToBack(true);
}

worked for me. I want to close the app here. And to come back from other activites; I used intents, e.g.

@Override
public void onBackPressed(){

    // Going back....
    Intent intent = new Intent(ActivityB.this, ActivityA.class);
    startActivity(intent);
    finish();
}

Note: This code is useful for the scenario where the developer wants to come back from ActivityZ to ActivityA and then close the app.

@GaneshKumar 2012-11-17 12:35:43

Every time while you move to the next page through intent, use:

`YourActivityname.this.finish()`;

Example:

Intent intent = new Intent(getApplicationContext(), SMS.class);

startActivity(intent);
MainActivity.this.finish();

So that no activity will be running on background and when you want to Exit your app, use:

MainActivity.this.finish();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
getParent().finish();

This exiting worked like a charm for me :)

@Sharath 2015-08-31 11:46:54

It doesnt exit the app instead it comes to Mainactivity.

@Pavel Biryukov 2015-10-29 09:09:37

But be careful - onPause() IS NOT called in the case of killProcess and System.exit. We had some problems with that.

@Ravi 2012-08-29 11:26:15

This is quite simple. Just follow these instruction which I am going to tell you:

Like you are having multiple activities, to go from one activity to another. You might be using the intent like this:

Intent i1 = new Intent(this, AnotherActivity);
startActivity(i1) 

You have just to add finish(); after starting the intent activity on each and every activity from start to end, for example,

Intent i1=new Intent(this, AnotherActivity);
startActivity(i1) 
finish();

So whenever you will click that exit button which is using finish() or System.exit(0) that must close your application completely.

@IgorGanapolsky 2012-09-12 17:48:10

Why are you calling finish() right after startActivity(i1)? What is the goal here?

@Andries 2012-05-19 12:58:43

Almost 99% of the time there is no need for an Android application to take over its own life cycle. Most of the time it comes down to better planning or smarter design of the application. For example, rather build an internal service (not exported) to handle downloads, etc., or design actions and tasks around user workflow.

But that being said, where there is a will there is a way. Android provides - through the android.os.Process class, a much better API than Java to control the underlying process. And unlike Java it does not treat the developer like a moron by hiding it all behind a simple java.lang.System.exit() call.

So how do you ask your application to commit suicide in Android? Well, the trick is simple:

Create your own Android application class by inheriting from the standard android.app.Application class (remember to declare it in the AndroidManifest.xml file).

Override the onCreate() method, and store the process ID which started your application:

this.pid = android.os.Process.myPid(); // Save for later use.

Now to kill your application, provide a kill() method:

android.os.Process.sendSignal(pid, android.os.Process.SIGNAL_KILL);

Now whenever you need your app to commit suicide just type cast the application context, and call your kill method!

((MySuicidalApp) context.getApplicationContext()).kill()

Just remember that due to the process management policies in Android, specifically related to services, Android may just opt to restart your service (see You should not use task killers on Android).

@Dheeraj V.S. 2012-04-22 16:49:45

Blog post When to Include an Exit Button in Android Apps (Hint: Never) explains it far, far better than I can. I wish every Android developer has read it already.

Excerpts:

In my experience what [the users] really want is: An unambiguous way to guarantee that an app will stop consuming resources (battery, CPU cycles, data transfer, etc.).

Many users perceive that an exit button implements this requirement and ask for it to be added. Developers, looking to please their users, obligingly add one. Shortly thereafter they both fail.

  • In most cases the exit button simply calls Activity.finish(). This is exactly equivalent to hitting the back button. Exactly. Services keep running and polling keeps happening. Users may think they've killed the app but they haven't, and soon they'll be even more annoyed.
  • Exit behavior is now ambiguous. Should your exit button just close the Activity, or should it also stop all associated Services, Receivers, and Alarms? What should Back do? What happens if they hit Home instead? What happens if your app has a widget? Should the exit button stop that from updating too?

The solution is to make the back button behave as you'd expect the exit button to. Better yet, simply stop consuming resources whenever the app isn't visible.

Go ahead and read the complete article.

@IgorGanapolsky 2012-09-12 17:51:59

Exit and Back are not always used for the same purpose. Take, for example, Pandora. When you hit back to get out of this app, it doesn't exit the app (keeps it playing in the background as a service).

@Dheeraj V.S. 2012-09-13 04:49:30

@IgorG. A music player app needs a "Stop" button to stop playing music, not an "Exit" button to exit the app.

@IgorGanapolsky 2012-09-13 13:18:46

Have you ever used Pandora, iHeartRadio, Spotify, Jango and other music streaming apps? They all have a quit button. Stopping music play is NOT THE SAME THING as quitting an app. Especially if you have a service running in the notification bar.

@Dheeraj V.S. 2012-09-14 05:11:51

@IgorG. I'm sure all those apps implement their so called Exit button by simply stopping their service that plays music and perhaps by finish()ing the activity. It is just that they have chosen to call this button as 'Exit' or 'Quit' to pander to the ignorant users who demand such a button and to give them that warm, fuzzy feeling of completely obliterating the app. How else do you think this mythical quit button is implemented? Using System.exit()???

@IgorGanapolsky 2012-09-14 14:41:09

Mythical or not, primitive users or not, but almost every UI software ever written - on any platform and OS - implements a quit/close/exit button. How else would you implement it?

@Pacerier 2014-11-17 10:18:26

@DheerajV.S., Simply stop consuming resources whenever the app isn't visible? Bad advice. Very. Very x99. Whenever I try to email myself a photo, I have to keep the app visible for a full 5 minutes because if I minimize it, it stops emailing the photo. Correct, I can't use my phone for a full 5 minutes just because of some developer who thinks apps should run only when visible. Now imagine sending a larger file like video.....

@Martin Marconcini 2014-11-17 20:54:38

At 8tracks I basically renamed the button to Shutdown. When used, I stopped media players (and released them), killed the music service with stopSelf(), cleared up some memory caches and finished the activity stack. Finally I did a system.exit. It's hacky but it works. Android users are annoying with these fake task managers and "OMG I SEE YOUR PROCESS RUNNING, MY CRAPPY BATTERY IS GONNA LAST LESS NOW!" even tho the service does "nothing" if you are not playing. Anyway, happy users = happy devs. ;)

@StErMi 2012-04-06 09:16:58

First of all, never never never use System.exit(0). It is like making a person sleep punching him on the head!

Second: I'm facing this problem. Before sharing my solution a I want to share my thoughts.

I think that an "Exit Button" is stupid. Really really really stupid. And I think that users (consumer) that ask for an exit button for your application is stupid too. They don't understand how the OS is working and how is managing resources (and it does a great job).

I think that if you write a good piece of code that do the right things (updates, saves, and pushes) at the right moment and conditions and using the correct things (Service and Receiver) it will work pretty well and no one will complain.

But to do that you have to study and learn how things works on Android. Anyway, this is my solution to provide to users an "Exit Button".

I created an Options Menu always visible in each activity (I've a super activity that do that).

When the user clicks on that button this is what happens:

Intent intent = new Intent(this, DashBoardActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

SharedPreferences settings = getSharedPreferences(getString(PREF_ID), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(FORCE_EXIT_APPLICATION, true);

  // Commit the edits!
editor.commit();
startActivity(intent);
finish();

So I'm saving in SharedPreferences that I want to kill my app, and I start an Intent. Please look at those flags; those will clear all my backstack calling my DashBoard Activity that is my "home" activity.

So in my Dashboard Activity I run this method in the onResume:

private void checkIfForceKill() {

    // CHECK IF I NEED TO KILL THE APP

    // Restore preferences
    SharedPreferences settings = getSharedPreferences(
            getString(MXMSettingHolder.PREF_ID), Context.MODE_PRIVATE);
    boolean forceKill = settings.getBoolean(
            MusicSinglePaneActivity.FORCE_EXIT_APPLICATION, false);

    if (forceKill) {

        //CLEAR THE FORCE_EXIT SETTINGS
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean(FORCE_EXIT_APPLICATION, false);

        // Commit the edits!
        editor.commit();

        //HERE STOP ALL YOUR SERVICES
        finish();
    }
}

And it will work pretty well.

The only thing that I don't understand why it's happening is that when I do the last finish (and I've checked: it's following all the correct flow of onPause → onStop → onDestroy) the application is still on the recent activity (but it's blank).

It seems like the latest intent (that has started the DashboardActivity) is still in the system.

I've to dig more in order to also remove it.

@Squiggles 2012-05-12 03:43:13

Not many consumers know what an OS is let alone how one works, this does not make them stupid. Wanting an Exit/Quit/Off button makes them normal. When you leave a room you turn off the lights, more importantly when you leave your house you lock the door and this is where I see the problem with the inability to properly exit a program. Leaving the program alive in the background is a big security risk.

@IgorGanapolsky 2012-09-12 17:53:34

"I think that a "Exit Button" is stupid". Most software applications provide an exit button.

@IgorGanapolsky 2012-09-12 17:56:42

You said "//HERE STOP ALL YOUR SERVICES" and then used finish(). Android services do not have a finish() method. They have unbindService(mConnection);

@Seshu Vinay 2015-01-31 08:43:39

@Squiggles If you have a room that automatically turns off all of its lights and lock your door when you leave, you don't need to care about it.

@Solostaran14 2012-03-06 18:22:51

When I conceive an application in Android, I see it this way:

  • You are working with your application
  • The phone rang
  • You take the call
  • At the end of the call, you come back to your application at the same place you were

To do that, you only need the Back button or the Home button of your phone (either by short or long press) and the notification bar.

When I exit my application, I only use the Back button until I am out of it or the Home button.

That's how most of the applications are conceived I think. But if I need some sort of session or connection, I made it clear to the user with a login/logout button and notification (title bar or anything else). This is a rather different style than the pure "exit" style application.

On PCs, you have a multi-GUI desktop, and on Android, you obviously have multi-tasks, but you only display one app at a time (I don't consider widgets here ^^). And on a mobile phone, at anytime, you could have a notification for something more important than what you are doing.

So the whole concept of an application rely on something different that "enter application - work - exit application".

@Navidonline 2012-02-08 11:54:43

Use this code:

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

@Heiko Rupp 2012-02-08 12:18:39

Did you try that? And shouldn't a finish() in the activity that is called first be enough?

@Harpreet 2012-03-28 11:21:09

This code just minimize the app, it don't do an exit. :P

@Andy Joiner 2013-01-16 11:12:24

I tried this but 3 threads were still left running even thought the activities closed. It may have appeared to work when running under the debugger, but in normal use, when I queried running processes from another app, it's still running.

@Pradeep Sodhi 2012-01-30 08:00:59

For closing an app at any point use FLAG_ACTIVITY_CLEAR_TOP flag in Intent and then system.exit();

Or there is similar way, but without system.exit() when you want to exit call this method:

public void exit() {
    startActivity(new Intent(this, HomeActivity.class).
    setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK).putExtra(EXIT_FLAG, true));
}

In your HomeActivity.onCreate() add following code

protected void onCreate(Bundle savedInstanceState) {
    if (getIntent().getBooleanExtra(EXIT_FLAG, false)) {
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0) {
            finish();
        }
    }
......................

This will work without breaking the Android life-cycle.

@Peter Teoh 2011-05-20 07:14:41

The Linux kernel has a feature called Out-of-memory killer (as mentioned above, the policies are configurable at the userspace level as well as the kernel is not an optimal one, but by no means unnecessary).

And it is heavily used by Android:

Some userspace apps are available to assist with these kill apps, for example:

@Brant 2011-03-29 15:37:26

It took me longer to read this Q&A than to actually implement a semi-proper Android Application Lifecycle.

It's a GPS app that polls for points and sends the current location to a webservice every few seconds using a thread... This could be polling every 5 minutes in Ted's case for an update, then onStop can simply start the update activity Ted was soo concerned about if one was found (asynchronous Ted, don't code like a Windows programmer or your programs will run like Windows programs ... eww, it's not that hard).

I did some initial code in onCreate to set up things for the activity lifetime, including checkUpdate.start();:

...

@Override
public void onStart() {
    super.onStart();
    isRemote = true;
    checkUpdate.resume();

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 0, luh);
}

@Override
public void onPause() {
    isRemote = false;
    checkUpdate.suspend();
    locationManager.removeUpdates(luh);
    super.onStop();
}

This code may be completely wrong, but it works. This is one of my first Android applications.

Voilà, an application that doesn't consume CPU when it's in the background, yet is instantly ready to reopen because it is in RAM (although not holding RAM as is the Android lifecycle) ... an app is always ready, it's a phone, guys/gals. If an app was to use up all the RAM and couldn't be shut down by the OS then the thing might stop ringing =P That's why the OS needs to be able to close your app when it's in the background (if your application isn't a resource hog it won't be closed BTW), so let's just write better applications.

@Matt Wolfe 2013-11-15 23:13:49

You shouldn't be calling super.onStop from onPause method.. This seems like it would screw things up majorly.

@Pacerier 2014-11-17 10:46:32

After reading through 20 or so philosophical answers that merely dodges the question.... +1 for having some code.

@Chad Hedgcock 2011-02-05 03:20:58

This debate boils down to the age-old question of whether the developers know best or whether the user knows best. Professional designers in all areas of human factors struggle with this every day.

Ted has made a point in that one of the most downloaded apps on the Market is the 'App Killer'. People get a bit of extra serotonin when they quit applications. They're used to it with a desktop/laptop. It keeps things moving fast. It keeps the processor cool and the fan from turning on. It uses less power.

When you consider that a mobile device is a much smaller ship, then you can especially appreciate their incentive to 'throw overboard what you no longer need'. Now the developers of Android have reasoned that the OS knows best and that quitting an app is antique. I wholeheartedly support this.

However, I also believe that you should not frustrate the user, even if that frustration is borne out of their own ignorance. Because of that, I conclude that having a 'Quit' option is good design, even if it is mostly a placebo button that does nothing more than close a View.

@IgorGanapolsky 2012-09-12 19:09:43

Yes, having a 'Quit' button is indeed user-friendly. How else would the user quit the app if he is 5 activities deep into it? Sure they can press back multiple times, but I don't think they'd like that.

@Joe Plante 2012-09-27 18:24:15

Only 5? The Android 2.2 web browser makes me spend a few minutes tapping the back button until I eventually exit

@DVK 2012-11-07 10:32:28

I would start listening to developers of android when they develop memory manager that WORKS. As of Froyo, it worked extremely poorly, killing off random apps, re-starting apps that don't need to be (and have no Intents to start them legitimately), and OTOH, slowing to a COMPLETE crawl when memory hits 50MB free.

@DVK 2012-11-07 10:34:49

When your religion says that Android Task Killer is "un-necessary", but using ATK to kill off dumb tasks that have no business running changes the OS from crawling at ~1-5% of normal speed back to 100% of normal speed (measured) 100% of time across 1000s of ATK usages over 2 years everytime the system hits 50MB free low end, your religion is wrong

@Logan 2013-04-20 22:25:22

@JoePlante You can close all the open tabs and windows first and then simply press the back button once to quit :) At least on my GS2 that is.

@Joe Plante 2013-04-22 19:52:25

@Logan Dam: No tabs on the 2.2 browser I used, my friend.

@Paul 2010-09-20 06:57:21

This is an interesting and insightful discussion with so many experts contributing. I feel this post should be looped back from within the Android development main website, because it does revolve around one of the core designs of the Android OS.

I would also like to add my two cents here.

So far I have been impressed with Android's way of handling lifecycle events, bringing the concept of a web-like experience to native apps.

Having said that I still believe that there should be a Quit button. Why? ... not for me or Ted or any of the tech gurus here, but for the sole purpose of meeting an end user demand.

Though I am not a big fan of Windows, but long back they introduced a concept that most end users are used to (an X button) ... "I want to quit running a widget when 'I' want to".

That does not mean someone (OS, developer?) will take care of that at its/his/her own discretion... it simply means "where is my Red X button that I am used to". My action should be analogous to 'end a call on pressing of a button', 'turn off the device by pressing a button', and so on and so forth ... it's a perception. It brings a satisfaction per se that my action indeed achieve its purpose.

Even though a developer can spoof this behavior using suggestions given here, the perception still remains i.e. an application should completely cease to function (now), by an independent, trusted and neutral source (OS) on demand from the end user.

@Qwertie 2012-04-17 22:44:09

Right. Good ol' Windows Mobile offered the same X button as Windows PCs, except that it did not actually quit the app, it just "smart minimized" it. Many users probably never found out the app didn't really quit. (The approach worked great, although if you used .NET Compact Framework, the app was not notified that this had happened and so did not have the option to free resources or actually quit.)

@Jon O 2012-07-30 14:38:55

Really, this amounts to lying to your users to give them a warm, fuzzy feeling. Ultimately, it's better to let the relics of the past fall to the wayside, lest they continue to be permanent fixtures of technology. Mobile and web are new platforms, and aren't expected to behave the same as desktops. And anecdotally, at least, Android's lifecycle decisions seem to be catching on with users: as my biggest app passes its 2 year anniversary, I have noticed the stream of end-user requests for "exit" buttons drying up as they get used to the new platform.

@IgorGanapolsky 2012-09-12 18:57:55

@Jon What do you recommend? Not offering an 'exit' option anywhere in the app?

@Jon O 2012-09-12 19:47:03

Well, when a user requested an exit button, I would explain to them precisely how things worked differently than on a desktop (which is the same explanation I give them when they mention task killers). Now, the information seems to have caught on, and I don't get those requests anymore. So, I recommend you explain it a few times (maybe come up with a canned response) and leave out the button. Or put in a fake exit button that pops a dialog explaining why there are no more exit buttons. :D (Also in Android 4+ a user can swipe an app "off" of the multitasking display to "kill" it.)

@William T. Mallard 2013-05-06 16:46:37

Personally I've come to use the home button as an exit button, which I find to be equally satisfying to a red X.

@DDSports 2014-02-09 12:04:48

I also haven't found the reasoning behind all the advice saying "don't kill the process". In my opinion, the customer is always right, so what's wrong with providing an exit button after it's been requested and "lying to your users to give them a warm, fuzzy feeling", if that's what they want? This is partly what writing good apps is all about. Most user don't know or care what's really going on under the hood, but if they like your app and it does what they want and expect, they'll come back and buy more of your apps. That's what we all want, isn't it? Or am I missing something?

@vgps 2010-08-21 04:04:39

Without an exit function for the application developer to kill their own application it is very bad design.

My application needs to allow the user to dynamically change data dynamically during runtime and the user needs to restart my application to make the change effect, but Android did not allow my application restart by itself. Android OS has a very bad design application life cycle.

@androidworkz 2011-01-21 17:36:27

public void appRestart() { Intent i = new Intent(getBaseContext(), MyActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i); }

@Harpreet 2012-03-28 11:23:57

This above comment's code really works well. At least you can move to first activity instead of complete exit from App. :)

@dipu 2010-08-06 20:15:36

I hope things will change over time. The user should be able to kill an app or process if the app process is sandboxed correctly by the OS. There is a notion that apps should be written perfectly or user will use only the apps that follow all SDK recommendations. I think that is a tall order.

@Dan 2010-11-19 07:33:46

Apple IOS ring a bell?

@dipu 2010-12-25 20:47:37

I know. Apple products are good for some consumers. They are not good for developers. Android OS has full potential to become like the "Windows OS of the PC world" for mobile phones. may be even better. It is already more open than windows of the PC world, except it is not allowing us to write a task manager.

@Burke 2010-07-13 00:28:52

I agree with Ted. I understand that exiting the application is not the "Android way", but it doesn't seem like it should be precluded. Here are three reasons why you might want a real exit to the application (not just the activity):

  1. The user might want some control over which app gets killed in the case of low memory. If important app A is running in the background, then you might like to exit app B when you are done with it so that app A doesn't get killed by the operating system.

  2. If your application has sensitive data cached in memory, you might like to kill the app so that a virus/worm/rogue app can't get at it. I know the security model is supposed to prevent that, but just in case...

  3. If your application uses resources (like network, CPU, sensors, etc.) that could adversely affect the phone, then one way of ensuring that those resources are freed up is to exit the application. I understand that well-behaved apps should free up resources when they are not needed. But again, exiting the application seems like a reasonable way of ensuring that.

@seanhodges 2010-07-13 08:11:42

What do you think represents the "application"? If I open the Facebook app, and set a new profile pic - my Camera or Gallery apps start up. As a user, I'm still performing the same task (using Facebook). If I then decide to close Facebook, my Camera and Gallery apps have to close too (since they are activities launched from Facebook)... What if I was in the middle of editing some of my other pics and had only intended to close Facebook? You would have shifted the problem to potential data loss.

@Neil Traft 2010-07-13 15:56:41

Well, I don't think it could go as far as data loss. If you have a third-party activity running in the same task as your own activity, and your own activity is the one with the exit button, then the user has to finish() the third party activity before he can hit the exit button. And the third party activity should be saving any unsaved information at that time. I don't think you can use the app switcher to return to the exit button activity unless it's running in a separate task. And if it's a separate task, it's a separate process, and therefore won't be killed by the exit button.

@Burke 2010-07-14 01:44:18

In my mind, the "application" is the underlying linux process that is running all of my activities. But I am not an android guru so maybe my understanding is flawed. I write fortran number crunching code in real life, so maybe I am just a dinosaur.

@Zsolt Török 2010-07-14 11:00:08

1. I think 99.99% of Android users should not worry about how the OS manages applications behind the curtains. The rest are geeks and will find advanced tools do make the system behave exactly how they want. 2. You can always unload any sensitive data when the activity gets paused or stopped. 3. Same as above, resources can be freed in lifecycle callback methods. When the activity resumes, resources can be allocated again.

@Ted 2010-07-21 10:59:48

I think its rather interesting that sooo many Android users are installing "Advanced Task Killer", an app that closes down other apps since you normally cant do it yourself. I use it all the time myself. Quitting an app is not something I feel you can do without.

@Pacerier 2014-11-17 10:31:34

@ZsoltTörök, 99.99% of people deal with slow computers/phones and are forced out of choice to worry about how the OS manages applications behind the curtains.

@Dronz 2019-01-05 01:19:17

I agree with this answer, and can think of several more. For example, when I use my Android, I don't want bunches of apps filling the list of apps that are loaded, so I can find the ones I want easily and not be distracted. Also, I don't necessarily want people I show my phone to to see the apps I have been running. I also LIKE the traditional application model's inclusion of a way to close apps and return to a starting point when I want to re-load them. Also apps don't necessarily do nothing when not in the foreground, and I many apps do stuff I don't want being done on my phone, Etc etc etc.

@Slig 2010-02-07 15:34:09

Hmmmm...

I think that you just don't see the Android app the right way. You can do something almost like what you want easily:

  • Do the app activities save/restore state like it is encouraged in the developer livecycle documentation.

  • If some login is needed at the restore stage (no login/session information available) then do it.

  • Eventually add a button/menu/timeout in which case you will do a finish() without saving the login and other session info, making implicitly the end of app session: so if the app is started/brought to front again it will start a new session.

That way you don't really care if the app is really removed from memory or not.

If you really want to remove it from memory (this is discouraged, and BTW for what purpose?) you can kill it conditionally at the end of onDestroy() with java.lang.System.exit(0) (or perhaps restartPackage(..)?). Of course do it only in the case where you want to "really end the app", because the onDestroy() is part of the normal lifecycle of activities and not an app end at all.

@Andy 2010-01-13 23:36:10

I would consider reading "Android Wireless Application Development" published by Addison-Wesley. I am just finishing it up and it is VERY thorough.

It appears that you have some fundamental misunderstandings of the Android platform. I too was a little frustrated at first with the application life-cycle of Android apps, but after coming to a greater understanding, I have come to really enjoy this approach. This book will answer all of your questions and much more. It really is the best resource I have found for new Android developers.

Also, I think you need to let go of a line-for-line port of the existing app. In order to port your application to the Android platform, some of the application design is going to change. The application-lifecycle used is necessary as mobile devices have very limited resources relative to desktop systems and allows Android devices to run several applications in an orderly and resource-aware fashion. Do some more in depth study of the platform, and I think you will realize that what you are wanting to do is entirely feasible. Best of luck.

By the way, I am no way affiliated with Addison-Wesley or any person or organization associated with this book. After re-reading my post I feel that I came off a little fanboyish. I just really, really enjoyed it and found it extremely helpful. :)

@Ted 2010-01-14 02:55:12

Thanks for the book tip. I will take a look at it if I can and if I decide to move on the the Android port. Just to state it again though: our users are not very up-to-date when it comes to computers. I will be very hard for them to use for example the NotificationBar in Android. Too small (they have BIG fingers hehe). Its a different world for them, so we need to keep it simple and without options for the user. We built our .NET-solution with that in mind - dont give them a choice =)

@Andy 2010-01-16 03:56:19

I hear that. You have to assume most users are not very tech smart.

@Ted 2010-07-21 11:06:09

I get so tired of the mantra of how little "resources" a mobile device has. Wake up, they are running on over 500Mhz and has loads of memory. My old Dell Axim had 128MB of RAM. The current devices out there have usually over 512RAM and running on 1GHZ! That is 10 times more than my old Pentium 90Mhz, and I didnt hear ppl saying "the very limited resources" this and that. Its time to wake up and smell the coffee - we are in the 2010 now, not the 80ies.

@Tasos Kleisas 2010-01-11 17:59:00

In any case, if you want to terminate your application you can always call System.exit(0);.

@Dheeraj V.S. 2012-09-13 07:22:20

System.exit() does NOT kill your app if you have more than one activity on the stack. An Android developer who uses it has not understood the basic Android app life-cycle. Read this answer.

@Sohail Zahid 2016-08-09 06:34:59

Full solution with System.exit(0); stackoverflow.com/questions/2033914/…

@Jesse Gordon 2017-12-11 06:37:25

Actually, System.exit() does kill your app. However, if the System.exit() was called from someplace other than the main activity, android will restart the app with one less activity on the stack. To me that seems like a ridiculous response to a clean intentional System.exit. I mean, if it was a div0 or some unintentional crash, maybe it would be polite to restart. But those don't even cause auto-re-launch as I recall. But in any case, the app is killed. It may be restarted, but that doesn't mean it was not killed.

@Aaron 2010-01-10 19:25:59

Ted, what you are trying to accomplish can be done, perhaps just not how you are thinking of it right now.

I suggest you read up on Activities and Services. Stop using the term "app" and start referring to the components, i.e. Activity, Service. I think you just need to learn more about the Android platform; it is a change in mindset from a standard PC app. The fact that none of your posts have had the word "Activity" (short of a FAQ quote, i.e. not your words) in them tells me you need to read some more.

@Ted 2010-01-11 17:10:00

Ive read most of the stuff on android.com =) and I can link to several of my questions where I talk about Activities, so thats not true (ex: stackoverflow.com/questions/2032335/… or stackoverflow.com/questions/2032335/… etc...) However, I might give it one last go, and try to create the who "app" as a Servce...

@Aaron 2010-01-11 23:10:18

An app can contain Services and Activitys, and it sounds like your app may need both. The activity is only the UI part.

@Sohail Zahid 2016-08-09 06:28:39

If you have 10,20 .. multiple Activities running and you want to finish all them and exit from system.

Create a static array in application class or constants class.

Constants

public class Constants {

public static ArrayList<Activity> activities = new ArrayList<Activity>();

}

MainActivity Add current activity reference in this array

activity = MainActivity.this; Constants.activities.add(activity);

public class MainActivity extends Activity {

    private ImageView imageButton;
    private Activity activity;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        activity = MainActivity.this;
        Constants.activities.add(activity);

        imageButton = (ImageView) findViewById(R.id.camera);
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // existing app.
                if (Constants.activities != null) {
                    for (int i = 0; i < Constants.activities.size(); i++) {
                        Activity s = Constants.activities.get(i);
                        s.finish();
                    }
                }
                //super.finish();
                finish();
                android.os.Process.killProcess(android.os.Process.myPid());
                System.exit(1);
            }
        });
    }
}

@HopefullyHelpful 2016-12-08 12:55:25

This can crash your app when the users tabs a button twice, especially when the system is under heavy load for any reason. This can be prevented by removing the activities from the array.

@CommonsWare 2010-01-09 17:35:40

This will eventually get to your question, but I first want to address a number of issues you raise in your various comments to the various answers already given at the time of this writing. I have no intention of changing your mind -- rather, these are here for others who come to read this post in the future.

The point is that I cannot allow for Android to determine when my app is going to be terminated. that must be the choice of the user.

Millions of people are perfectly happy with the model where the environment closes up the application as needed. Those users simply don't think about "terminating" the Android app, any more than they think about "terminating" a Web page or "terminating" a thermostat.

iPhone users are much the same way, in that pressing the iPhone button does not necessarily "feel" like the app was terminated, since many iPhone apps pick up where the user left off, even if the app really was shut down (since iPhone only allows one third-party app at a time, at present).

As I said above, there is a lot of things going on in my app (data being PUSHed to the device, lists with tasks that always should be there, etc.).

I don't know what "lists with tasks that always should be there" means, but the "data being PUSHed to the device" is a pleasant fiction and should not be done by an activity in any case. Use a scheduled task (via AlarmManager) to update your data for maximum reliability.

Our users log in and can't be doing that every time they get a phone call and Android decides to kill the app.

There are many iPhone and Android applications that deal with this. Usually, it is because they hold onto logon credentials, rather than forcing users to log in every time manually.

For example, we want to check updates when exiting the application

That is a mistake on any operating system. For all you know, the reason your application is being "exited" is because the OS is shutting down, and then your update process will fail mid-stream. Generally, that's not a good thing. Either check updates on start or check updates totally asynchronously (e.g., via a scheduled task), never on exit.

Some comments suggest that hitting the back button does not kill the app at all (see link in my question above).

Pressing the BACK button does not "kill the app". It finishes the activity that was on-screen when the user pressed the BACK button.

It should only terminate when the users wants to terminate it - never ever any other way. If you can't write apps that behave like that in Android, then I think that Android can't be used for writing real apps =(

Then neither can Web applications. Or WebOS, if I understand their model correctly (haven't had a chance to play with one yet). In all of those, users don't "terminate" anything -- they just leave. iPhone is a bit different, in that it only presently allows one thing to run at a time (with a few exceptions), and so the act of leaving implies a fairly immediate termination of the app.

Is there a way for me to really quit the application?

As everybody else told you, users (via BACK) or your code (via finish()) can close up your currently-running activity. Users generally don't need anything else, for properly-written applications, any more than they need a "quit" option for using Web applications.


No two application environments are the same, by definition. This means that you can see trends in environments as new ones arise and others get buried.

For example, there is a growing movement to try to eliminate the notion of the "file". Most Web applications don't force users to think of files. iPhone apps typically don't force users to think of files. Android apps generally don't force users to think of files. And so on.

Similarly, there is a growing movement to try to eliminate the notion of "terminating" an app. Most Web applications don't force the user to log out, but rather implicitly log the user out after a period of inactivity. Same thing with Android, and to a lesser extent, iPhone (and possibly WebOS).

This requires more emphasis on application design, focusing on business goals and not sticking with an implementation model tied to a previous application environment. Developers who lack the time or inclination to do this will get frustrated with newer environments that break their existing mental model. This is not the fault of either environment, any more than it is the fault of a mountain for storms flowing around it rather than through it.

For example, some development environments, like Hypercard and Smalltalk, had the application and the development tools co-mingled in one setup. This concept did not catch on much, outside of language extensions to apps (e.g., VBA in Excel, Lisp in AutoCAD). Developers who came up with mental models that presumed the existence of development tools in the app itself, therefore, either had to change their model or limit themselves to environments where their model would hold true.

So, when you write:

Along with other messy things I discovered, I think that developing our app for Android is not going to happen.

That would appear to be for the best, for you, for right now. Similarly, I would counsel you against attempting to port your application to the Web, since some of the same problems you have reported with Android you will find in Web applications as well (e.g., no "termination"). Or, conversely, someday if you do port your app to the Web, you may find that the Web application's flow may be a better match for Android, and you can revisit an Android port at that time.

@Ted 2010-01-09 18:09:12

Thanks for this answer commonsware =) And I agree totally. Actually, I made the reference and comparison between Android and a webpage yesterday when I discussed these issues with my collegue with whom I work. I indeed feel that Android tries to imitate some form of webpage, and that is not what I call "a real app" (even though that is subjective of course). If the app could be transformed to a WebApp, then I might just create a webpage and ask the users to start their web browser. But thats not the case =(

@Ted 2010-01-09 18:12:48

Im not going to comment in detail on all what you wrote. They are all good and valid comments, but not really knowing what our apps is and how it is working today (the server structure cannot change, the idea was to port the mobile app to Android) makes it hard, of course, for you to see whats needed. Even though we "keep login credentials", that would mean that the users logs in everytime something happens on the device and the server is isnstructed to react in certain ways on login. That cant be done just randomly, as would happen in an Android-application...

@Ted 2010-01-09 18:14:01

Nonetheless, thanks for the answer. It was informative and appreciated =)

@Christopher Orr 2010-01-09 18:24:37

Mark: Thanks for the good summary. Ted: We're very slowly discovering what functionality you require, like long-lived sessions. As mentioned, you can use a Service for that. Also, I doubt that you need to log in to your app each time you interact with the server -- surely there's a session ID token you can hold onto?

@Ted 2010-01-09 18:30:41

One thought that drifted in my head: If I just rewrite the whole app as a Service, and treat that Service as the actual application - perhaps that would work better? Then I could "dumb up" the Activities (just as Android wants them) to just present data contained in the Service. In that case, I could perhaps keep login state and other stuff there. Using startForeground(int, Notification) I can almost stop Android from killing the Service...?

@Ted 2010-01-09 18:33:21

Christopher: yes, your tip on using Services has been in my mind since then, see the above comment =) I also have to say that I really appreciate your comments, and everyone elses. I learn a lot, even though I get disappointed with the way things work... ;-)

@Ted 2010-01-09 18:34:22

Well, actually the server just keeps track of "valid TCP-connections". When the client connects to server, the server only accepts the Login-packet. If such a packet is received, then the server checks to see if login == OK. If so, the TCP-connection used to send teh Login-packet is saved in a Hash. Whenever a incoming packet is received on one of the many TCP-connections in the server, the server know what User is logged in on that TCP-connection. So if the TCP-connection dies (android killed the app), a new login is required...

@CommonsWare 2010-01-09 19:10:47

"Using startForeground(int, Notification) I can almost stop Android from killing the Service...?" Assuming your users will not mind having an icon in their status bar, this should work. Or, to put it another way, if your service still gets killed due to low RAM even after using startForeground(), you have much bigger problems.

@Ted 2010-01-09 19:17:32

How do you mean I have bigger problems? That should be the same problem I would have in a "normal non-service app" on Android? Please note that my users are professionals, that use the device for the sole purpose of using the application Im trying to port to Android. They will not be using it for anything else =)

@CommonsWare 2010-01-09 20:05:27

"How do you mean I have bigger problems?" I mean that the only way this will occur is if the device is having serious memory issues, probably requiring a reboot. A startForeground() service is 2nd-to-last to have to get killed off for memory reclamation (last being the foreground activity). Since Android apps do not have unlimited heap sizes, the only way this should occur is either because lots of apps are abusing startForeground() or if the OS itself is leaking RAM.

@CommonsWare 2010-01-09 20:07:36

"Please note that my users are professionals, that use the device for the sole purpose of using the application Im trying to port to Android." Actually, you have indicated otherwise ("cant be doing that everytime they get a phonecall" -- a "phonecall" is not your app). Moreover, unless you are building your own device, you can't prevent people from installing other apps if they so choose.

@Christopher Orr 2010-01-09 22:37:32

As another aside, surely you'd be caching the user's credentials anyway if you're relying on long-lived TCP connections for session management? For a mobile application, it would seem a bit crazy to expect the user to manually re-establish their session just because the device lost the network temporarily.

@SomeCallMeTim 2010-10-29 23:24:47

While your answer is correct for Java apps, there's a good reason to kill an application completely: If you're using NDK code of an app ported, for example, from iPhone, that isn't going to expect the process to be recycled, and therefore has a pile of code with global or static values that will be in an invalid state if the application "exits" and restarts. finish() doesn't even help here, in fact; the application won't even get an onDestroy() call until well after another instance has a chance to run, reusing the process. android.os.Process.killProcess(android.os.Process.myPid()); works. :)

@CommonsWare 2010-10-30 06:27:20

@SomeCallMeTim: No, that is not a valid reason to use killProcess(). It is a valid reason to write better iOS code.

@SomeCallMeTim 2010-10-30 22:30:22

@CommonsWare: Sorry, but that's a trite answer that is of no use to me. I'm porting code that I'm paid to port. Should I spent twice the time doing the port, rewriting their code, or get it done in the way that reduces costs for my employer, allowing them to put more games on Android sooner? It's an entirely academic question anyway: They don't want me to make such major changes to their engine, since I can't test the changes on iOS. AND it's simply wrong: There's nothing "bad" about using Singleton patterns for appropriate objects. Android is just broken WRT NDK apps.

@CommonsWare 2010-10-31 07:53:39

@SomeCallMeTim: "application won't even get an onDestroy() call until well after another instance has a chance to run, reusing the process" -- color me skeptical, but even then, there should be ways to address the problem without resorting to killProcess() (e.g., detect the change in Application object in your NDK library). I suggest that you open a fresh SO question so we can get more info about the exact pattern you are using and problems you are perceiving.

@CommonsWare 2010-10-31 18:25:18

@SomeCallMeTim: Dianne Hackborn has officially endorsed your approach, should you need it: groups.google.com/group/android-developers/browse_thread/thr‌​ead/… -- personally, I still think we could find an alternative.

@SomeCallMeTim 2010-11-01 03:54:11

@CommonsWare: Thanks for letting me know about that thread. I'm in that group as well as the NDK group, but I only get emails for the NDK group, so I never saw that discussion.

@gcb 2010-11-17 04:22:51

tl;dr. but just wanted to add that YES, take your head out of the sand and agree that android documentation is a mess. i understand OP when he says he may never delevelop for android because of that (and maybe java:). e.g. they talk about the multi task android way, but then the menu example blatantly shows a "Quit" option.... wtf?!

@Android Eve 2011-02-11 19:13:52

@CommonsWare This is a remarkable answer. Thank you. I expected to find the word/term "service" in the answer but I didn't. Did I miss anything?

@Ted 2011-10-12 20:49:11

Im back on trying Android, and I ran into this quitting-business once again. One major problem with not being able to fully destroy/quit a Service/whatever is that it is insanely error-prone! If I could restart an app (for real) I would know for SURE that all variables are reset - that everything is initialized to its starting point. Now, I need to do all that manually. So if I add a variable, and then forget to reset also that I'm gonna have problems when I "relaunch" the app, as soem variables (and stuff) will be lingering. This is still something I cannot understand how anyone can defend.

@Barry Fruitman 2011-11-10 17:42:55

Lifecycle management of activities by the OS is not an immutable law (if it were we would all be writing for iPhone instead). Many users prefer the warm fuzzy feeling of knowing an app is closed after they logout, not to mention avoiding the extra keypress to return to the home screen. Leaving an app hanging around when it is doing absolutely nothing is also a drain or resources while waiting for the OS to do it. If it weren't app killers wouldn't be so popular (and necessary).

@Qwertie 2012-04-17 22:34:08

@Ted for more reliable reinitialization, maybe you could minimize the amount of state that is stored at the Activity or Service itself. Instead, place most of the state and code in a separate class that you recreate "from scratch" every time the Activity or Service starts.

@Name is Nilay 2012-07-14 11:14:51

I had the same dilemma about Killing the appliction....thanks that helped !!!

@Jon O 2012-07-30 14:28:30

@BarryFruitman App killers are not necessary, and in fact will break many properly-functioning apps. An activity that isn't in the foreground isn't using the CPU, so there's no issue with "leaving it hanging around" i.e., cached in memory. The OS will just kill it if it needs the memory. And if an app is using the CPU but not running in the foreground, it is running a service; i.e., not "doing absolutely nothing".

@Barry Fruitman 2012-07-30 18:44:27

@Jon O: Yes, but CPU is not the only limited resource. Unused apps are a waste of RAM, too. The OS may kill them automatically, but it doesn't always do it in the order one might expect or prefer. As for app killers, I tend to agree with you now, but I still think a good old-fashioned "close" button is a good idea for certain apps.

@Jon O 2012-07-30 18:53:16

@BarryFruitman On pretty much every platform, even after an app is closed, it stays cached in RAM until the system has a reason to replace it in RAM with something else. Android is no different (except in Android's case, the heap an app is allowed to use is bounded). The only time where that distinction between "closed" and "idle" becomes meaningful on Android is under very high memory load, and with phones approaching 2GiB of RAM, one isn't likely to run into them very often. (And 100% of RAM is always powered, so no impact on battery life by closing memory-resident idle apps.)

@Barry Fruitman 2012-07-30 19:07:42

@Jon O: 1) I'm pretty sure it is standard practice to free all RAM immediately when an app exits, especially in Android where every app gets its own JVM. Just because RAM isn't wiped doesn't mean anything is "cached". 2) I'm even more certain Android heap size is not unbounded. 3) Heavy memory load happens quite frequently on older devices. Not everyone has a 2Gb phone. 4) Unreleased RAM is not a waste of battery, but it is just a waste of... well, RAM.

@Jon O 2012-07-30 19:19:44

@BarryFruitman 1) "Free" is commonly implemented as "indicate that someone else can use this should they need it". So if you reopen an app immediately, almost everything becomes a cache hit. 2) Agreed; reread! :) 3) Not certain but IIRC apps are closed in LRU order when contention occurs. 4) There is no such thing. It's only wasted if it isn't in use; unused RAM = free cache! geekfor.me/faq/you-shouldnt-be-using-a-task-killer-with-andr‌​oid <-- see the Addendum, especially.

@user1767754 2014-02-19 01:16:26

This requires more emphasis on application design, focusing on business goals and not sticking with an implementation model tied to a previous application environment. this is a very important part of the thext

@Jesse Gordon 2014-07-30 01:21:46

Regarding "Millions of people are perfectly happy with the model where the environment closes up the application as needed." Millions of people also have to wait several seconds to answer their phone after it rings because Android has to free memory first by killing apps you haven't used in weeks. I say if users want to exit the JVM that runs their app so that memory is available right away when they need it, then by all means let them! ~Jesse

@Martin Marconcini 2014-10-09 02:04:03

"Millions of people also have to wait several seconds to answer their phone after it rings because Android has to free memory first by killing apps you haven't used in weeks." -> Fortunately this is not the case. Android apps are generally killed a lot faster than that. Don't believe "fake" task managers and the fact that Android does, in fact, show you the app in the task manager, that doesn't mean it's using memory, in fact, you will rather have to fight to HAVE your memory not killed all the time at any time, than having to worry about the opposite.

@Pacerier 2014-11-17 09:39:37

@CommonsWare, He is asking how to build an application like a web server. The "web app model" you so adore is actually severely limited. You can't build a database server or a web server using "web app model". Indeed, there is no such thing as a major application using pure "web app model" because a web app model itself relies on a web server that runs on "program model".

@Pacerier 2014-11-17 10:42:33

@MartínMarconcini, It doesn't change the fact that you'd have to wait. One second is one second too long. Anything near two seconds is an eternity.

@Martin Marconcini 2014-11-17 20:45:35

@Pacerier I agree that exit buttons are OK for some things (heck, even I had to add one to 8tracks app when I worked there, and it was a pain to add). But that is not going to make your Ringer faster.

@Pacerier 2014-11-19 20:05:47

@MartínMarconcini, It has the potential to go faster when the OS does not need to kill tasks to get their memory before a new app can be launched.

@Martin Marconcini 2014-11-20 00:40:18

@Pacerier the benefits are superior to the few milliseconds you may gain. CPU on the other hand, may hinder your phone. Memory? most modern devices have enough ram to plan ahead and Android does a great job (I've always used Nexus devices). The same goes for iOS, the memory models work fine. Can it be improved? Sure but I'd say there are more important things than that. For example, the horrible state of the lifecycle between Activities and Fragments to name one.

@Pacerier 2014-11-20 08:02:17

@MartínMarconcini, What superior benefits are you talking about? Implementing an exit button has the superior usability benefit. And there will never be enough ram, especially so on a hand-held device. Do you not know that demand grows with supply?

@Martin Marconcini 2014-11-20 18:17:37

The superior benefits are many: Developers don't have to think about it 99% of the time. Users don't have to worry. Applications are consistent. It's not an issue with modern devices. You can certainly wait 50ms to answer your phone. Given the quality of code that I see from Android Developers (especially here on StackOverflow), I'm glad about this. Now… would I like an exit button that kills the process (And its children) at Operating System Level? Yes, but the abuse of this, could cause apps to use more battery (restarting the app means moving all the stuff to memory again, etc.)

@sebastian nielsen 2016-06-20 00:02:07

I really don't agree with it being like a web page. A web page runs 100% at the server so its accessible for all users at any time. But an app does run inside the user's terminal (eg mobile phone), and can be equvalient of "minimizing" in windows. In the same way people don't minimize when they are finished with something, same should apply to apps IMHO. Imagine a notepad app. If I want to continue on my old note, I press home button, and then return to the note later. But if I want to start on a fresh empty note. Then it should be possible to kill the app and then start fresh.

@BlackOverlord 2018-01-31 08:11:46

Totally agree with sebastian nielsen. As a user I can say that the big difference between mobile app and web app is that web app doesn't run on MY device and doesn't consume MY resources. So I don't care what it does after i leave it by closing browser tab. But when i finish working with app and i close it (e.g. any game or other "heavy" app) i really want to CLOSE it rigtht at the time. I don't want it leaving until OS decides to kill it.

@Xieyi 2015-06-30 09:41:14

If you specify API >= 16, Activity#finishAffinity() meets your needs.

@h22 2014-06-22 11:19:28

One of the important reasons to have the exit button is the "on exit" advertisment. On the exit, it is possible to display some revenue-generating ad. It is still somewhat annoying, like all ads are, but may be less annoying than something that keeps hanging around all time, using precious screen space. Some ad networks offer this way of advertisement. But, really, you cannot just put an exit button that does nothing after showing that ad!

As a result, one or another way to terminate the program is required in some cases, and "should never be needed" may not be the most comprehensive answer.

Activity.finish() or System.exit(0) could probably be used.

@Pacerier 2014-11-17 10:49:50

On exit advertisement is not the reason Android-exiting is so badly needed.

@Dan 2010-08-04 21:51:36

If you are unable to fathom how to make your data/connections (and thereby your "application") persistent, then you will be unable to do what you "need" to do with Android.

Those who do download those cutesy little App Killers usually find they do not help battery life or memory usage, but hinder the OS from doing it's job of managing memory efficiently...

http://android-developers.blogspot.com/2010/04/multitasking-android-way.html

@Neil Traft 2010-08-05 00:42:34

While we're talking about task killers, a very enlightening post appeared on the Android reddit a couple of days ago. The gist is, use task killers carefully or you could actually end up hurting your battery life: reddit.com/r/Android/comments/cwhm6/…

@dipu 2010-08-09 06:14:12

@Neil Traft, I found the comments on the post very enlightening. Sales reps in the stores are recommending and installing task killers for their customers :)

@Jesse Gordon 2013-09-09 03:54:26

@Dan, How is it even remotely possible that me fully exiting an app that I'm done with for a week hinder Android OS from its job? So there's more free memory. That can't possibly hinder android! It sure could speed things up later, though! If I know I'm done with the app for a while, it serves absolutely no purpose whatsoever. It only takes up memory, and sooner or later, I will launch a new app and the OS will have an added delay because it has to go kill some apps that I knew WEEKS ago that I was done with.

@Dan 2013-09-10 15:50:41

@Jesse Gordon, Have you watched the actual processes after you killed an app? They get restarted, the OS assumes there was a problem... The OS will kill apps when it needs memory. Did you even read anything posted in the articles mentioned around here?

@Pacerier 2014-11-17 10:23:54

@Dan, To think that Android would do something like this.... it really needs some serious white-washing re-education.

Related Questions

Sponsored Content

26 Answered Questions

16 Answered Questions

[SOLVED] Ship an application with a database

2 Answered Questions

[SOLVED] How is bundle sent to onCreate if App process killed?

4 Answered Questions

1 Answered Questions

2 Answered Questions

[SOLVED] Android destroying activities, killing processes

0 Answered Questions

How to stopService when App is fired

  • 2015-06-13 14:25:19
  • MaybeMercy
  • 25 View
  • 0 Score
  • 0 Answer
  • Tags:   android ondestroy

2 Answered Questions

[SOLVED] In which cases should one override onDestroy()?

2 Answered Questions

[SOLVED] event when app is started, stopped and paused

2 Answered Questions

[SOLVED] When to commit application settings to SharedPreferences (onStop or onDestroy)

  • 2013-02-07 17:03:41
  • Cheok Yan Cheng
  • 3285 View
  • 7 Score
  • 2 Answer
  • Tags:   android

Sponsored Content