Firebase 前台通知未显示

Posted

技术标签:

【中文标题】Firebase 前台通知未显示【英文标题】:Firebase Foreground Notifications Not Showing 【发布时间】:2019-08-05 14:36:21 【问题描述】:

由于某种原因,我的 Firebase 通知没有显示在前台。然而,它们在后台运行良好,我按照 Anroid Studio 告诉我添加的内容以及 tutorial example on github

从运行窗口判断,它正在接收通知但没有在前台发送

这是我发送通知的服务代码

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import static android.support.constraint.Constraints.TAG;

public class FirebaseNotificationsRecieverService extends FirebaseMessagingService 
    private static final String TAG = FirebaseNotificationsRecieverService.class.getName();

    public FirebaseNotificationsRecieverService() 
    

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) 
        // ...
        System.out.println("RECIEVED");
        // TODO(developer): Handle FCM messages here.
        // Not getting messages here? See why this may be: (there was a link here)
        Log.d(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) 
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());

            if (/* Check if data needs to be processed by long running job */ true) 
                // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
                //scheduleJob();
             else 
                // Handle message within 10 seconds
                handleNow();
            

        

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) 
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        
        sendNotification(remoteMessage.getNotification().getBody());
        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.
    
    private void handleNow() 
        Log.d(TAG, "Short lived task is done.");
    

    private void sendNotification(String messageBody) 
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String channelId = getString(R.string.default_notification_channel_id);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.wlmaclogo)
                        .setContentTitle(getString(R.string.fcm_message))
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) 
            NotificationChannel channel = new NotificationChannel(channelId,
                    "Channel human readable title",
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    


清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.starenkysoftware.macapp">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true">
        <service
            android:name=".FirebaseNotificationsRecieverService"
            android:enabled="true"
            android:exported="true"></service>
        <service android:name="com.google.firebase.messaging.FirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

【问题讨论】:

你是否在 manifest 中定义了服务? 是的。只需添加清单^,如果您可以检查它以确保它没问题。我的运行模块说“已连接到远程服务”,然后是“不活动,与服务断开连接”,但是当我推送通知时,它似乎又重新启动了。 我添加了一个 System.out.println("RECIEVED");看看它是否甚至调用了 onMessageReceived 但它没有打印任何东西所以我认为它没有调用该方法 试试这个***.com/questions/52609283/… 【参考方案1】:

替换清单如下:-

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.starenkysoftware.macapp">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    android:usesCleartextTraffic="true">

    <service android:name=".FirebaseNotificationsRecieverService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

intent 过滤器com.google.firebase.MESSAGING_EVENT 应放置在您用于获取通知的服务中。

【讨论】:

非常感谢您解决了所有问题!能否请您告诉我如何将.setContentTitle(getString(R.string.fcm_message)) 换成firebase 通知附带的标题?我尝试将 remoteMessage 传递给 sendNotification(RemoteMessage remoteMessage) 并且它适用于描述,但 remoteMessage.getNotification().getTitle() 的标题给出错误 Cannot resolve method 'getString(java.lang.String)'【参考方案2】:

记得从 AndroidManifest.xml 中删除现有的消息服务。如果您将 FireBaseMessagingService 留在 Manifest 中。您新定义的服务没有被提取。

例如删除以下内容:

    <service
        android:name="com.google.firebase.messaging.FirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

并添加以下内容:

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

【讨论】:

以上是关于Firebase 前台通知未显示的主要内容,如果未能解决你的问题,请参考以下文章

Firebase Cloud Messaging 通知未显示在 iOS 设备上(前台和后台)

应用程序处于前台时未收到 Firebase 推送通知

Web 前台推送通知未弹出在 Reactjs 中使用 Firebase 集成

在某些设备中未显示 React 本机 Firebase 通知提示

在前台显示通知反应原生 firebase v6

如何使用 Firebase Cloud Messaging 在前台显示多个通知