如何在应用程序处于后台时显示firebase通知的自定义UI?

时间:2018-06-01 10:02:39

标签: android firebase notifications remoteview

我使用此类来显示从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());
        }

    }

}

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

1 个答案:

答案 0 :(得分:4)

实际上我们在发送通知时使用了两种有效载荷,

一个是通知有效负载,另一个是数据有效负载。 当您处于从firebase服务调用onMessageReceived的前台时,通知有效负载会自动管理通知,但是当您在Background中时他们不会调用onMessageReceived,

因此,出于解决方案的目的,只需在数据有效负载中发送数据并删除通知有效负载,这样您就可以在每个状态的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'
);