I am sure this question has been asked number of times because I read a few. My client wants me to put a button into his app where users can click and exit. I have read this and found calling finish()
will do it. But, finish is only closing the current running activity right? I have lot of activities so in this case I have to pass each and every activity's instance and finish them or make every activity into Singleton pattern.
I also got to know Activity.moveTaskToBack(true)
can get you into the home screen. OK, this is not closing but backgrounding the process. So is this is effective?
Which method should I use to close the app completely? Any of above described or any other method/other usage of above methods?
The finishAffinity method, released in API 16, closes all ongoing activities and closes the app:
this.finishAffinity();
Finish this activity as well as all activities immediately below it in the current task that have the same affinity. This is typically used when an application can be launched on to another task (such as from an ACTION_VIEW of a content type it understands) and the user has used the up navigation to switch out of the current task and in to its own task. In this case, if the user has navigated down into any other activities of the second application, all of those should be removed from the original task as part of the task switch.
Note that this finish does not allow you to deliver results to the previous activity, and an exception will be thrown if you are trying to do so.
Since API 21, you can use:
finishAndRemoveTask();
Finishes all activities in this task and removes it from the recent tasks list.
Alternatives:
getActivity().finish(); System.exit(0);
int pid = android.os.Process.myPid(); android.os.Process.killProcess(pid);
Process.sendSignal(Process.myPid(), Process.SIGNAL_KILL);
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);
Source: How to quit android application programmatically
Hope it helps! Good Luck!
Actually everyone is looking for closing the application via an onclick event, wherever may be activity...
Add this code to an onclick event:
Intent homeIntent = new Intent(Intent.ACTION_MAIN); homeIntent.addCategory( Intent.CATEGORY_HOME ); homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(homeIntent);
You can call System.exit(); to get out of all the acivities.
submit=(Button)findViewById(R.id.submit);
submit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With