0

I have my app that receives a GCM message from the server. I got all that working with notification coming up.

My issue is that if the app is open then I don't want to show notification and just display show the message withing the app. But if the app is closed then I need to show notification ( like a chat app).

How can I do this determination?

Thanks

Snake
  • 14,228
  • 27
  • 117
  • 250
  • there is no way to determine it except manually - create some flag somewhere, and track your app's activities' lifecycle to check if any activity is in foreground. – Vladyslav Matviienko Jun 12 '17 at 06:51

2 Answers2

0

you can check if app is in background or not try this.

 public static boolean isAppIsInBackground(Context context) {
    boolean isInBackground = 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())) {
                        isInBackground = false;
                    }
                }
            }
        }
    } else {
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        ComponentName componentInfo = taskInfo.get(0).topActivity;
        if (componentInfo.getPackageName().equals(context.getPackageName())) {
            isInBackground = false;
        }
    }

    return isInBackground;
}
0

You can add an listener for Activity lifecycle events to your Application object.

See here Android event listener for app lifecycle

Checking if an Android application is running in the background

Kaskasi
  • 1,330
  • 1
  • 14
  • 15