Java 仅当应用程序处于后台时发送推送通知

Java 仅当应用程序处于后台时发送推送通知,java,android,push-notification,background,foreground,Java,Android,Push Notification,Background,Foreground,我使用NotificationManager、NotificationChannel和NotificationCompat.Builder在触发事件时显示推送通知,无需在线Firebase 推送通知在我的应用程序处于前台和后台时显示,但它只应在我的应用程序处于后台时显示 我有两个活动,其中只有1个知道创建推送通知的类。我可以设置一个变量来显示我的活动是否在前台(使用onResume和onPause),但如果我的其他活动启动了活动,则通知触发器类设置在后台,因此我不能使用此方法。我需要知道整个应用

我使用NotificationManager、NotificationChannel和NotificationCompat.Builder在触发事件时显示推送通知,无需在线Firebase

推送通知在我的应用程序处于前台和后台时显示,但它只应在我的应用程序处于后台时显示

我有两个活动,其中只有1个知道创建推送通知的类。我可以设置一个变量来显示我的活动是否在前台(使用onResume和onPause),但如果我的其他活动启动了活动,则通知触发器类设置在后台,因此我不能使用此方法。我需要知道整个应用程序是否在前台,但我没有找到解决这个问题的好方法


那么,当我的整个应用程序都在后台时,是否还有其他方法显示推送通知呢?

因此,我找到了一个解决这个问题的正确且非常好的方法。 根据这一回答:


我认为您有
FCMListenerService
作为后台服务接收推送通知。
服务
应在清单文件中具有以下声明

<service android:name=".Service.FCM.FCMListenerService">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

希望有帮助

检查一下,我找不到任何可以帮助我的东西。他们使用的是谷歌firebase,而不是本地pushsystem。
<service android:name=".Service.FCM.FCMListenerService">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>
private static boolean isForeground(Context context) {
    ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> runningTaskInfo = manager.getRunningTasks(1);
    ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
    return componentInfo.getPackageName().equals(Constants.ApplicationPackage);
}
public class FCMListenerService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage message) {
        if(!isForeground(this)) createNotification();
    }
}