android开发中的“killprocess”

        最近在研究android中“清除其它进程”的方法,在这个过程中学到了android进程的概念以及如何“清除其它可以清除的进程”,请允许我用 “ 清除其它进程” 这样的字样来表达我的观点,因为这里的清除和在windows上KillProcess不太一样。学习知识要踏踏实实的不能人云亦云,对找到的方法不光要自己尝试更要仔细的去验证其真伪。清除进程,首先明白何谓进程,其次什么样的程序有这种权限来清除进程等等。下面我自己做一下这我学习的总结。

   我归纳一下网上盛传的android下killProcess的方法:

        一 .public static final void killProcess (int pid)

         很遗憾这种方法仅仅对当前进程或者有当前进程启动的进程有效,再就是有相同UID的进程

         参看:Android Process 

     public static final void killProcess (int pid)

Added in API level 1

Kill the process with the given PID. Note that, though this API allows us to request to kill any process based on its PID, the kernel will still impose standard restrictions on which PIDs you are actually able to kill. Typically this means only the process running the caller's packages/application and any additional processes created by that app; packages sharing a common UID will also be able to kill each other's processes.

二.public void killBackgroundProcesses (String packageName)

该方法解释为:

 public void killBackgroundProcesses (String packageName)

Added in API level 8

Have the system immediately kill all background processes associated with the given package. This is the same as the kernel killing those processes to reclaim memory; the system will take care of restarting these processes in the future as needed.

You must hold the permission KILL_BACKGROUND_PROCESSES to be able to call this method.

Parameters
packageName The name of the package whose processes are to be killed.


  这个方法的确能清除掉一些进程但是请注意这个可以清除的类型——Background。什么是后台进程呢?这就要说说进程的       importance hierarchy

  

There are five levels in the importance hierarchy. The following list presents the different types of processes in order of importance (the first process is most important and is killed last):

  1. Foreground process

    A process that is required for what the user is currently doing. A process is considered to be in the foreground if any of the following conditions are true:

    Generally, only a few foreground processes exist at any given time. They are killed only as a last resort—if memory is so low that they cannot all continue to run. Generally, at that point, the device has reached a memory paging state, so killing some foreground processes is required to keep the user interface responsive.

  2. Visible process

    A process that doesn't have any foreground components, but still can affect what the user sees on screen. A process is considered to be visible if either of the following conditions are true:

    • It hosts an Activity that is not in the foreground, but is still visible to the user (its onPause() method has been called). This might occur, for example, if the foreground activity started a dialog, which allows the previous activity to be seen behind it.
    • It hosts a Service that's bound to a visible (or foreground) activity.

    A visible process is considered extremely important and will not be killed unless doing so is required to keep all foreground processes running.

  3. Service process

    A process that is running a service that has been started with the startService() method and does not fall into either of the two higher categories. Although service processes are not directly tied to anything the user sees, they are generally doing things that the user cares about (such as playing music in the background or downloading data on the network), so the system keeps them running unless there's not enough memory to retain them along with all foreground and visible processes.

  4. Background process

    A process holding an activity that's not currently visible to the user (the activity's onStop() method has been called). These processes have no direct impact on the user experience, and the system can kill them at any time to reclaim memory for a foreground, visible, or service process. Usually there are many background processes running, so they are kept in an LRU (least recently used) list to ensure that the process with the activity that was most recently seen by the user is the last to be killed. If an activity implements its lifecycle methods correctly, and saves its current state, killing its process will not have a visible effect on the user experience, because when the user navigates back to the activity, the activity restores all of its visible state. See the Activities document for information about saving and restoring state.

  5. Empty process

    A process that doesn't hold any active application components. The only reason to keep this kind of process alive is for caching purposes, to improve startup time the next time a component needs to run in it. The system often kills these processes in order to balance overall system resources between process caches and the underlying kernel caches.

明白了什么是后台进程那么就可用该方法清除这类进程了,但是有些网友在stackoverflow或者其他地方说这个方法没有用,被清除的进程里有service就没法kill等等。这里我就要说弄清该函数的功能最重要!他清理的是Background process,如果一个进程中有正在运行的service那可不是background进程哦!

至于例子嘛 我建议可以运行http://developer.android.com/shareables/training/ActivityLifecycle.zip这个,启动该程序,kill该进程。就会很直观的看见效果。
核心代码如下:
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		Button btn = (Button)findViewById(R.id.btn_kill_process);
		btn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				ActivityManager activitymanager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
				
				List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activitymanager.getRunningAppProcesses();
				final String strTargetPackageName = "com.example.android.lifecycle";//""com.example.test.bekill.process";
				for(ActivityManager.RunningAppProcessInfo runningAppProcessInfo : runningAppProcesses)
				{					
					if(runningAppProcessInfo.processName.equals(strTargetPackageName))
					{
						/*
						 * IMPORTANCE_FOREGROUND, 
						 * IMPORTANCE_VISIBLE, 
						 * IMPORTANCE_SERVICE, 
						 * IMPORTANCE_BACKGROUND, 
						 * IMPORTANCE_EMPTY. 
						 * */
						switch(runningAppProcessInfo.importance)
						{
						case ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND:
							Log.d("[The Process is:]", "IMPORTANCE_FOREGROUND");
							break;
						case ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE:
							Log.d("[The Process is:]", "IMPORTANCE_VISIBLE");
							break;
						case ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE:
							Log.d("[The Process is:]", "IMPORTANCE_SERVICE");
							break;
						case ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND:
							Log.d("[The Process is:]", "IMPORTANCE_BACKGROUND");
							break;
						case ActivityManager.RunningAppProcessInfo.IMPORTANCE_EMPTY:
							Log.d("[The Process is:]", "IMPORTANCE_EMPTY");
							break;
						default:
							break;
						}
						activitymanager.killBackgroundProcesses(strTargetPackageName);
					}
				}
				//
			}
		});
		
		Intent intent = new Intent(MainActivity.this,NormalService.class);
		startService(intent);
	}

执行后会发现该process没有任何活动的应用程序组件。那么该进程就是 一个empty process.

三.forceStopPackage
号称唯一种能像系统自带的应用程序管理器一样结束进程的方法,但是这个函数虽然猛,但是对调用者有严格限制,不仅要求调用者的进程具有系统权限(在 /system/app 下),而且必需具有系统签名(用编译系统 rom 的签名进行编译)。否则调用报权限异常。所以第三方应用想通过反射、root 之类调用的就省省吧,目前官方系统只有系统的 Setting 里面的强制终止应用会调用这个函数。(请参看:http://mingming-killer.diandian.com/post/2014-05-15/40061757929)

说了这么多,提醒自己也提醒正在学习android的朋友们不要再以在windows上的某些思维来思考问题,在发一条博客连接供大家来学习:
http://yangguangfu.iteye.com/blog/1090138

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值