解除抬头通知并创建正常通知

leo*_*ian 4 notifications android heads-up-notifications

我正在使用此代码创建Heads Up通知.

private static void showNotificationNew(final Context context,final String title,final String message,final Intent intent, final int notificationId, final boolean isHeaderNotification) {
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context.getApplicationContext())
            .setSmallIcon(R.drawable.prime_builder_icon)
            .setPriority(Notification.PRIORITY_DEFAULT)
            .setCategory(Notification.CATEGORY_MESSAGE)
            .setContentTitle(title)
            .setContentText(message)
            .setWhen(0)
            .setTicker(context.getString(R.string.app_name));

    PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    notificationBuilder.setContentText(message);
    if(isHeaderNotification) {
        notificationBuilder.setFullScreenIntent(fullScreenPendingIntent, false);
    }

    notificationBuilder.setContentIntent(fullScreenPendingIntent);
    notificationBuilder.setAutoCancel(true);


    Notification notification = notificationBuilder.build();
    NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(notificationId, notification);
}
Run Code Online (Sandbox Code Playgroud)

事情是,通知应该出现占据顶部屏幕的一个好部分以引起用户注意,但是几秒钟之后它应该被解雇并且应该出现正常通知.

但是这段代码并没有这样做.通知保持占据所有顶部屏幕,直到用户解雇它.

我正在考虑使用Handler在几秒钟后使用相同的ID创建另一个正常通知,但我想知道是否有更好的方法来执行此操作.

按照WhatsApp的一个例子,模拟我想要的行为.

在此输入图像描述 在此输入图像描述

Mat*_*ini 6

问题是由于您使用setFullScreenIntent引起的:

启动而不是将通知发布到状态栏的意图.仅适用于要求用户立即关注的极高优先级通知,例如用户明确设置为特定时间的来电或闹钟.如果此设施用于其他设施,请为用户提供关闭并使用正常通知的选项,因为这可能会造成极大的破坏.

另外,如本回答所述,您应该使用setVibrate进行Heads-up工作.

这是工作单挑通知的一个例子:

private static void showNotificationNew(final Context context, final String title, final String message, final Intent intent, final int notificationId) {
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context.getApplicationContext())
            .setSmallIcon(R.drawable.small_icon)
            .setPriority(Notification.PRIORITY_HIGH)
            .setContentTitle(title)
            .setContentText(message)
            .setVibrate(new long[0])
            .setContentIntent(pendingIntent)
            .setAutoCancel(true);

    NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(notificationId, notificationBuilder.build());
}
Run Code Online (Sandbox Code Playgroud)

  • 有趣的是,设置全屏意图可以防止平视通知自动关闭。当我想到我的电话响起时,这是有道理的,但我花了一段时间才弄清楚发生了什么。 (2认同)