how to close android app completely

元气小坏坏 提交于 2019-11-27 12:52:45
ryderz8

To Quit Application on Button click use this code :

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);

Try it..

To kill the complete app and remove it from Runningapp list kill the app through its pid(its nasty)... use this lines before above code.

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

If you want to close application completely you should use finishAffinity(); instead of finish() . It will clear all stack of activities previously opened by an application.

chiru

To Finish an Activity I'm using this code:

public void appExit () {
    this.finish();
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
}  //close method

or kill Process with this code:

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

For Xamarin Users:

int pid = Android.OS.Process.MyPid();
Android.OS.Process.KillProcess(pid);

put it in your OnDestroy() function.

Edit:

After investigating it thoroughly, I found out that even the above code I wrote does not "Kill" the app totally (deleting it from task manager - "recent apps"). Eventually, after a lot of code tryouts, I managed to figure something out, Overriding "Finish" functions with this code:

public override void Finish()
    {
        if (Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
        {
            base.FinishAndRemoveTask();
        }
        else
        {
            base.Finish();
        }
    }

this is the sole solution for that question!

For API 21 and up

finishAndRemoveTask()

You can call this to close the app completely. All activities will finish() and the app is removed from the task list.

Pavel Polushkin

Even if it looks ok killing process will cause you headache in future. You can ensure this by following use case:

  1. call several activities to populate activities stack
  2. call android.os.Process.killProcess(pid);
  3. open your application

OBSERVED: Your application opens not from main activity in inconsistent way. This is because Android consider killing of process like crash.

You can find more detailed information here: Is quitting an application frowned upon?

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

I think this is better. How about it ?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!