[Android]应用的前后台运行

            在开发中,你是不是没有抽象一个出常用的类,那你可能要为你的懒惰付出很大的代价。要时刻记得自己的工具箱,不断往里面添加一些小小玩意。今天就给大家带来一个很有意思的例子。前后台运行!!

            在Android开发中为了使用的方便要把所有的Activity包裹一层形成自己的activity,比如这个activity在创建时加入到一个容器里,在ondestroy时及时清除,可以通过Application管理activity,这个是今天我要介绍的项目背景。

            好了,我就直接开始切入题目。

           前台,就是当前显示运行的是自己的App;后台,就是自己的App不是激活或者说项目的Activity不在activity堆栈的最顶端。那如何判断呢?

           我们离开自己的app可能是通过按键或顶端的提示,亦或者是中途的电话打断,总而言之,就是Activity不是出于运行的状态,所以我们的目标就是监听所有的Activity的状态!!咋一听吓死了,我的项目有好多Activity呢?别忘了我开始说的 我把每个Activity继承于自己的Activity啦,所以实际上我只需要监听一个啦。

            好啦,贴代码:

package com.chaoxing.core;

import java.util.List;

import roboguice.activity.RoboActivity;
import android.app.ActivityManager;
import android.app.KeyguardManager;
import android.app.ActivityManager.RunningAppProcessInfo;


public class DefaultActivity extends Activity{	
	
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
	
		appRunningInBackground = AppRunningInBackground.getInstance(getApplicationContext());
		appRunningInBackground.onCreate();
	}

	
	@Override
	protected void onStart() {
		super.onStart();
		appRunningInBackground.onStart();
	}
	@Override
	protected void onStop() {
		super.onStop();
		appRunningInBackground.onStop();
	}

	private AppRunningInBackground appRunningInBackground ;
	
	
	
}

 

fragmentActivity也是同理。

import java.util.List;



public class AppRunningInBackground {
	
	public static boolean notifyShowing = false;
	public static boolean isSpecialSystem=false;
	private boolean isInstance = false;
	ActivityManager activityManager;
	KeyguardManager keyguardManager;
	private Context context = null;
	private static AppRunningInBackground appRunningInBackground = null;
	public static AppRunningInBackground getInstance(Context context){
		synchronized (AppRunningInBackground.class) {
			if(appRunningInBackground == null){
				appRunningInBackground = new AppRunningInBackground(context);
			}
			
			return appRunningInBackground;
		}
		
	}
	
	public AppRunningInBackground(Context context) {
		this.context = context;
	}
	public void onCreate() {
		if(!isInstance){
			activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);  
			keyguardManager = (KeyguardManager)context.getSystemService(Context.KEYGUARD_SERVICE);
			isInstance = true;
		}
		
    }     
	
	public void onStart() {
		if(notifyShowing && appRunningInBackground != null){
			notifyShowing = false;
			Intent  startIntent = new Intent(AppGlobalConfig.STARTACTIVITY); 
			context.sendBroadcast(startIntent);
		}
	}
	
	public void onStop() {
		if(appRunningInBackground != null && !isAppOnForeground() ){
			notifyShowing = true;
			Intent  startIntent = new Intent(AppGlobalConfig.STOPACTIVITY); 
			context.sendBroadcast(startIntent);
		}
	}
    

	/**
	 * 判断程序是否在前台
	 * @return true 在前台; false 在后台
	 */
	private boolean isAppOnForeground() {   
		if(!isSpecialSystem){
			boolean isspecial=true;
			String packageName = context.getPackageName();
	        List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();   
	        if (appProcesses == null) 
	        	return false;   
	        for (RunningAppProcessInfo appProcess : appProcesses) {   
	            if (appProcess.processName.equals(packageName)) {
	            	if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND||appProcess.importance == RunningAppProcessInfo.IMPORTANCE_VISIBLE) {   
	            		return true;   
	            	}
	            	if (keyguardManager.inKeyguardRestrictedInputMode()) return true;
	            }  
	            if(isspecial){
	            	if(appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
	            		isspecial=false;
		            }
	            }
	        }
	        if(isspecial){
	        	isSpecialSystem=true;
	        	return !isApplicationBroughtToBackgroundByTask();
	        }
	        return false;   
		}else{
			return !isApplicationBroughtToBackgroundByTask();
		}
    }   
	
    /**
     * 判断当前应用程序是否处于后台,通过getRunningTasks的方式
     * @return true 在后台; false 在前台
     */
    public  boolean isApplicationBroughtToBackgroundByTask() {
        List<RunningTaskInfo> tasks = activityManager.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }
}

posted @ 2013-11-21 20:26  Cyning  阅读(757)  评论(0编辑  收藏  举报