Android监听程序进入后台,或者恢复到前台

转载于:https://blog.csdn.net/gouguofei/article/details/7775752

基本思路:
就是让app中所有的activity继承与一个公共的activity(例如:BaseActivity),然后在BaseActivity的onStop()中判断当前程序是否处于后台



  1. public class BaseActivity extends Activity {  
  2.         @Override  
  3.         protected void onStop() {  
  4.                 // TODO Auto-generated method stub  
  5.                 super.onStop();  
  6.    
  7.                 if (!isAppOnForeground()) {  
  8.                         //app 进入后台  
  9.                            
  10.                         //全局变量isActive = false 记录当前已经进入后台  
  11.                 }  
  12.         }  
  13.    
  14.         @Override  
  15.         protected void onResume() {  
  16.                 // TODO Auto-generated method stub  
  17.                 super.onResume();  
  18.    
  19.                    
  20.                 //if (!isActive) {  
  21.                         //app 从后台唤醒,进入前台  
  22.                            
  23.                         //isActive = true;  
  24.                 //}  
  25.         }  
  26.    
  27.         /** 
  28.          * 程序是否在前台运行 
  29.          *  
  30.          * @return 
  31.          */  
  32.         public boolean isAppOnForeground() {  
  33.                 // Returns a list of application processes that are running on the  
  34.                 // device  
  35.                    
  36.                 ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);  
  37.                 String packageName = getApplicationContext().getPackageName();  
  38.    
  39.                 List<RunningAppProcessInfo> appProcesses = activityManager  
  40.                                 .getRunningAppProcesses();  
  41.                 if (appProcesses == null)  
  42.                         return false;  
  43.    
  44.                 for (RunningAppProcessInfo appProcess : appProcesses) {  
  45.                         // The name of the process that this object is associated with.  
  46.                         if (appProcess.processName.equals(packageName)  
  47.                                         && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {  
  48.                                 return true;  
  49.                         }  
  50.                 }  
  51.    
  52.                 return false;  
  53.         }  
  54. }  

猜你喜欢

转载自blog.csdn.net/u010898441/article/details/79897412
今日推荐