ActivityManager.getRunningTasks is deprecated android

前端 未结 5 1282
情书的邮戳
情书的邮戳 2020-12-01 05:51

I am working on push notification in android where i am using a below method to show notification, but the problem is that now ActivityManager.getRunningTasks(1); is being

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-01 06:29

    This should work for the pre Lollipop devices as well as for Lollipop devices

    public static boolean isBackgroundRunning(Context context) {
            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List 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())) {
                            //If your app is the process in foreground, then it's not in running in background
                            return false;
                        }
                    }
                }
            }
    
    
            return true;
        }
    

    Edit: It should return true if the app is in background, not the opposite

提交回复
热议问题