Android-kills the selected process (frees up the space occupied by the process)

Source: Internet
Author: User

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

This article is based on the previous article "Android-get process, memory, Task List" perfect, you can first read the previous blog "Android-get process, memory, Task List" to be aware of. In this article I mainly introduce how to kill the process that we have selected in the list and free up the space occupied by the process. Well, no more nonsense, let's go straight to the subject.

First, the principle

The usual, or the first nagging about this principle level of the East Bar.

Based on the previous article, in this post, we add a checkbox for each entry in the ListView, and we add a property for each process information we get to identify whether it is the selected state. For the sake of convenience, I am here to create two context menu, one is the full select function, when clicked on this menu, the list in addition to the current application of the process of all the process information, marked as selected, one is "deselect button", when clicked on this button, the selection of all the application process is canceled. Clicking the "one button Cleanup button" at the bottom of the UI kills the selected application process and frees up the resources that the process consumes.

The principle of nagging over, is not very simple? Let's do it together!

Second, the realization

These features are not difficult to achieve, based on the previous blog "Android-get process, memory, Task List" perfect, if you have not read the previous blog post, please read the previous post, so as to fully understand the content of this blog post.

1, Update taskutils class

In this class, we are mainly updating the method of obtaining all the process information list of the system Gettaskinfos (), in the previous blog post, there is a problem is that the Android system is written by C or C + + when it is writing, it may not have icons and names, This information is not displayed in the list, so the user experience is not very good, all I have in this method's exception capture code block, for such an application set the default icon and name.

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);} 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;}

2. Update the entity class TaskInfo

In this class, I add a Boolean field that identifies whether the current application is selected.

The specific code is as follows:

Check state private Boolean isChecked = False;public Boolean isChecked () {return isChecked;} public void setchecked (Boolean isChecked) {this.ischecked = isChecked;}

3. Update Task_manager_item.xml

This file is the ListView Display Item entry information, and I have added a CheckBox button in this file, so that the UI can see directly whether the current application is selected, so it can be seen at a glance.

Note: The checkbox grabs the screen focus and click events, and when we click the ListView entry, we cannot change the checkbox's selected state, all of which I have added two properties to this control:

        Android:focusable= "false"        android:clickable= "false"
This will solve the problem.

The specific code is as follows:

    <!--new CheckBox control--><checkbox     android:id= "@+id/cb_task_manager_selected"    android:layout_width= "Wrap_content"        android:layout_height= "wrap_content"        android:layout_centervertical= "true"        Android: Focusable= "false"        android:clickable= "false"        android:layout_alignparentright= "true"/>

4. Update Task_manager.xml

This file is mainly to display the process information of the main interface, in this interface, our main change is to adjust the display process information list height, the following two buttons, one is "one-click Cleanup", one is "program settings", here we only "one click Cleanup" for event processing, "program settings" next post will be covered, Please look forward to it.

The specific code is as follows:

1) changes to the Framelayout

<framelayout        android:layout_width= "fill_parent"        android:layout_height= "0dip"        android:layout_ weight= "1" >

2) New button at bottom

<linearlayout         android:layout_width= "match_parent"        android:layout_height= "Wrap_content"        android: gravity= "center"        android:orientation= "Horizontal" >                <button             android:layout_width= "Wrap_ Content "            android:layout_height=" wrap_content "            android:onclick=" kill_process "            android:text=" one-click Cleanup "/ >                <button             android:layout_width= "wrap_content"            android:layout_height= "Wrap_content            " android:text= "program Settings"/>    </LinearLayout>

5. Update Taskmanageractivity

It can be said that this class is the main interface of our program, and in this class, I add an attribute field Activitymanager, which calls the method that kills the background process, adds two constants, identifies the ID of the context menu Added the checkbox information to the custom adapter class Taskmanageradapter, and created a context menu, one for "Select All", one for "deselect", each to handle their click events, an entry click event for the ListView, and finally, a rewrite of the " One-click cleanup button for clicking Events.

1) New fields

private static final int all_selected_id = 1;private static final int cancel_selected_id = 2;private Activitymanager am;

2) Added ListView entry Click event

This is our new feature, here, I have customized a class to implement the Onitemclicklistener interface, overriding the Onitemclick method, the specific logic is: when the original state of the application is selected, we set the application's state to unchecked, The checkbox is also set to unchecked, and when the application's original state is unchecked, we set the application's state to checked and the checkbox to checked.

