8

How can i close my application programmatically?

I used

   finish();

Or

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

Or

System.exit(0);

Or

moveTaskToBack(true);

but it closed the current running activity, but i need to close the whole application??

I need to close app to retrieve some memory and then restart application again.

Or

does there is a way to clear all memory of the application?

Mahmoud Emam
  • 1,499
  • 4
  • 20
  • 37

1 Answers1

10

Using these lines in your activity:-

this.finish();
Process.killProcess( Process.myPid() ); 

will kill your whole application (assuming its running in a single process) it will also free any associated memory.

WARNING: On some phones doing this may leave bluetooth sockets dangling if you are using them.

IAmGroot
  • 13,760
  • 18
  • 84
  • 154
David
  • 452
  • 5
  • 8
  • This didn't help me. actually situation is like- I have to activity A and B and when user is on activity B and pressed back then it will be redirected to Activity A by using intent. and I want when user is on activity A now and pressed back key, whole application should be closed as Activity A is Main Activity. But What is happening is that- when user is on activity A and pressed back then activity B comes on front. Please give any advice how can i close by application if user is on main activity and pressed back button. – Avinesh May 22 '13 at 13:02
  • @neel you should not start another instance of A from B. In A use `startActivityForResult()` and exit B using `this.setResult()` with `this.finish()`. Activity A now received a parameter from B, without starting another instance. – Barry Staes Apr 09 '14 at 08:48
  • @David: what about 'System.exit(0);' ,does this also leave the bluetooth sockets dangling if we use them? .If yes,what other methods are there to gracefully close an application? – Basher51 Jul 26 '14 at 11:12
  • 1
    By the way, this is totally bad practice! Do not kill process! – Vyacheslav Feb 03 '17 at 13:03