Android获取进程是否在后台注意事项

当我们需要判断进程是否在后台运行时,需要用ActivityManager的getRunningAppProcesses方法获得正在运行的进程列表,然后跟本进程名称比对,来判断进程信息。

实际使用中发现,当你在主进程中判断时,获得进程信息始终是IMPORTANCE_FOREGROUND,就是说始终标识你的进程在前台运行,不管你按了HOME键还是返回键,让人郁闷不解。

后再stackoverflow论坛中找到解决方法,就是将判断过程放到异步中,不要放到主进程中,所以方法如下:

	 private class ProcessTask extends AsyncTask {
		 IProcessCheckFinishedListener processCheckFinishedListener;
		 
	        public void setProcessCheckFinishedListener(
				IProcessCheckFinishedListener processCheckFinishedListener) {
			this.processCheckFinishedListener = processCheckFinishedListener;
		}
			@Override
	        protected Boolean doInBackground(String... strings) {
	            
	        	ActivityManager activityManager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
	    	    List appProcesses = activityManager.getRunningAppProcesses();
	    	    for (RunningAppProcessInfo appProcess : appProcesses) {
	    	         if (appProcess.processName.equals(activity.getPackageName())) {
	    	        	 if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_VISIBLE ||
	 	                		appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
	    	                          
	    	                          return false;
	    	                }else{
	    	                          
	    	                          return true;
	    	                }
	    	           }
	    	    }
	    	    return false;
	        }
	        @Override
	        protected void onPostExecute(Boolean result) {
	        	if (processCheckFinishedListener != null){
	        		processCheckFinishedListener.OnProcessCheckFinished(result);
	        	}
	        }
	    }

使用

		ProcessTask task = new ProcessTask();
		task.setProcessCheckFinishedListener(new IProcessCheckFinishedListener() {
			
			@Override
			public void OnProcessCheckFinished(Boolean result) {
				// TODO Auto-generated method stub
				这里根据result返回结果做处理
			}
		});
		task.execute("");


你可能感兴趣的:(Android)