Android--Separation of system processes from user processes

Source: Internet
Author: User

Reprint Please specify source: http://blog.csdn.net/l1028386804/article/details/47282031

In the article "Android-Kill user-selected process optimization" in the previous blog post, I'll show you how to optimize the user experience, so in this post I'll show you how to detach the system process from the user process. Again, this blog post was improved based on the previous blog post. If you haven't read the previous blog post, please read the article "Android-Kill user-selected process optimization" in the previous blog post. OK, let's go straight to the subject.

First, the principle

It's the same thing, let's talk about the principle level first.

First of all, we are based on the current application is installed by users or systems, the application is divided into user applications and system applications, the user application of the corresponding process is the user process, the system application of the corresponding process is the system process. People can not help but say, this is not nonsense? Yes, that's the basic principle. Let's continue to say the UI display problem, first of all, give you a picture to illustrate, look at the picture:

, we want to achieve the effect as shown in the illustration on the left, first, the user process (the number of user processes) is displayed at the top of the ListView, then the following is the list information for the user process, and then the system process (number of system processes) is displayed below, followed by the system process list information. Of course, such a design would make the custom adapter class change slightly larger. Here, we may as well assume that the user process collection is Usertaskinfos, the system process collection is Systemtaskinfos, first, the data collection size returned in the custom adapter should be the user process collection size plus the system process collection size plus 2, That is Usertaskinfo.size () +systemtaskinfos.size () +2, do not understand the children's shoes please look at the picture carefully analyzed. In the first position of this listview, where position is 0, is a textview prompt user process (the number of user processes), the following from the location of the position to 1 to the user process size, always show the user process information, The specific process information returned by these locations is Usertaskinfo.get (position-1), and when position is usertaskinfo.size () +1, it is also a textview, prompting the system process (number of system processes), The following is a list of information about the system process, the specific process information returned by these locations, Systemtaskinfos.get (Position-usertaskinfo.size ()-2). That's the principle we're going to show on our interface. Please do not understand the children's shoes, carefully read a few times, if still do not understand, please leave a message below. I will respond to you when I see it.

II. implementation 1, update process information entity class TaskInfo

In this class, add a Boolean field isusertask that identifies whether the current process is a user process

The specific code is implemented as follows:

Is the user process private Boolean isusertask = False;public Boolean isusertask () {return isusertask;} public void Setusertask (Boolean isusertask) {this.isusertask = Isusertask;}

2, update Process tool class TASKUTILS1) New method to determine whether the user process

New method in this class to determine whether the current process is a user process, is to return true, not to return false

The specific code is implemented as follows:

Determine if the application is a user program public    static Boolean Filterapp (ApplicationInfo info) {    //original is a system application, the user manually upgrades        if ((info.flags & applicationinfo.flag_updated_system_app)! = 0) {            return true;            User-installed Applications        } else if ((Info.flags & applicationinfo.flag_system) = = 0) {            return true;        }        return false;    }

2) How to get a list of all process information in the system

In the loop of this method, we call the new method to determine whether the process is a user process, and then set the result of the decision to the Isusertask attribute of the entity class.

The specific code is as follows:

/** * Get a list of all process information for the system * @param context * @return */public static list<taskinfo> Gettaskinfos (context context) {list< taskinfo> TaskInfos = new arraylist<taskinfo> (); Packagemanager pm = Context.getpackagemanager (); Activitymanager am = (activitymanager) context.getsystemservice (Context.activity_service); list<runningappprocessinfo> runningappprocesses = am.getrunningappprocesses (); for (RunningAppProcessInfo info : runningappprocesses) {TaskInfo taskinfo = new TaskInfo ();//process name string packagename = Info.processname; Taskinfo.setpackagename (PackageName); try {applicationinfo applicationinfo = pm.getapplicationinfo (packageName, 0); /icon drawable Task_icon = Applicationinfo.loadicon (PM), if (Task_icon = = null) {Taskinfo.settask_icon ( Context.getresources (). getdrawable (R.drawable.ic_launcher));} Else{taskinfo.settask_icon (Task_icon);} Name string task_name = Applicationinfo.loadlabel (PM). toString (); Taskinfo.settask_name (task_name);// Determine if the user program is Boolean isusertask = Filterapp (applicationinfo);//Set whether the user program Taskinfo.setusertask (isusertask);} catch (Namenotfoundexception e) {//TODO auto-generated catch Blocke.printstacktrace (); Taskinfo.settask_icon ( Context.getresources (). getdrawable (R.drawable.ic_launcher)); Taskinfo.settask_name (PackageName);} Process Idint pid = info.pid;taskinfo.setpid (PID);//Gets the memory used by the process android.os.debug.memoryinfo[] Processmemoryinfo = Am.getprocessmemoryinfo (New Int[]{pid}); Android.os.Debug.MemoryInfo memoryinfo = Processmemoryinfo[0];long Totalprivatedirty = Memoryinfo.gettotalprivatedirty (); Kbtaskinfo.settask_memory (Totalprivatedirty); Taskinfos.add (TaskInfo);} return TaskInfos;}

3. Update TaskManagerActivity1) new attribute field

In this class, we first add two attribute fields to encapsulate all user processes and all system processes.

The specific code is as follows:

Private list<taskinfo> usertaskinfos;private list<taskinfo> Systemtaskinfos;

2) Update the collection on the OnCreate child thread

