推送通知的前景和背景

时间:2018-07-25 16:19:02

标签: java notifications

我创建了一个简单的通知,并使用创建和设计的全新图层以不同的颜色和通用样式设置了通知。 一旦我通过Firebase Messages触发了通知,当应用程序处于前台时,它就可以完美显示我所需的确切样式。

但是当应用程序在后台运行时,它使用的是丑陋的默认样式。

是否可以解决该问题?谢谢。

通知Java类文件代码-

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

private static final String TAG = "FirebaseMessagingServic";

public MyFirebaseMessagingService() {
}

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    String title = remoteMessage.getNotification().getTitle();
    String message = remoteMessage.getNotification().getBody();
    Log.d(TAG, "onMessageReceived: Message Received! \n " +
        "Title : " + title + "\n" +
            "Message : " + message);

    sendNotification(title, message);

}

@Override
public void onDeletedMessages() {



}

private void sendNotification(String title, String messageBody) {

    final RemoteViews remoteViews = new RemoteViews(getApplicationContext().getPackageName(), R.layout.notification_layout);

    remoteViews.setTextViewText(R.id.remoteview_notification_short_message, messageBody);
    remoteViews.setTextViewText(R.id.notificationDate, title);

    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    String channelId = "0";
    Uri defaultSoundUri= Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/notice");
    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this, channelId)

                    .setSmallIcon(R.mipmap.minilogored)
                    .setContentIntent(pendingIntent)
                    .setContent(remoteViews)
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setLights(0xf14d39, 1500, 2000)
                    .setPriority(NotificationCompat.PRIORITY_HIGH);


    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    // Since android Oreo notification channel is needed.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(channelId,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_DEFAULT);
        notificationManager.createNotificationChannel(channel);
    }

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

}

1 个答案:

答案 0 :(得分:0)

请参考链接以更多地了解数据消息和显示消息如何在onMessageReceived()回调函数中进行处理。

How to handle notification when app in background in Firebase

https://firebase.google.com/docs/cloud-messaging/android/receive