The specific implementation code is as follows:

ListView Entry Click event Private class Myonitemclicklistener implements onitemclicklistener{@Overridepublic void Onitemclick ( Adapterview<?> Parent, view view, int Position,long id) {LOG.I ("I", "position ======" +position); CheckBox checkbox = ((Viewholder) View.gettag ()). cb_task_manager_selected; TaskInfo TaskInfo = (taskinfo) madapter.getitem (position);//If it is a self-application, do not perform the following operation directly if (Taskinfo.getpackagename (). Equals (Getpackagename ())) {return;} if (taskinfo.ischecked ()) {taskinfo.setchecked (false); checkbox.setchecked (false);} Else{taskinfo.setchecked (True); checkbox.setchecked (True);}}}
After that, we click events in the OnCreate () method for the ListView register entry.

The specific code is as follows:

Set Entry Click event Lv_taskmanage.setonitemclicklistener (New Myonitemclicklistener ());

3) Update the custom adapter and Viewholder

I've added a checkbox here, and it's important to note that no matter how it's chosen, the current application cannot be selected, or the current application's process will be killed. So, I made a judgment here, if one of the processes in the column process list is the current application's process, the checkbox is set to an invisible state so that the current application's process cannot be selected.

The specific code is as follows:

(1) GetView Method for custom adapters

@Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {view view = null; Viewholder holder = null;if (Convertview! = null) {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); <span style= "color: #FF0000;" >//gets the CheckBox control on the UI holder.cb_task_manager_selected = (checkbox) View.findviewbyid (r.id.cb_task_manager_ selected); </span>view.settag (holder);} TaskInfo TaskInfo = taskinfos.get (position); 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;}
(2) Update Viewholder
/** * Viewholder * @author Liuyazhuang * */static class Viewholder{imageview Iv_task_manager_icon; TextView Iv_task_manager_name; TextView iv_task_manager_memory;//New CheckBox property checkbox cb_task_manager_selected;}

4) New Create context menu method

This method is a callback method that comes with the Android system, and we just need to override this method to

The specific code is as follows:

Create callback for context menu @overridepublic boolean oncreateoptionsmenu (Menu menu) {//TODO auto-generated method Stubmenu.add (0, All_ selected_id, 0, "Select All"), Menu.add (0, cancel_selected_id, 0, "deselect"), return Super.oncreateoptionsmenu (menu);

5) New custom menu click event

This method is also a callback method that comes with the Android system, and we just need to rewrite this method. When we click on the "Select All" menu, all processes except the current application are labeled as checked, and when we click the "Deselect" button, the selected state of all processes is canceled and the ListView update list is notified.

The specific code is as follows:

Context Menu Click event @overridepublic boolean onoptionsitemselected (MenuItem Item) {//TODO auto-generated method Stubint id = Item . Getitemid (); switch (ID) {Case all_selected_id://sets each entry to the selected state for (TaskInfo Taskinfo:taskinfos) {//does not modify the state of its own application if (! Taskinfo.getpackagename (). Equals (Getpackagename ())) {taskinfo.setchecked (true);}} Refresh list madapter.notifydatasetchanged (); break;case cancel_selected_id://set each list to unchecked status for (TaskInfo TaskInfo: TaskInfos) {taskinfo.setchecked (false);} Refresh list madapter.notifydatasetchanged (); break;default:break;} return super.onoptionsitemselected (item);}

6) Click event to implement the "one button cleanup" button

The simple approach is to traverse all the process collections, kill the selected process, and release the resources that the process consumes.

The specific code is implemented as follows:

/** * Kill process * @param v */public void kill_process (View v) {for (TaskInfo Taskinfo:taskinfos) {if (taskinfo.ischecked ()) {//Kill Select The process in Am.killbackgroundprocesses (Taskinfo.getpackagename ());}}}

6. Registration rights

Killing an application requires permission, and we need to configure the appropriate permissions in Androidmanifest.xml.

The specific permissions to configure are as follows:

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

Third, the Operation effect

1. Program Running interface

2. Select a process in an entry

3. Uncheck the process in an item

4. Context Menu

5. Select All

6. Cancel All Selection

7. Select SMS app to clean up

8. Cleaning results

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-kills the selected process (frees up the space occupied by the process)

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.