Android Base "1" method to kill the process (Force stop) application

Source: Internet
Author: User

written in front: into the mobile phone ODM has been a long time, experienced several project projects down, on Qualcomm, Spreadtrum, Marvell Platform has been contacted, for me personally, participate in mobile phone system project development and maintenance, the most obvious advantage is that you can deeply understand the specific implementation of a function of the process, As well as the Android design framework, can be the framework of thinking to modify the code to add functionality.        For so long, more and more feel the need to see themselves in the actual work process, some of the things learned can be remembered and shared. From this beginning I will filter out some common features in the Google source code standard method with everyone to share, for me personally, prefer to follow the source code has already existed standard method to coding. The first thing to share is to kill the process of the method, general mobile Phone Butler class application Most basic is the function of the cleanup process. In fact, this function in the source code to see is very simple, there are two main steps:1. Get a list of running processes; 2choose how to kill according to PackageName. 2015.05.06update a method that uses the reflection mechanism to invoke activitymanagerservice::forcestoppackage to kill the process (for USR groups, but still not necessarily successful). This part of the function mainly refers to the1. Settings-application-running-Stop All Processes2. Any interface--long press home--the practice of getting the application used in the cleanup of recent process settings: mainly using Packagemanager::getinstalledapplications (intflags) {} method [Java] View plaincopyFinal intMretrieveflags; List<ApplicationInfo> mapplications =NewArraylist<applicationinfo>(); //Only the owner can see all apps.         if(Userhandle.myuserid () = = 0) {Mretrieveflags= Packagemanager.get_uninstalled_packages |packagemanager.get_disabled_components|packagemanager.get_disabled_until_used_components; } Else{mretrieveflags= Packagemanager.get_disabled_components |packagemanager.get_disabled_until_used_components; }          //get all packages in the system<strong>mapplications = Mpm.getinstalledapplications (mretrieveflags);</strong>if(Mapplications = =NULL) {mapplications=NewArraylist<applicationinfo>(); }             for(inti=0; I<mapplications.size (); i++) {              FinalApplicationInfo info =Mapplications.get (i); //need to trim off any applications that is disabled by//something different than the user.             if(!info.enabled) {//it is necessary here to obtain a package that is not prohibited and allowed to be manipulated                if(Info.enabledsetting! =Packagemanager.component_enabled_state_disabled_user)                      {Mapplications.remove (i); I--; Continue; } Mhavedisabledapps=true; }} The standard method gets the running process: primarily using the activitymanagerservice::getrunningappprocesses () {} method [Java] View plaincopy//temporary structure used when updating above information. FinalSparsearray<appprocessinfo> mtmpappprocesses =NewSparsearray<appprocessinfo>(); //Retrieve List of running processes, organizing them into a sparse//array for easy retrieval. List<activitymanager.runningappprocessinfo>Processes= Am.getrunningappprocesses ();//get a running process    Final intNP = processes! =NULL? Processes.size (): 0;      Mtmpappprocesses.clear ();  for(inti=0; i<np; i++) {activitymanager.runningappprocessinfo pi=Processes.get (i); Mtmpappprocesses.put (Pi.pid,Newappprocessinfo (pi)); How to kill a running process: for API level<= 7permissions Android.permission.restart_package[java] View plaincopyPrivate voidkillpackage (String pkgname) {Activitymanager am=(Activitymanager) getactivity (). Getsystemservice (Context.activity_service);    Am.restartpackage (Pkgname); } for API level>=8permissions Android.permission.kill_backgorund_processes[java] View plaincopyPrivate voidkillpackage (String pkgname) {Activitymanager am=(Activitymanager) getactivity (). Getsystemservice (Context.activity_service);    Am.killbackgroundprocesses (Pkgname); } Settings--application--detail--Force stop: For non-system group processes, you cannot call the Activitymanager::forcestoppackage (String) {} method, only try using Activitymanagerservice:: Forcestoppackage (FinalString PackageName,intuserId) and does not necessarily succeed, the logic in the setup is roughly as follows: [Java] View plaincopyPrivateDevicepolicymanager MDPM =(Devicepolicymanager) getactivity (). Getsystemservice (Context.device_policy_service); Private FinalBroadcastreceiver Mcheckkillprocessesreceiver =NewBroadcastreceiver () {@Override Public voidOnReceive (Context context, Intent Intent) {Updateforcestopbutton (Getresultcode ()!=activity.result_canceled);    }  }; Private voidUpdateforcestopbutton (Booleanenabled)      {mforcestopbutton.setenabled (enabled); Mforcestopbutton.setonclicklistener (installedappdetails. This); }    Private voidCheckforcestop () {if(Mdpm.packagehasactiveadmins (mpackageinfo.packagename)) {//User can ' t force stop device Admin. Updateforcestopbutton (false); } Else if((mappentry.info.flags&applicationinfo.flag_stopped) = = 0) {          //If the app isn ' t explicitly stopped, then always show the//Force stop button. Updateforcestopbutton (true); } Else{Intent Intent=NewIntent (Intent.action_query_package_restart, Uri.fromparts ("Package", MAppEntry.info.packageName,NULL)); Intent.putextra (Intent.extra_packages,Newstring[] {mAppEntry.info.packageName});          Intent.putextra (Intent.extra_uid, MAppEntry.info.uid);          Intent.putextra (Intent.extra_user_handle, Userhandle.getuserid (MAppEntry.info.uid)); Getactivity (). Sendorderedbroadcastasuser (Intent, userhandle.current,NULL, Mcheckkillprocessesreceiver,NULL, activity.result_canceled,NULL,NULL); }} [Java] view plaincopyPrivate voidforcestoppackage (String pkgname) {Activitymanager am=(Activitymanager) getactivity (). Getsystemservice (Context.activity_service); Am.forcestoppackage (Pkgname); //Not necessarily successfulMstate.invalidatepackage (Pkgname);//re-fetch the package information after forcing stopApplicationsstate.appentry Newent =mstate.getentry (pkgname); if(Newent! =NULL) {Mappentry=Newent; } checkforcestop (); //final Check whether the strong stop is successful (reflected in whether the "Force stop" button is grayed out)During debugging, the method of forcing a process to stop is: ADB shell am Force-stop < Package>For example: AM force-Stop com.android.launcher additional AM kill< Package>kill the process in safe mode without affecting the experience attached: AM force-stop:force stop everything associated with <PACKAGE>. --user <USER_ID> | All |current:specify user to force stop; All UsersifNot specified.am Kill:kill all processes associated with<PACKAGE>.  Only kills. Processes that is safe to kill--that is, would not impact the user experience. --user <USER_ID> | All |current:specify user whose processes to kill; All UsersifNot specified.am kill-All:kill all background processes. Third method: Kill process by reflection mechanism [Java] View plaincopy Packagecom.example.androidtest; ImportAndroid.app.ActivityManager; ImportAndroid.content.Context; Importjava.lang.reflect.InvocationTargetException; ImportJava.lang.reflect.Method; /*** Force the kill process through the reflection mechanism of Java *@authorHanhao **/   Public classforcekillprogress { Public Static voidforcestopprogress (Context context, String Pkgname) {Activitymanager am=(Activitymanager) Context.getsystemservice (Context.activity_service); Try{Method Forcestoppackage= Am.getclass (). Getdeclaredmethod ("Forcestoppackage", String.class); Forcestoppackage.setaccessible (true);          Forcestoppackage.invoke (AM, pkgname); } Catch(nosuchmethodexception e) {e.printstacktrace (); } Catch(illegalaccessexception e) {e.printstacktrace (); } Catch(IllegalArgumentException e) {e.printstacktrace (); } Catch(InvocationTargetException e) {e.printstacktrace (); }      }  } 

Android Base "1" method to kill the process (Force stop) application

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.