在Android上屏幕显示通知

6
我正在使用这段代码发送本地通知。
mNotificationManager = (NotificationManager)
                getSystemService(Context.NOTIFICATION_SERVICE);

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                i, PendingIntent.FLAG_ONE_SHOT);

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
                        .setContentTitle(title)
                        .setDefaults(Notification.DEFAULT_SOUND)
                        .setStyle(new NotificationCompat.BigTextStyle()
                                .bigText(msg))
                        .setContentText(msg);

        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify((int)value, mBuilder.build());

然而,如果手机屏幕被滑动锁定,它们会显示在状态栏上。我想像WhatsApp、Facebook、短信等应用一样,在屏幕顶部显示推送通知。如何实现这一点?

我认为Android操作系统会自动处理它。 - Hiren Patel
@HirenPatel 好的,我只在状态栏上看到了一个小图标,没有显示在锁屏顶部。 - Muhammad Umar
仅在Android 5(Lollipop)中默认支持悬浮通知。因此,如果您仍然想要这样做,那么您可以构建自定义通知视图,并使用WindowManager服务将其添加到屏幕中。 - GiapLee
1个回答

6
你可以这样做:
通过添加以下行:
setPriority(Notification.PRIORITY_MAX)

完整代码:

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

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                i, PendingIntent.FLAG_ONE_SHOT);

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
                        .setContentTitle(title)
                        .setDefaults(Notification.DEFAULT_SOUND)
                        .setStyle(new NotificationCompat.BigTextStyle()
                                .bigText(msg))
                        .setContentText(msg)
                        .setPriority(Notification.PRIORITY_MAX);

        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify((int)value, mBuilder.build());

希望这能对你有所帮助。

似乎无法正常工作,我只收到顶部通知和通知。 - Muhammad Umar
2
它在我的设备上运行良好,但在Marshmallow及以上版本中无法正常工作,感谢@Hiren。 - Anurag Shrivastava

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