Send a notification only when my app is not running

I want to send a notification when an alarm starts the broadcastreceiver and my App is closed. On the Receive method, Works fine detecting when the app is running. But the else part is not working. The "send_notification" method only works if it is not inside the else. Even the System.Out is not working when app is closed.

    public void onReceive(Context context, Intent intent) {


      if (App_status.isAppRunning(context, "com.example.app")) {

            System.out.println(TAG + " APP IS RUNNING");

      } else {

            System.out.println(TAG + " APP IS NOT RUNNING");

        send_notification(context);

      }
}


    public static boolean isAppRunning(final Context context, final String packageName) {
        final ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        final List<ActivityManager.RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();
        if (procInfos != null) {
            for (final ActivityManager.RunningAppProcessInfo processInfo : procInfos) {
                if (processInfo.processName.equals(packageName)) {
                    return true;
                }
            }
        }
        return false;
    }

} 

Why doesn't work the else part?

I tried also to create a String variable. Being null at the begining the activity and changing to "no" if app is running. Inside the if(App_status.isAppRunning(context, "com.example.app")).

So at the end asking if the variable is diferent of no send the notification. But also doesn't work.

1 answer

  • answered 2020-07-29 17:26 Karan Khurana

    Use alarm manager, for this :

    AlarmManager alarmManager =
        (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent pendingIntent =
        PendingIntent.getService(context, requestId, intent,
                                    PendingIntent.FLAG_NO_CREATE);
    if (pendingIntent != null && alarmManager != null) {
      alarmManager.cancel(pendingIntent);
    }
    

    For full guidance visit this developer android page