仅在未在oreo上打开应用程序时显示通知的标题和正文?

时间:2019-05-04 13:03:33

标签: android push-notification firebase-cloud-messaging android-8.0-oreo

我在Oreo上使用FCM尝试过Android Push Notification,我得到的是当应用程序未运行时,通知显示在通知栏上,并显示了标题和正文,但是当我尝试在打开应用程序时发送通知时,我收到一个带有空标题和正文的通知。然后,我尝试将应用程序保留在后台,而没有关闭该应用程序,该通知再次显示标题和正文。

这是我的FirebaseMessagingService代码:

NotificationManager notificationManager;
private static final String ADMIN_CHANNEL_ID ="default";
Uri defaultSoundUri;
int notificationId;

@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override public void onMessageReceived(RemoteMessage remoteMessage) {

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

    //Setting up Notification channels for android O and above
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        setupChannels();
    }
    notificationId = new Random().nextInt(60000);

    defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, ADMIN_CHANNEL_ID)
            .setChannelId(ADMIN_CHANNEL_ID) //COBA HAPUS KALO NOUGAT FORCE CLOSE (OPTIONAL)
            .setSmallIcon(R.drawable.ic_launcher_background)
            .setPriority(Notification.PRIORITY_HIGH) //COBA HAPUS KALO NOUGAT FORCE CLOSE (OPTIONAL)
            .setContentTitle(remoteMessage.getData().get("title"))
            .setContentText(remoteMessage.getData().get("message"))
            .setAutoCancel(true)
            .setVibrate(new long[]{0, 100, 100, 100, 100, 100})
            .setSound(defaultSoundUri);

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

    notificationManager.notify(notificationId, notificationBuilder.build());

}

@RequiresApi(api = Build.VERSION_CODES.O)
private void setupChannels(){
    CharSequence adminChannelName = getString(R.string.app_name);
    String adminChannelDescription = getString(R.string.notifications_admin_channel_description);

    AudioAttributes attributes = new AudioAttributes.Builder()
            .setUsage(AudioAttributes.USAGE_NOTIFICATION)
            .build();
    NotificationChannel adminChannel;
    adminChannel = new NotificationChannel(ADMIN_CHANNEL_ID, adminChannelName, NotificationManager.IMPORTANCE_HIGH);
    adminChannel.setDescription(adminChannelDescription);
    adminChannel.enableLights(true);
    adminChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
    adminChannel.setSound(defaultSoundUri, attributes);
    adminChannel.enableVibration(true);
    if (notificationManager != null) {
        notificationManager.createNotificationChannel(adminChannel);
    }
}

我错过了我的代码吗?

0 个答案:

没有答案