Push Notification when app is running
android, google-cloud-messaging, push-notification
Solution
Using the `activity manager` doesn't exactly work as expected. The activity manager keeps a track of all the running apps on the phone. It doesn't really tell you whether the app is in `foreground` or `background`. To check whether the activity is running, set a boolean value in the `onResume` and `onPause` method of the activity.
Example:
public void onResume()
{
super.onResume();
isActivityRunning = true;
}
public void onPause()
{
super.onPause();
isActivityRunning = false;
}
You can then use the isActivityRunning to see if you want to throw the notification or not.
Also see this: Checking if an Android application is running in the background
Problem
I am implementing push notification and so far it works fine. I manage to get push notification and when I click on that able to start activity. But I don't want to notify user about notification if app is already running. This how I am planning to do this...but not sure is this correct way ``` Intent actIntent = new Intent(this, MainActivity.class); actIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pIntent = PendingIntent.getActivity(this, 0, actIntent, 0); if (!isActivityRunning()) mNotificationManager.notify(0, notification); public boolean isActivityRunning(Context ctx) { ActivityManager activityManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE); List<RunningTaskInfo> tasks = activityManager.getRunningTasks(Integer.MAX_VALUE); for (RunningTaskInfo task : tasks) { if (ctx.getPackageName().equalsIgnoreCase(task.baseActivity.getPackageName())) return true; } return false; } ``` isActivityRunning function will basically checks whether MainActivity is running or not. If it is in running state then won't show notification and will pass information to activity itself to update UI. If activity is not running on click of notification MainActivity will open. Is this right way of achieving this?