【问题标题】:Firebase notification works in background but doesn't appear in Foreground in OreoFirebase 通知在后台工作,但不会出现在 Oreo 的前台
【发布时间】:2019-02-02 20:47:00
【问题描述】:

我正在尝试使用 Firebase 向我的应用发送推送通知。我试过了,它在奥利奥的后台运行得很好,但是当我尝试打开应用程序并从另一个帐户发送通知时,通知没有出现。

我该如何解决这个问题以及我的代码中的问题在哪里?

这是我的服务代码的一部分:

 public class FirebaseMessagingService extends 
     com.google.firebase.messaging.FirebaseMessagingService {

     @Override
     public void onMessageReceived(RemoteMessage remoteMessage) {
         super.onMessageReceived(remoteMessage);
         String messageTitle = remoteMessage.getNotification().getTitle();
         String messageBody = remoteMessage.getNotification().getBody();

         NotificationCompat.Builder builder = new NotificationCompat.Builder(
                this, getString(R.string.default_notification_channel_id))
             .setSmallIcon(R.drawable.ic_launcher_foreground)
             .setContentTitle(messageTitle)
             .setContentText(messageBody);
        Intent resultIntent = new Intent(this, MainAdsActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        int id = (int) System.currentTimeMillis();

        builder.setContentIntent(pendingIntent);
        startForeground(id,builder.build());

        NotificationManager notificationManager = 
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(id, builder.build());

     }
 }

Android 清单文件:

  <service
        android:name=".FirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>
    <meta-data
        android:name="com.google.firebase.messaging.default_notification_channel_id"
        android:value="@string/default_notification_channel_id"/>

云功能

const functions = require('firebase-functions');
const admin=require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const api = admin.firestore()
api.settings({timestampsInSnapshots: true})
 exports.fuync=functions
.firestore.document("Users/{userid}/notification/{notification_id}")
.onWrite((change,context)=>{
const userid=context.params.userid;
const notification_id=context.params.notification_id;
return admin.firestore().collection('Users')





    .doc(userid).collection('notification')
    .doc(notification_id).get().then(queryRes
    ult=>{

    const fromuserid=queryResult.data().from;
    const frommessage=queryResult.data().message;

    const 
    fromdata=admin.firestore()
     .collection('Users').doc(fromuserid).get();
    const todata=admin.firestore()
     .collection('Users').doc(userid).get();

    return Promise.all([fromdata,todata]).then(result=>{
        const fromname=result[0].data().name;
        const toname=result[1].data().name;
        const tokenid=result[1].data().token_id;
       //return console.log("from :" +fromname + "TO: " +toname);

       const payload= {
           notification: {
               title : "notification from" +fromname,
               body : frommessage,
               icon : "default"
           }
       };
       return admin.messaging().sendToDevice(tokenid,payload).then(result=>{
           return console.log("NOTIFICATION SENT.");
       });
    });

});
 });

构建等级

android {
compileSdkVersion 27
defaultConfig {
    applicationId "com.example.amr.app"
    minSdkVersion 18
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner 

buildToolsVersion '27.0.3'
}

【问题讨论】:

    标签: android firebase firebase-cloud-messaging google-cloud-functions


    【解决方案1】:

    这是我已经完成的解决方案,并且在 Oreo 版本和更高版本的前景和背景中完美运行。

    创建通知渠道非常重要。最重要的是NotificationChannel channel = new NotificationChannel() 中的String id。 它必须是由 firebase 提供的:default_notification_channel_id

    代码会是这样的:

        private static final CharSequence NAME = "amro";
    
     @Override
     public void onMessageReceived(RemoteMessage remoteMessage) {
     super.onMessageReceived(remoteMessage);
     //____ID _____
     int id = (int) System.currentTimeMillis();
     //_____NOTIFICATION ID'S FROM FCF_____
     String messageTitle = remoteMessage.getNotification().getTitle();
     String messageBody = remoteMessage.getNotification().getBody();
    
     NotificationCompat.Builder builder =
         new NotificationCompat
        .Builder(this, getString(R.string.default_notification_channel_id))
        .setSmallIcon(R.drawable.ic_launcher_foreground)
        .setContentTitle(messageTitle)
        .setContentText(messageBody);
    
     //_____REDIRECTING PAGE WHEN NOTIFICATION CLICKS_____
     Intent resultIntent = new Intent(this, ProfileActivity.class);
     PendingIntent pendingIntent = PendingIntent
         .getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT
         );
     builder.setContentIntent(pendingIntent);
    
     if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ) {
    
          int importance = NotificationManager.IMPORTANCE_HIGH;
          String channelID = BuildConfig.APPLICATION_ID;
          NotificationChannel channel = new NotificationChannel
         (getString(R.string.default_notification_channel_id), BuildConfig.APPLICATION_ID, importance);
          channel.setDescription(channelID);
          NotificationManager notificationManager = getSystemService(NotificationManager.class);
          //assert notificationManager != null;
          notificationManager.createNotificationChannel(channel);
     }
    
    
     NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
     assert notificationManager != null;
     notificationManager.notify(id, builder.build());
    
    
     }
    

    【讨论】:

      【解决方案2】:

      由于android oreo 有Channel

      当您面向 Android 8.0(API 级别 26)时,您必须实现一个或多个通知通道。如果您的 targetSdkVersion 设置为 25 或更低,当您的应用在 Android 8.0(API 级别 26)或更高版本上运行时,它的行为与在运行 Android 7.1(API 级别 25)或更低版本的设备上相同。

      尝试使用支持库 26 或更高版本并检查此Create and Manage Notification Channels

      尝试使用此方法创建NotificationCompat.Builder

      public NotificationCompat.Builder initChannels() {
          if (Build.VERSION.SDK_INT < 26) {
              return new NotificationCompat.Builder(this);
          }
          NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
          String id = BuildConfig.APPLICATION_ID;
          NotificationChannel channel = new NotificationChannel(id, BuildConfig.APPLICATION_ID, NotificationManager.IMPORTANCE_HIGH);
          channel.setDescription(BuildConfig.APPLICATION_ID);
          notificationManager.createNotificationChannel(channel);
          return new NotificationCompat.Builder(this, id);
      }
      

      从此方法创建新实例

      NotificationCompat.Builder builder = initChannels();
      

      【讨论】:

      • 我已经添加了我的SDK版本你可以检查一下吗?
      • 添加频道是对的,这对我有帮助。我已经发布了我的答案并且它有效。你能检查一下吗?
      【解决方案3】:
      String messageTitle = remoteMessage.getNotification().getTitle();
       String messageBody = remoteMessage.getNotification().getBody();
      

      试试

      String messageTitle = remoteMessage.getData().getTitle();
       String messageBody = remoteMessage.getData().getBody();
      

      【讨论】:

      • 它无法应用,因为我的云函数中没有使用数据对象
      【解决方案4】:

      首先在onMessageArrived()中添加日志

      Log.d("Firebase PM 服务", "onMessageArrived called");

      并检查您是否在 LogCat 中获取此日志。

      如果您不这样做,则说明 Firebase 端的某些内容无法正常工作。

      如果您收到它,则表示您在收到推送消息后做错了(即未正确显示通知)。还要检查 LogCat 是否抛出任何异常。

      然后发布你的回放。

      【讨论】:

        【解决方案5】:

        在 FirebaseMessagingService 中使用以下代码。

        @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {
          super.onMessageReceived(remoteMessage);
          String messageTitle = remoteMessage.getNotification().getTitle();
          String messageBody = remoteMessage.getNotification().getBody();
        
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = “Your channel name, It will be visible in app setting”;
            String description =“Description for your channel”;
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(SOME_CHANNEL_ID, name, importance);
            channel.setDescription(description);
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
          }
        
          NotificationCompat.Builder builder = new NotificationCompat
                       .Builder(this, getString(R.string.default_notification_channel_id))
                       .setSmallIcon(R.drawable.ic_launcher_foreground)
                       .setContentTitle(messageTitle)
                       .setContentText(messageBody);
          Intent resultIntent = new Intent(this, MainAdsActivity.class);
          PendingIntent pendingIntent = PendingIntent
         .getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT
         );
          int id = (int) System.currentTimeMillis();
          builder.setContentIntent(pendingIntent);
          startForeground(id,builder.build());
        
          NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
          notificationManager.notify(id, builder.build());
        
         }
        }
        

        【讨论】:

        • 不工作,我已经发布了我的答案,它工作,你的解决方案有一个小问题。
        猜你喜欢
        • 2019-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-22
        • 2017-05-31
        相关资源
        最近更新 更多