安卓杀掉后台多余进程

有客户说后台服务进程太多导致系统会卡顿,本来芯片处理能力有限,所以想把后台多的不重要的进程杀掉,以下代码通过添加进程白名单的方式把其余的进程杀掉,在服务中通过一个handler5秒检测一次:

import android.app.ActivityManager;
import android.app.Service;
import java.util.List;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.usage.UsageStatsManager;
import android.app.usage.UsageStats;
import android.content.pm.ApplicationInfo;
import com.android.server.wm.ActivityTaskManagerService;

import static android.app.ActivityManager.RunningAppProcessInfo;
		 private void  kill_other_processapp(){
			   ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
			   List<RunningTaskInfo> tasks = am.getRunningTasks(1);			  
               boolean kill_flag =true;
			   if (!tasks.isEmpty()) {
				   for (RunningAppProcessInfo runningAppProcessInfo : am.getRunningAppProcesses()) {
						String processname = runningAppProcessInfo.processName;

						if(runningAppProcessInfo.importance ==ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND)
						{
							processname = runningAppProcessInfo.processName;
                            Log.i("fan", "importance app is : " + processname);
							continue;
							//Log.i("fan", "clean background apps top : " + packagename);
						}
					  // ComponentName topActivity = tasks.get(0).topActivity;
					   Log.i("fan","processname ="+processname);
					   String[] itemString={""};
					   String default_permission_app=SystemProperties.get("persist.sys.default_permission_app");
					   if(default_permission_app!=null){
						   itemString = default_permission_app.split(",");
					   }	   
					   for (int i = 0; i < itemString.length; i++)
					   {
						   Log.d("fan", "default_permission_app="+itemString[i]);
						   if(processname.equals(itemString[i]))
						   {  
							   Log.i("fan","found goal appname");
                               kill_flag =false;
							   break;
						   }				
					   }
					   if(kill_flag){
					   		am.forceStopPackage(processname);
					   		Log.i("fan","kill appname ="+processname);
					   }
					   
			   }
		   }
		 }

 Handler apphandler=new Handler();

 private final Runnable main_runnable=new Runnable(){    
 @Override    
   public void run() {
       Log.i("fan","kill app handler running ");
       kill_other_processapp();
       apphandler.postDelayed(main_runnable, 1000*5);
   }
 };

你可能感兴趣的:(android)