How to detect if your android app is in the foreground (API 21)

独自空忆成欢 提交于 2019-12-04 16:35:36

You can use an ordered broadcast approach where you

  • Create a BroadcastReceiver registered in your manifest which does the background behavior
  • Dynamically register a BroadcastReceiver in your activity with a positive priority (the default is 0), making sure to register it in onStart()/onResume() and unregistering it in onStop()/onPause() - this does the foreground behavior and should call abortBroadcast() to ensure the manifest registered BroadcastReceiver is not called

Your GCM receiver can then use sendOrderedBroadcast() to send a broadcast (preferably with a custom action that both your other BroadcastReceivers register for) which will be received by the dynamically registered receiver if it exists and the manifest registered receiver if it does not exist.

I detect using getRunningAppProcesses

boolean isOnForeground = true;
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH)
{
    List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
    for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses)
    {
        if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND)
        {
            for (String activeProcess : processInfo.pkgList)
            {                                 if(activeProcess.equals(context.getPackageName()))
                {
                    isOnForeground = false;
                }
            }
        }
    }
}
else
{
     List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
     ComponentName componentInfo = taskInfo.get(0).topActivity;
                if(componentInfo.getPackageName().equals(context.getPackageName()))
     {
          isOnForeground = false;
     }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!