Introduction
Android OS is a multitasking operating system, there are a lot of running background process, these process make your device slower. Android SDK provides a set of API that allow a developer to list all background processes and kill (stop) them. In this post, we will discuss about how to list and kill background process in Android device.
Background
Known android App GUI and thread
Code
We need two permissions - KILL_BACKGROUND_PROCESSES
and GET_TASKS
.
Declare two permission as:
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />
<uses-permission android:name="android.permission.GET_TASKS" />
Declare 2 variables:
List<ActivityManager.RunningAppProcessInfo> processes;
ActivityManager amg;
Register service with Android to get all running processes:
amg = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
processes = amg.getRunningAppProcesses();
Create MyAdapter
class extends BaseAdapter
class to populate process's information on ListView
as:
public class MyAdapter extends BaseAdapter {
List<ActivityManager.RunningAppProcessInfo> processes;
Context context;
public MyAdapter(List<ActivityManager.RunningAppProcessInfo>
processes, Context context) {
this.context = context;
this.processes = processes;
}
@Override
public int getCount() {
return processes.size();
}
@Override
public Object getItem(int position) {
return processes.get(position);
}
@Override
public long getItemId(int position) {
return processes.get(position).pid;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Process pro;
if(convertView == null)
{
convertView = new TextView(context);
pro = new Process();
pro.name = (TextView)convertView;
convertView.setTag(pro);
}else
{
pro = (Process)convertView.getTag();
}
pro.name.setText(processes.get(position).processName);
return convertView;
}
class Process
{
public TextView name;
}
}
Display list of process on listview, display name only (just demo).
adp = new MyAdapter(processes, MainActivity.this);
lst.setAdapter(adp);
When user longclicks on process name, this process will be killed:
lst.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?>
parent, View view, int position, long id) {
if (load == 1) {
for (ActivityManager.RunningAppProcessInfo info : processes) {
if (info.processName.equalsIgnoreCase(
((ActivityManager.RunningAppProcessInfo)parent.getItemAtPosition
(position)).processName)) {
android.os.Process.killProcess(info.pid);
android.os.Process.sendSignal(info.pid, android.os.Process.SIGNAL_KILL);
amg.killBackgroundProcesses(info.processName);
}
}
load = 0;
skill_Load_Process();
}
return true;
}
});
You can only kill user process, with system process you need a rooted device.
Points of Interest
This is a very simple tip for killing running background processes on Android.
History