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

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

问题描述

我需要创建一个简单的通知,这将显示在通知栏中将伴随着声音和图标,如果可能的吗?我还需要它compatitible与Android 2.2,所以我发现NotificationCompat.Builder适用于所有的API上述4.如果有一个更好的解决方案,随时就别提了。

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.

推荐答案

的<一个href="http://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html">NotificationCompat.Builder最简单的方法来创建通知在所有的Andr​​oid版本。你甚至可以使用的功能,可与Android 4.1。如果您的应用程序与设备运行Android> = 4.1的新功能将被使用,如果运行在Android&LT; 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.

要创建一个简单的通知只是(见<一href="http://developer.android.com/guide/topics/ui/notifiers/notifications.html#SimpleNotification">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

您必须设置至少 smallIcon contentTitle contentText 。如果你错过了一个通知将不会显示。

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

请注意:在姜饼和下面你要设置内容的意图,否则抛出:IllegalArgumentException 将被抛出

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

要创建一个什么都不做内容的意图,用途:

To create a do-nothing content intent, use:

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

您添加声音低谷的建设者,即从RingtoneManager一个声音:

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

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

的通知被加入到条线槽NotificationManager:

The Notification is added to the bar trough the NotificationManager:

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

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

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