user2095470 user2095470 - 4 months ago 52
Android Question

Push Notification when app is running

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);
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?


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.


  public void onResume()
      isActivityRunning = true;
    public void onPause()
       isActivityRunning = false;

You can then use the isActivityRunning to see if you want to throw the notification or not.

Also see this: Android: Is application running in background?