Ted
Ted

Reputation: 20184

Is quitting an application frowned upon?

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?

Upvotes: 1251

Views: 299480

Answers (30)

sb4
sb4

Reputation: 189

As a novice Android developer, I am getting familiar with the life cycle, etc. As an Android user, I have always hated that I can't obliterate an app.

Why should any user trust an app? We may think putting an app in the background is "safe", but does the user? We may be in love with the genius of the "new" way of doing things, but not all apps are written perfectly or even well. Some may be nefarious and try to keep background processes running at all times. Some may be well-intentioned but messy.

I hate opening a browser or google and starting up at the last place I left off and having to back-stack dozens of slow pages just to feel like I get a clean start. The user should be in ultimate control. How many times does tech support tell us to "reboot our machine" or "close the program and restart"? Users need to feel they are rebooting an app, not restoring a state which possibly was frustrating them or causing them problems.

You can't expect people to retain a sophisticated model of an environment just to use an app to get something done. People feel in control of a pencil and paper because it is manifest in their experience of how it behaves and will behave in the future. Software is magic which all takes place behind the curtain. The rules for its behavior are as capricious as the developer that created it.

We should try to design appliances that relate to an underlying, almost physical, model that is robust and reliable and truly intuitive to the user. "Killing" an app is something a user can embrace. It's like throwing out a pile of scratch paper and starting over; closing a book and putting it back on the shelf. Magic has its place for dedicated professionals who can invest themselves in a particular world, such as video editing or animation systems. And these users often contribute to the features themselves and so are comfortable with them. But everyday users deserve at least a few really grounded options they can rely on regardless of sophistication level, in my opinion. I'm for an easy way to exit a process completely even if it is not the target model the system aspires to.

Upvotes: 1

CommonsWare
CommonsWare

Reputation: 1007534

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 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 login 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 want 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.

Upvotes: 1342

ThirdPrize
ThirdPrize

Reputation: 194

You have probably spent many years writing "proper" programs for "proper" computers. You say you are learning to program in Android. This is just one of the things you have to learn. You can't spent years doing watercolour painting and assume that oil painting works exactly the same way. This was the very least of the things that were new concepts to me when I wrote my first app eight years ago.

Upvotes: 6

Jawad Zeb
Jawad Zeb

Reputation: 523

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 :-)

Upvotes: 2

Birkensox
Birkensox

Reputation: 3721

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.

Upvotes: 9

Harer
Harer

Reputation: 101

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.

Upvotes: 1

raguM.tech.
raguM.tech.

Reputation: 183

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);
}

Upvotes: 1

Jesse Gordon
Jesse Gordon

Reputation: 1455

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.

Upvotes: 25

Husnain Iqbal
Husnain Iqbal

Reputation: 466

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.

Upvotes: 2

GK_
GK_

Reputation: 1222

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 :)

Upvotes: 6

Ravi
Ravi

Reputation: 2367

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.

Upvotes: 2

Andries
Andries

Reputation: 317

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).

Upvotes: 17

Dheeraj Vepakomma
Dheeraj Vepakomma

Reputation: 28767

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.

Upvotes: 25

StErMi
StErMi

Reputation: 5469

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.

Upvotes: 7

Solostaran14
Solostaran14

Reputation: 1665

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".

Upvotes: 15

Navidonline
Navidonline

Reputation: 98

Use this code:

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

Upvotes: 1

Pradeep Sodhi
Pradeep Sodhi

Reputation: 2145

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.

Upvotes: 7

Peter Teoh
Peter Teoh

Reputation: 6753

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:

Upvotes: 10

Brant
Brant

Reputation: 41

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.

Upvotes: 6

Chad Hedgcock
Chad Hedgcock

Reputation: 11785

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.

Upvotes: 32

Paul
Paul

Reputation: 1759

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.

Upvotes: 74

vgps
vgps

Reputation: 65

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.

Upvotes: 7

dipu
dipu

Reputation: 1340

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.

Upvotes: 10

Burke
Burke

Reputation: 351

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.

Upvotes: 10

Slig
Slig

Reputation: 79

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.

Upvotes: 12

Andy
Andy

Reputation: 131

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. :)

Upvotes: 17

Tasos Kleisas
Tasos Kleisas

Reputation: 314

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

Upvotes: 4

Aaron
Aaron

Reputation: 201

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.

Upvotes: 31

Sohail Zahid
Sohail Zahid

Reputation: 8149

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);
            }
        });
    }
}

Upvotes: 3

Xieyi
Xieyi

Reputation: 1328

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

Upvotes: 0

Related Questions