Close the current program for Android programming

Source: Internet
Author: User

Currently, the most common method to disable Android is finish (). If it is written normally, no problem occurs. However, in some unconventional cases, you need to disable the current application.

Close the program in this way before 2.2, that is, before the API-8:
ActivityManager manager = (ActivityManager) getSystemService (ACTIVITY_SERVICE );
Manager. restartPackage (getPackageName (); (the name is a real publisher. Why is it called restart ?! -_-#)
Permission to be declared <uses-permission android: name = "android. permission. RESTART_PACKAGES"/>
This method terminates all processes associated with the package, all processes that share the same uid are killed, and all activities are removed.
All created services will be stopped, and a broadcast Intent. ACTION_PACKAGE_RESTARTED will be sent, so that all registered alarms will be stopped, and notifications will be removed.


After 2.2, we will use the new method:
ActivityManager manager = (ActivityManager) getSystemService (ACTIVITY_SERVICE );
Manager. killBackgroundProcesses (getPackageName ());
Permission to be declared <uses-permission android: name = "android. permission. KILL_BACKGROUND_PROCESSES"/>
This is the same as the above.

 

So next, I will write a complete method to close it for your use:
[Java]
/**
* Exit the program completely. You need to add permissions!
* <Uses-permission android: name = "android. permission. RESTART_PACKAGES"/>
* <Uses-permission android: name = "android. permission. KILL_BACKGROUND_PROCESSES"/>
*/
Protected void exitProgram (){
Finish ();
ActivityManager activityManager = (ActivityManager) getSystemService (ACTIVITY_SERVICE );
Int sdk = Integer. valueOf (Build. VERSION. SDK). intValue ();
If (sdk <8 ){
ActivityManager. restartPackage (getPackageName ());
} Else {
ActivityManager. killBackgroundProcesses (getPackageName ());
}
System. exit (0 );
}


Prepared by xyz_fly

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.