如何使用 NotificationCompat.Builder 创建通知? [英] How to create a notification with NotificationCompat.Builder?

查看:20
本文介绍了如何使用 NotificationCompat.Builder 创建通知?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果可能,我需要创建一个简单的通知,该通知将与声音和图标一起显示在通知栏中?我还需要它与 Android 2.2 兼容,所以我发现 NotificationCompat.Builder 适用于 4 以上的所有 API.如果有更好的解决方案,请随时提及.

I need to create a simple notification which will be shown in notification bar along with the sound and icon if possible? I also need it to be compatitible with Android 2.2, so i found that NotificationCompat.Builder works with all APIs above 4. If there's a better solution, feel free to mention it.

推荐答案

NotificationCompat.Builder 是在所有 Android 版本上创建 Notifications 的最简单方法.您甚至可以使用 Android 4.1 提供的功能.如果您的应用在 Android >=4.1 的设备上运行,将使用新功能,如果在 Android <4.1 上运行,通知将是简单的旧通知.

The NotificationCompat.Builder is the most easy way to create Notifications on all Android versions. You can even use features that are available with Android 4.1. If your app runs on devices with Android >=4.1 the new features will be used, if run on Android <4.1 the notification will be an simple old notification.

要创建一个简单的通知,只需执行(参见 Android API 指南通知):

To create a simple Notification just do (see Android API Guide on Notifications):

NotificationCompat.Builder mBuilder =
    new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("My notification")
    .setContentText("Hello World!")
    .setContentIntent(pendingIntent); //Required on Gingerbread and below

您必须至少设置smallIconcontentTitlecontentText.如果您错过了一个通知,则不会显示.

You have to set at least smallIcon, contentTitle and contentText. If you miss one the Notification will not show.

注意:在 Gingerbread 及以下,您必须设置内容意图,否则将抛出 IllegalArgumentException.

Beware: On Gingerbread and below you have to set the content intent, otherwise a IllegalArgumentException will be thrown.

要创建一个什么都不做的意图,请使用:

To create an intent that does nothing, use:

final Intent emptyIntent = new Intent();
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, NOT_USED, emptyIntent, PendingIntent.FLAG_UPDATE_CURRENT);

您可以通过构建器添加声音,即来自 RingtoneManager 的声音:

You can add sound through the builder, i.e. a sound from the RingtoneManager:

mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))

Notification 通过 NotificationManager 添加到栏:

The Notification is added to the bar through the NotificationManager:

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(mId, mBuilder.build());

这篇关于如何使用 NotificationCompat.Builder 创建通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