简体   繁体   English

仅在我的应用未运行时发送通知

[英]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.我想在警报启动 broadcastreceiver 并且我的应用程序关闭时发送通知。 On the Receive method, Works fine detecting when the app is running.在 Receive 方法上,可以很好地检测应用程序何时运行。 But the else part is not working.但是其他部分不起作用。 The "send_notification" method only works if it is not inside the else. “send_notification”方法只有在不在 else 中时才有效。 Even the System.Out is not working when app is closed.当应用程序关闭时,即使 System.Out 也不工作。

    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?为什么 else 部分不起作用?

I tried also to create a String variable.我还尝试创建一个 String 变量。 Being null at the begining the activity and changing to "no" if app is running.在活动开始时为 null,如果应用程序正在运行,则更改为“否”。 Inside the if(App_status.isAppRunning(context, "com.example.app")).在 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.但也不起作用。

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如需完整指南,请访问此 开发人员 android 页面

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM