spentak
spentak

Reputation: 4727

Exit Android App - Kill all processes

We have a live video streaming app with a lot going on. A user presses the home button. I want the app to be removed from memory. When the app is selected again we have a brand new load. There are a lot of processes going on and we don't want to have to manually manage all the connections, streams, etc. This is how our iPhone version of the app works.

I've read this: Is quitting an application frowned upon?

I don't really care about Androids design patterns here either way. However if someone has an elegant, simple way that all my activities will be removed from the stack when the home button is pressed, and then when the app is reloaded it starts with a fresh main activity, that would be great. Also, I can't seem to ever debug when the home key is pressed in onKeyDown. Its simply not registering. (keyCode == KeyEvent.KEYCODE_HOME) is my check. It picks up back buttons, etc.

Any thoughts?

Upvotes: 0

Views: 6391

Answers (5)

IgorGanapolsky
IgorGanapolsky

Reputation: 26821

If you want to clear all of your activities from the stack, you can broadcast an intent from the activity which initiates the quit like this:

Intent broadcastIntent = new Intent();
broadcastIntent.setAction("CLEAR_STACK");
sendBroadcast(broadcastIntent);

And in every one of your activities that you want to be cleared off the stack you can create a BroadcastReceiver with an inner class:

class ActivitiesBroadcastReceiver extends BroadcastReceiver {
  @Override
  public void onReceive(Context context, Intent intent) {
    finish();
  }
}

And register your BroadcastReceiver in the onCreate() method:

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("CLEAR_STACK");
BroadcastReceiver r;
r = new ActivitiesBroadcastReceiver();
registerReceiver(r, intentFilter);

Upvotes: 0

Ankit Dhingra
Ankit Dhingra

Reputation: 125

you can do than on button click. Define any static method like exit() and define

android.os.Process.killProcess(android.os.Process.myPid()); in exit method

in the main or first activity.

Then call this method on button click.

Upvotes: 0

Philip Sheard
Philip Sheard

Reputation: 5815

int p = android.os.Process.myPid();
android.os.Process.killProcess(p);

Upvotes: 1

Matt
Matt

Reputation: 5511

Could you just override the onPause method and use the finish() function?

Upvotes: 1

MByD
MByD

Reputation: 137282

You can call system.exit(0); but I would still suggest to follow the Android guidelines, and clean everything (as should be) on onPause() or similar method.

Upvotes: 3

Related Questions