How to force stop my android application programmatically?

前端 未结 6 959
天涯浪人
天涯浪人 2020-11-27 05:59

I\'d like to force stop my Android application when I click closeButton. This is my code.

protected void onCreate(Bundle savedInstanceState) {

  this.setCon         


        
相关标签:
6条回答
  • 2020-11-27 06:15

    I know it is a late reply , hope this helps some one.

    You can try finishAndRemoveTasks(); instead of finish(); in your snippet.

    This would kill your application's all activities and all process and even remove for recent apps from task manager.

    Note: If you have use any kind of handler or thread in your code make sure you remove its functionalities and then use the above suggested code , if not NullPointer Exception or ResourceNotFound Exception would occur.

    0 讨论(0)
  • 2020-11-27 06:17

    Another way is

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

    I don't think it's all that bad to do this, provided you put those calls in onDestroy(). (If you kill your process in the middle of event handling, all kinds of bad things—like the touch focus going into the ether—can happen.)

    Nevertheless, you need a compelling reason to deviate from best practice, which is to just call finish() and let the OS take care of killing off your process when/if it needs to.

    0 讨论(0)
  • 2020-11-27 06:22

    Why not to make a Shell-Call to ActivityManager?

    try {
          Runtime.getRuntime().exec("am force-stop com.me.myapp");
        } catch (IOException e) {
          e.printStackTrace();
        }
    
    0 讨论(0)
  • 2020-11-27 06:23

    A bad way to kill the application would be System.exit(0)

    Edit: I believe I owe some explanation. Android handles the application lifecycle on its own, and you are not supposed to 'ForceClose' it, and I don't know any good way to do it. Generally its ok if your application is still alive in the background, this way if user launches it again it will pop up quickly.

    0 讨论(0)
  • 2020-11-27 06:25

    Note: This does not kill the entire app, but if what you want to do is to finish all the app activities, this is the best option.

    Android ≥ 16

    finishAffinity();

    Android < 16

    ActivityCompat.finishAffinity(Activity activity)

    Hope this helps

    0 讨论(0)
  • 2020-11-27 06:39

    Short and simple

    Intent homeIntent = new Intent(Intent.ACTION_MAIN);
    homeIntent.addCategory( Intent.CATEGORY_HOME );
    homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(homeIntent);
    
    0 讨论(0)
提交回复
热议问题