In OnCreate's sub-thread, we get all the process collections, and here I instantiate the Usertaskinfos and Systemtaskinfos collections, traverse the collection information obtained, and differentiate whether the user process is based on the Isusertask attribute in the process information To add data to the Usertaskinfos and Systemtaskinfos collections, and if it is a user process, add to the Usertaskinfos collection, if not the user process, to the Systemtaskinfos collection.

The specific code is as follows:

New Thread (New Runnable () {@Overridepublic void run () {TaskInfos = Taskutils.gettaskinfos (Getapplicationcontext ());// Separate user programs and system programs Usertaskinfos = new arraylist<taskinfo> (); Systemtaskinfos = new arraylist<taskinfo> (); for ( TaskInfo Taskinfo:taskinfos) {if (Taskinfo.isusertask ()) {Usertaskinfos.add (taskinfo);} Else{systemtaskinfos.add (TaskInfo);}} Send message mechanism msg = new Message (); msg.what = Success_gettaskinfo;mhandler.sendmessage (msg);}}). Start ();

4. Custom adapter Class Taskmanageradapter

The user process collection is Usertaskinfos, and the system process collection is Systemtaskinfos, first, the data collection size returned in the custom adapter should be the user process collection size plus the system process collection size plus 2, which is usertaskinfo.size ( ) +systemtaskinfos.size () +2, do not understand the child shoes please look at the picture carefully analyzed under. In the first position of this listview, where position is 0, is a textview prompt user process (the number of user processes), the following from the location of the position to 1 to the user process size, always show the user process information, The specific process information returned by these locations is Usertaskinfo.get (position-1), and when position is usertaskinfo.size () +1, it is also a textview, prompting the system process (number of system processes), The following is a list of information about the system process, the specific process information returned by these locations, Systemtaskinfos.get (Position-usertaskinfo.size ()-2). In order to block out the list of two TextView Click events, we have replicated the Baseadapter in the IsEnabled method, this method to pass a position parameter, its role is to determine whether the current position can be clicked, when returning True, you can click, When you return FALSE, you cannot click. At the same time, in order not to cache TextView I made a decision here to filter out the operation of the cache TextView.

The specific code is implemented as follows:

/** * Custom Adapter * @author Liuyazhuang * */private class Taskmanageradapter extends Baseadapter{private layoutinflater Minflat Er;private list<taskinfo> infos;public void Setinfos (list<taskinfo> infos) {This.infos = infos;} Public Taskmanageradapter () {minflater = Getlayoutinflater ();} @Overridepublic boolean isenabled (int position) {//TODO auto-generated method stubif (Position = = 0) {return false;} else if (position = = Usertaskinfos.size () + 1) {return false;} return super.isenabled (position);} @Overridepublic int GetCount () {//return infos.size (); return usertaskinfos.size () + systemtaskinfos.size () + 2;} @Overridepublic Object getItem (int position) {if (position = = 0) {return null;} else if (position <= usertaskinfos.size ()) {return usertaskinfos.get (position-1);} else if (position = = Usertaskinfos.size () + 1) {return null;} Else{return Systemtaskinfos.get (Position-usertaskinfos.size ()-2);} return Infos.get (position);} @Overridepublic long Getitemid (int position) {return position;} @OverrIdepublic view GetView (int position, view Convertview, ViewGroup parent) {view view = null; Viewholder holder = null;if (position = = 0) {//show user prompts TextView TV = new TextView (taskmanageractivity.this); Tv.settex T ("User process" + "(" + usertaskinfos.size () + ")"); tv.settextsize; Tv.setbackgroundcolor (Color.gray); return TV;} else if (position <= usertaskinfos.size ()) {//Displays a list of user processes if (Convertview! = NULL &&!) Convertview instanceof TextView) {view = Convertview;holder = (viewholder) View.gettag ();} Else{view = minflater.inflate (R.layout.task_manager_item, null); holder = new Viewholder (); holder.iv_task_manager_ icon = (ImageView) View.findviewbyid (r.id.iv_task_manager_icon); holder.iv_task_manager_name = (TextView) View.findviewbyid (r.id.tv_task_manager_name); holder.iv_task_manager_memory = (TextView) View.findviewbyid (R.id.tv _task_manager_memory);//gets to the CheckBox control on the UI holder.cb_task_manager_selected = (checkbox) View.findviewbyid (r.id.cb_ task_manager_selected); View.settag (holder);} TaskInfo TASkinfo = Usertaskinfos.get (position-1); Holder.iv_task_manager_icon.setImageDrawable (Taskinfo.gettask_icon ()); Holder.iv_task_manager_memory.setText ("Occupied Memory:" +textformat.formatbyte (Taskinfo.gettask_memory () *1024)); Holder.iv_task_manager_name.setText (Taskinfo.gettask_name ()); String PackageName = Taskinfo.getpackagename ();//The application is the currently running program if (Packagename.equals (Getpackagename ())) {Holder.cb_ Task_manager_selected.setvisibility (View.gone);} Else{holder.cb_task_manager_selected.setvisibility (view.visible);} Gets the selected state of the entry, Boolean isChecked = taskinfo.ischecked (), if (isChecked) {holder.cb_task_manager_selected.setChecked (True );} Else{holder.cb_task_manager_selected.setchecked (false);} return view;} else if (position = = Usertaskinfos.size () + 1) {//Display system process hint TextView TV = new TextView (taskmanageractivity.this); tv.settext ("System Process" + "(" + systemtaskinfos.size () + ")"); tv.settextsize; Tv.setbackgroundcolor (Color.gray); return TV;} ELSE{//Displays the system process list if (Convertview! = NULL &&! Convertview instanceof TextView)) {View = Convertview;holder = (viewholder) View.gettag ();} Else{view = minflater.inflate (R.layout.task_manager_item, null); holder = new Viewholder (); holder.iv_task_manager_ icon = (ImageView) View.findviewbyid (r.id.iv_task_manager_icon); holder.iv_task_manager_name = (TextView) View.findviewbyid (r.id.tv_task_manager_name); holder.iv_task_manager_memory = (TextView) View.findviewbyid (R.id.tv _task_manager_memory);//gets to the CheckBox control on the UI holder.cb_task_manager_selected = (checkbox) View.findviewbyid (r.id.cb_ task_manager_selected); View.settag (holder);} TaskInfo TaskInfo = Systemtaskinfos.get (Position-usertaskinfos.size ()-2); Holder.iv_task_manager_ Icon.setimagedrawable (Taskinfo.gettask_icon ()); Holder.iv_task_manager_memory.setText ("Memory occupied:" + Textformat.formatbyte (Taskinfo.gettask_memory () *1024)); Holder.iv_task_manager_name.setText (taskinfo.gettask_ Name ()); String PackageName = Taskinfo.getpackagename ();//The application is the currently running program if (Packagename.equals (Getpackagename ())) {Holder.cb_ Task_manager_selected.setvisibility(View.gone);} Else{holder.cb_task_manager_selected.setvisibility (view.visible);} Gets the selected state of the entry, Boolean isChecked = taskinfo.ischecked (), if (isChecked) {holder.cb_task_manager_selected.setChecked (True );} Else{holder.cb_task_manager_selected.setchecked (false);} return view;}}}
Code is a bit long, please be patient to read, in fact, a lot of code is the same, I do not do code refactoring operation here, interested in children's shoes can be their own try Oh, come on!!

5. Update "One-click cleanup" click events

This method now operates on two sets of Usertaskinfos and Systemtaskinfos, and my logic here is primarily to create a collection Killtaskinfos represents the collection of processes to kill, traversing two sets, respectively, Determines whether the process within the collection is selected, and if selected, calls Activitymanager's Killbackgroundprocesses method to kill the process while adding the killed process to the Killtaskinfos collection. Finally, write a loop traversal Killtaskinfos, respectively, to determine the Isusertask property of the process information, if true to remove it from the Usertaskinfos, if False, it is removed from the Systemtaskinfos, Call the ListView notifydatasetchanged () method to update the UI.

The specific code is implemented as follows:

/** * Kill process * @param v */public void kill_process (View v) {//store killed process information list<taskinfo> Killtaskinfos = new arraylist< Taskinfo> (); for (TaskInfo Taskinfo:usertaskinfos) {if (taskinfo.ischecked ()) {// Kills the selected process am.killbackgroundprocesses (Taskinfo.getpackagename ()); Killtaskinfos.add (TaskInfo);}} for (TaskInfo Taskinfo:systemtaskinfos) {if (taskinfo.ischecked ()) {//kills the selected process am.killbackgroundprocesses ( Taskinfo.getpackagename ()); Killtaskinfos.add (TaskInfo);}} Remove the killed process for (TaskInfo Taskinfo:killtaskinfos) {if (Taskinfo.isusertask ()) {usertaskinfos.remove (taskinfo);} Else{systemtaskinfos.remove (TaskInfo);}} Madapter.notifydatasetchanged ();}

Third, the Operation effect

Four, warm tips

In this example, for the sake of the aspect, I write some text directly in the layout file and the related class, Everyone in the real project to write these words in the String.xml file, in the external reference to these resources, remember, this is the most basic development knowledge and specifications as an Android programmer, I am here just to facilitate directly written in the class and layout files.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android--Separation of system processes from user processes

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.