Firebase云消息传递无法在后台运行

时间:2020-06-21 17:11:59

标签: android firebase api firebase-realtime-database firebase-cloud-messaging

我正在尝试向我的应用发送推送通知。但是,如果应用程序在后台运行,则不会收到通知。我正在使用Firebase云消息传递服务。

这是onMessageReceived方法:

 @Override
    public void onMessageReceived(@NonNull final RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        Map<String, String> data = remoteMessage.getData();
        String body = data.get("body");
        String title = data.get("title");
        String id = data.get("android_channel_id");
        int priority = remoteMessage.getPriority();


        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getApplicationContext());

        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

 Notification notification = new NotificationCompat.Builder(getApplicationContext(), id)
                        .setSmallIcon(R.drawable.notification)
                        .setContentTitle(title)
                        .setContentText(body)
                        .setPriority(priority)
                        .setContentIntent(pendingIntent)
                        .setStyle(new androidx.media.app.NotificationCompat.MediaStyle())
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.aajevan_logo))

                        .setAutoCancel(true)
                        .build();

                notificationManager.notify(200, notification);


 @Override
    public void onNewToken(@NonNull String s) {
        FirebaseInstanceId.getInstance().getInstanceId()
                .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                    @Override
                    public void onComplete(@NonNull Task<InstanceIdResult> task) {

                        if (!task.isSuccessful()) {
                            Log.d("*******FAILED", task.getException().getMessage());
                            return;
                        }

                        String token = task.getResult().getToken();
                        Log.d("/**MY TOKEN", token);
                    }
                });
    }


当应用程序处于前台或后台时,没有问题。但是,如果我杀死我的应用程序,它将无法正常工作。如果我打开应用一次,那么我会立即收到所有通知。

1 个答案:

答案 0 :(得分:0)

首先,有两种消息类型(通知和数据)。 Firebase控制台发送通知消息。当您发送这些类型的消息时,firebase会在您的应用程序关闭或在后台(未终止)时自动处理它们。检查this以获得有关通知消息和数据消息的更多信息。

另外,被杀死的应用程序是用户强制停止运行或由于错误或操作系统决定将其杀死(电池管理)而崩溃的应用程序。被终止的应用程序将不会收到任何通知。