类似于WhatsApp或短信应用的Android通知

6

我想创建一个类似于WhatsApp或短信通知的通知视图。我该如何实现这一点。

enter image description here

到目前为止我所搜寻的内容:

Crouton: 可以在这里找到

这将在运行的活动和操作栏下方显示一个 Crouton。如果我的活动没有运行或者我在其他活动上,该如何处理。

Toast: 这不像一个 Toast。它只会出现在底部或中心位置。

Dialog: 可以这样做,但是这会使应用程序变模糊并禁用背景。而我不想要这个。

任何解决方案都将受到赞赏。

谢谢


1
你需要的是一个通知。(http://developer.android.com/guide/topics/ui/notifiers/notifications.html) WhatsApp和其他所有应用程序都有自己定制的通知。如果您正在寻找定制的通知,我可以帮助您。但我不确定您确切需要什么。 - Sandeep R
3个回答

12

这是一种在 Android Lollipop 及以上版本中使用的悬浮通知。您可以在此处查看如何显示通知:http://developer.android.com/guide/topics/ui/notifiers/notifications.html ,要使用悬浮通知,您需要将通知优先级设置如下:

.setPriority(Notification.PRIORITY_HIGH)

希望它有所帮助

编辑于Nov-17

Notification.PRIORITY_HIGH在API level 26中已被弃用,请使用(NotificationManager.IMPORTANCE_HIGH)代替。


如果您查看屏幕截图,您会发现我没有拉下通知栏。这种情况发生的原因是:
  1. 当消息到来时,Crouton 会显示并出现在状态栏上的通知图标中。
- shailesh
是的,这是悬浮通知。我会将代码添加为答案。谢谢。 - shailesh
现在 Notification.PRIORITY_MAX 已经被弃用。 - pRaNaY
在使用NotificationCompat.Builder时,使用NotificationCompat.PRIORITY_HIGHNotificationCompat.PRIORITY_MAX代替。 - pRaNaY

6

可以通过 Headsup 通知来完成。这是 Andorid L 的一个功能,下面是演示代码:

Notification createNotification(boolean makeHeadsUpNotification) {
    Notification.Builder notificationBuilder = new Notification.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setPriority(Notification.PRIORITY_DEFAULT)
            .setContentTitle("Sample Notification")
            .setContentText("This is a normal notification.");

    if(Build.VERSION.SDK_INT> Build.VERSION_CODES.KITKAT)
    {
        notificationBuilder.setCategory(Notification.CATEGORY_MESSAGE);
    }
    if (makeHeadsUpNotification) {
        Intent push = new Intent();
        push.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        push.setClass(this, IndexActivity.class);

        PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(this, 0,
                push, PendingIntent.FLAG_CANCEL_CURRENT);
        notificationBuilder
                .setContentText("Heads-Up Notification on Android L or above.")
                .setFullScreenIntent(fullScreenPendingIntent, true);
    }
    return notificationBuilder.build();
}

您可以这样调用它

 NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context
           .NOTIFICATION_SERVICE);
    mNotificationManager.notify(NOTIFICATION_ID, createNotification(
           true));

我有一个疑问,如果应用程序关闭了,我会收到通知吗? - user6602265
@Vishal 为什么不行呢?这是API 21及以上版本中通知如何在屏幕上显示的方式。 - shailesh

0

您在上方图像中看到的是“提醒通知”(在安卓4.3后添加的功能)

链接: 提醒通知

将通知优先级设置为高,以便在屏幕顶部显示它。希望这可以帮助您。


嘿,如何从4.3支持它?我以为它是从5.0开始支持的。是否有任何支持库或类似的东西,请告诉我,我想在我的应用程序中实现它。 - Pavan
头顶通知是Lollipop的新增功能。我怀疑你无法在Pavan上实现它。 - ajinkya gaurkar
@ajinkyagaurkar,我知道你提到了4.3之后的事情,所以我问了一下。 - Pavan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接