当应用程序在后台运行时,如何显示自定义UI用于Firebase通知?

X F*_* Fa 2 notifications android remoteview firebase

我使用此类显示从Firebase控制台收到的自己的UI(RemoteViews)的通知。当应用程序是前台应用程序时,这很好用,但是当应用程序在后台运行时,通知以默认的设备样式显示。即使应用程序是前台或后台,我应该怎么做才能在自己的UI中显示通知?

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "Mehdi";

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

        if (remoteMessage.getNotification() != null)
        {
            RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.payam_notification_layout);
            contentView.setTextViewText(R.id.payam,remoteMessage.getNotification().getBody());

            String channelId = "Default";
            NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(this,channelId)
                            .setSmallIcon(R.drawable.status_icon_delivered)
                            .setLargeIcon(BitmapFactory.decodeResource( getResources(), R.mipmap.icon))
                            .setSound(Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.notification))
                            .setCustomBigContentView(contentView)
                            .setContentTitle(remoteMessage.getNotification().getTitle())
                            .setContentText(remoteMessage.getNotification().getBody())
                            .setAutoCancel(true);

            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel(channelId, "Default channel", NotificationManager.IMPORTANCE_DEFAULT);
                manager.createNotificationChannel(channel);
            }
            manager.notify(0, mBuilder.build());
        }

    }

}
Run Code Online (Sandbox Code Playgroud)

注意:感谢您提供正确的答案,我可以使用此链接通过自己的UI发送通知,即使应用程序在后台还是前台:http : //www.androiddeft.com/2017/11/18/push-notification-android -firebase-php /

Dha*_*nki 5

实际上是在发送通知时使用的拖曳类型的有效载荷,

一个是通知有效负载,另一个是数据有效负载。通知有效负载自动管理通知,当您在前台时它们会从Firebase服务中调用onMessageReceived,但是当您在后台时它们不会调用onMessageReceived,

因此,出于解决方案的目的,只需在Data有效负载中发送数据并删除Notification有效负载,这样您就可以在每种状态下的onMessageReceived中获取通知,并可以管理其UI。

检查波纹管示例

function sendFCMNotification($message,$id) {
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array (
        'to' => $id,
        'data' => array (
                "body" => $message,
                "title" => "Title Text"
        )
);
$fields = json_encode ( $fields );
$headers = array (
        'Authorization: key=' . "Legcy Key",
        'Content-Type: application/json'
);
Run Code Online (Sandbox Code Playgroud)