深入解析Android系统中应用程序前后台切换的实现要点

2019-12-10 18:07:56丽君

具体实现代码如下:

//用来控制应用前后台切换的逻辑 
 private boolean isCurrentRunningForeground = true; 
 @Override 
 protected void onStart() { 
   super.onStart(); 
   if (!isCurrentRunningForeground) { 
     Log.d(TAG, ">>>>>>>>>>>>>>>>>>>切到前台 activity process"); 
   } 
 } 
 
 @Override 
 protected void onStop() { 
   super.onStop(); 
   isCurrentRunningForeground = isRunningForeground(); 
   if (!isCurrentRunningForeground) { 
     Log.d(TAG,">>>>>>>>>>>>>>>>>>>切到后台 activity process"); 
   } 
 } 
 
 public boolean isRunningForeground() { 
   ActivityManager activityManager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE); 
   List<ActivityManager.RunningAppProcessInfo> appProcessInfos = activityManager.getRunningAppProcesses(); 
   // 枚举进程 
   for (ActivityManager.RunningAppProcessInfo appProcessInfo : appProcessInfos) { 
     if (appProcessInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { 
       if (appProcessInfo.processName.equals(this.getApplicationInfo().processName)) { 
         Log.d(TAG,"EntryActivity isRunningForeGround"); 
         return true; 
       } 
     } 
   } 
   Log.d(TAG, "EntryActivity isRunningBackGround"); 
   return false; 
 } 


注:相关教程知识阅读请移步到Android开发频道。