Search code examples
androidexitback-button-control

How to exit with stopping the background running from application but, not close services


I have long been looking for a solution on how to close an android application.

Gathering all the posts dealing with the subject, I ended up building a healthy and effective solution that I wanted to share in this post

Please, correct me if I have failed somewhere.

public static void closeApp(Activity activity) {
    //Go to home to change main android view and focus
    //You can remove this part
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        activity.startActivity(intent);

    //finish in background many activities as possible
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        activity.finishAndRemoveTask();
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        activity.finishAffinity();
    } else {
        activity.finish();
    }

    //Kill all existing app process
    activity.moveTaskToBack(true);
    android.os.Process.killProcess(android.os.Process.myPid());

    //close the app
    System.exit(0);
}

using example

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            closeApp(MainActivity.this);
        }
    });
}

Solution

  • The approach you are using looks quite comprehensive when it comes to releasing the resources and completely closing the app. Although I feel its a bit over-done but if that's what your use case demands, then no issues. You can check this SO for more insights.

    I have comment on following line

    stopping the background running from application but, not close services

    android.os.Process.killProcess(android.os.Process.myPid()); This method will kill the process with given PID. If your Services are running in this PID then they will be killed too.

    Starting from Android O, several restrictions on background execution have been imposed, due to which you cannot keep services running in background. When your application exits, OS will terminate the Services as if you have called stopSelf(). As a consequence, you won't be able to keep your Services alive.