How to close entire application?

2019-04-17 12:34发布

问题:

I am beginner in android. When i click a Button KILL selected apps to close or kill a Particular(Running) Application or Selected Application. I Know it is possible. But how to work out it. My Sample UI is
http://answers.oreilly.com/index.php?app=core&module=attach&section=attach&attach_rel_module=post&attach_id=555
I am try to use some code. But all the codes can be used to close only for activities. Not Closed Application. May i tried to refer some stackoverflow answers. But i am not clearly understand anything. My code is

finish();
System.exit(0);
Intent i = new Intent();
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
startActivity(i);
android.os.Process.killProcess(android.os.Process.myPid());

Please reply your Answers and comments are valuable me. Thanks.

回答1:

I Know it is possible.

Not at your will though.

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

A note from the documentation about this method:

Note that, though this API allows us to request to kill any process based on its PID, the kernel will still impose standard restrictions on which PIDs you are actually able to kill. Typically this means only the process running the caller's packages/application and any additional processes created by that app; packages sharing a common UID will also be able to kill each other's processes.

About system.exit(0) , read this answer. And keep that in your mind.

And about finish(), the documentation clearly says the following:

"Call this when your activity is done and should be closed."

To sum it all up - don't try to make a task killer. The android OS takes care of that perfectly well. Don't meddle with it.

The wheel has been invented and is being used perfectly, don't reinvent it.

Please read this. You need to understand that Android doesn't require task killers. Google it and you will find many such articles.



回答2:

Use restart application instead of killProcess

ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
am.restartPackage("YOUR_PACKAGE_NAME");

restartPackage is the wrapper of killProcess method.

use below permission to use restartPackage method

<uses-permission android:name="android.permission.RESTART_PACKAGES" />