Firebase通知在后台工作,但不会出现在Oreo的前景中

时间:2018-08-28 09:09:56

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

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

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

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

 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.");
       });
    });

});
 });

构建gradle

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

buildToolsVersion '27.0.3'
}

5 个答案:

答案 0 :(得分:1)

自android oreo以来就有频道

  

以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();

答案 1 :(得分: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 :(得分:0)

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

尝试

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

答案 3 :(得分:0)

首先在onMessageArrived()中添加日志

Log.d(“ Firebase PM服务”,“ onMessageArrived被调用”);

,然后检查是否在LogCat中获得此日志。

如果不这样做,则说明Firebase端无法正常工作。

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

然后发布您的重放。

答案 4 :(得分:0)

在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());

 }
}