Push notification at application launch

I am implementing a push notification, and so far it is working fine. I manage to get a push notification and when I click on it to get started.

But I do not want to notify the user of the notification if the application is already running. This is how I plan to do it ... but not sure if this is the right 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;
}
Function

isActivityRunning will basically check if MainActivity is working or not. If it is in working condition, it will not show a notification and will transmit information to the action itself to update the interface. If the activity is not started when you click the notification, MainActivity will open.

Is this achieved correctly?

+4
2

activity manager , . . , foreground background. , , onResume onPause .

:

  public void onResume()
    {
       super.onResume();
      isActivityRunning = true;
    }
    public void onPause()
    {
       super.onPause();
       isActivityRunning = false;
    }

isActivityRunning, , .

. : , Android

+5

, , :

 private boolean isActivityRunning() {
    if (MainActivity.getInstance() != null) {
        return true;
    } else {
        return false;
    }
}

MainActivity

 public static MainActivity getInstance() {
    return mInstance;
}

in onCreate mInstance:

mInstance = this;

onDestroy:

mInstance = null;

mInstance, MainActivity, .

0

Source: https://habr.com/ru/post/1532915/


All Articles