android - 应用关闭时的 Firebase 通知

标签 android firebase firebase-cloud-messaging firebase-notifications

我在我的 Android 应用程序中实现了 Firebase 通知。当我的应用程序正在运行时,通知会以我的自定义布局显示,但当应用程序未运行时,通知会以默认布局显示。当应用程序未运行时,如何将通知布局更改为我的布局。此外,我存储共享首选项以让用户切换通知。但是,当应用程序未运行时,无论如何都会显示通知。怎样才能做到这一点?

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    if(SettingsFragment.getReceiceNotification()){ //if user wants to receive notification

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    RemoteViews remoteViews = new RemoteViews(getPackageName(),R.layout.push_notification_layout);

    remoteViews.setImageViewResource(R.id.push_notif_icon,R.mipmap.ic_bird_black);

    Intent intent = new Intent(this,MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);


    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
    notificationBuilder.setContent(remoteViews);
    notificationBuilder.setContentTitle("Radyo Türkkuşu");
    notificationBuilder.setContentText(remoteMessage.getNotification().getBody());

    notificationBuilder.setAutoCancel(true);
    notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
    notificationBuilder.setContentIntent(pendingIntent);
    remoteViews.setTextViewText(R.id.push_title, "Radyo Türkkuşu");
    remoteViews.setTextViewText(R.id.push_context, remoteMessage.getNotification().getBody());
    //notificationBuilder.setLights (ContextCompat.getColor(MainActivity.context, R.color.pushColor), 5000, 5000);
    notificationManager.notify(0,notificationBuilder.build());
    }

}

最佳答案

您的问题是您将它与通知托盘一起使用。

查看 link

Messages with both notification and data payload, both background and foreground. In this case, the notification is delivered to the device’s system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.

如果您在应用运行时将 {data:"something"}(data-message){notification:"something"}(display-message) 一起使用在后台,数据负载将传递给 Intent 的附加部分,但不会传递给 onMessageReceived() 方法。我假设您实现了显示通知的代码,因此当您的应用程序处于前台时 onMessageReceived() 是触发器,它会显示您想要的通知,但是当它不是 onMessageReceived() 时,没有获取触发器,而是 android 系统将使用您的通知有效负载处理它。您只需从服务器端代码中删除 {notification:"something"}(display-message/notification tray) 以始终确保 onMessageReceived()

对于任何人来说,无论是不是前台还是后台,onMessageReceived() 都会触发,请访问 link

关于android - 应用关闭时的 Firebase 通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41383238/

相关文章:

java - 停止 MediaPlayer 时出现问题

Embarcadero XE5 中的 Android NFC

java - 如何增加 Firebase 查询中 "limitToFirst"的限制?

flutter - 启用或禁用通知抖动

firebase - Flutter-如何获取当前上下文?

android - 从 list 中以编程方式加载 Activity 和/或应用程序 Logo

Android 垃圾收集运行异常

java - FirebaseAuth 未创建用户

android - 从 Firebase 控制台中删除 Firebase 用户时(用户登录后),它不会反射(reflect)在应用程序中

ios - 您可以使用 ios 的 FCM 通知设置线程 ID