Android通知显示但未在屏幕上弹出

时间:2018-10-16 19:34:09

标签: android push-notification android-notifications

我正在尝试在Android中使用通知。我面临的问题是通知显示如下(左上角为黑色): enter image description here

我希望它像WhatsApp通知一样弹出。我该怎么办。目前,我正在使用以下代码:

public void displayNotification(String title,String body) {
    Intent intent = new Intent(context, ViewEventsActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
    taskStackBuilder.addNextIntentWithParentStack(intent);

    PendingIntent pendingIntent = taskStackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);

    Bitmap icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.logo);

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context,Utils.CHANNEL_ID)
            .setSmallIcon(R.drawable.logo)
            .setLargeIcon(icon)
            .setContentTitle("SRC:"+title)
            .setContentText(body)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .setCategory(NotificationCompat.CATEGORY_ALARM);

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

    if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel=new NotificationChannel(CHANNEL_ID,CHANNEL_NAME,NotificationManager.IMPORTANCE_DEFAULT);

        notificationChannel.setDescription(CHANNEL_DESC);
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.enableVibration(true);
        notificationChannel.setVibrationPattern(new long[]{100,200,300,400,500,400,300,200,400});
        notificationManager.createNotificationChannel(notificationChannel);
    }

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

如何完成我想要的任务?

1 个答案:

答案 0 :(得分:0)

我今天遇到了同样的问题。 经过大量尝试,我找到了解决方案。您只需要添加优先级和默认值即可。这是自定义视图的示例。

NotificationCompat.Builder(context)
            .setCustomContentView(createView())
            .setDefaults(NotificationCompat.DEFAULT_ALL)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setChannelId(CHANNEL_ID)
            .setSmallIcon(R.drawable.icon_notification)
            .build()