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.

asked Dec 16 '12 at 14:15
Vladimir

58041223

7 Answers

up vote 118 down vote accepted

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.

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

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

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);

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

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

The Notification is added to the bar through the NotificationManager:

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(mId, mBuilder.build());
answered Dec 16 '12 at 14:36
thaussma

8,36233339
  • 1
    Will it automatically show in notification bar? And how do i add sound? – Vladimir Dec 16 '12 at 14:43
  • 1
    i tried this, but the application crashes. Any ideas? – Vladimir Dec 16 '12 at 15:24
  •  
  • 1
    the problem is with this NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(mId, mBuilder.build()); – Vladimir Dec 22 '12 at 15:09
  • 3
    @Herrmann what is mId in notify method? – Dinesh T A Apr 12 '13 at 5:50
  • 2
    Thank you for You have to set at least smallIcon, contentTitle and contentText. If you miss one the Notification will not show. That line solved my headache. Didn't realize you HAD to set all of those. – zgc7009 Jun 10 '14 at 14:37

Working example:

    Intent intent = new Intent(ctx, HomeActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder b = new NotificationCompat.Builder(ctx); b.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("Hearty365")
.setContentTitle("Default notification")
.setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
.setDefaults(Notification.DEFAULT_LIGHTS| Notification.DEFAULT_SOUND)
.setContentIntent(contentIntent)
.setContentInfo("Info"); NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, b.build());
answered Dec 31 '14 at 13:30
Sumoanand

7,17213740
  • 1
    Hi, I've tried this code but I don't have any references to NotificationCompat.Builder... is it something missing? – nhenrique Feb 19 '15 at 16:31
  • 1
    Check to make sure you included the android support-v4 compatibility library. You might also try to clean and rebuild your project. – Jimmy Ilenloa May 26 '15 at 9:40
  • 1
    I have a problem i set the icon have green colour but when notification appear it changes to white automatically. – HUSNAIN SARWAR Jul 21 '16 at 6:56
  • 2
    @HUSNAINSARWAR because that happens on the API >21 (Lollipop and above). To resolve that please specify an icon for setSmallIcon(R.id.your_icon_small) and set a main icon like this mBuilder.setLargeIcon(BitmapFactory .decodeResource(context.getResources(), R.drawable.icon)) for API >21. – sud007 Jan 12 '17 at 6:22
  •  
  •  
    This will not work when you want to show it at android 8 and when the app is opened – Ultimo_m Aug 2 at 16:20

I make this method and work fine. (tested in android 6.0.1)

public void notifyThis(String title, String message) {
NotificationCompat.Builder b = new NotificationCompat.Builder(this.context);
b.setAutoCancel(true)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.favicon32)
.setTicker("{your tiny message}")
.setContentTitle(title)
.setContentText(message)
.setContentInfo("INFO"); NotificationManager nm = (NotificationManager) this.context.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(1, b.build());
}

Notification in depth

CODE

Intent intent = new Intent(this, SecondActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,0); NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.your_notification_icon)
.setContentTitle("Notification Title")
.setContentText("Notification ")
.setContentIntent(pendingIntent ); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, mBuilder.build());

Depth knowledge

Notification can be build using Notification. Builder or NotificationCompat.Builder classes.
But if you want backward compatibility you should use NotificationCompat.Builder class as it is part of v4 Support library as it takes care of heavy lifting for providing consistent look and functionalities of Notification for API 4 and above.

Core Notification Properties

A notification has 4 core properties (3 Basic display properties + 1 click action property)

  • Small icon
  • Title
  • Text
  • Button click event (Click event when you tap the notification )

Button click event is made optional on Android 3.0 and above. It
means that you can build your notification using only display properties
if your minSdk targets Android 3.0 or above. But if you want your
notification to run on older devices than Android 3.0 then you must
provide Click event otherwise you will see IllegalArgumentException.

Notification Display

Notification are displayed by calling notify() method of NotificationManger class

notify() parameters

There are two variants available for notify method

notify(String tag, int id, Notification notification)

or

notify(int id, Notification notification)

notify method takes an integer id to uniquely identify your notification. However, you can also provide an optional String tag for further identification of your notification in case of conflict.

This type of conflict is rare but say, you have created some library and other developers are using your library. Now they create their own notification and somehow your notification and other dev's notification id is same then you will face conflict.

Notification after API 11 (More control)

API 11 provides additional control on Notification behavior

  • Notification Dismissal
    By default, if a user taps on notification then it performs the assigned
    click event but it does not clear away the notification. If you want
    your notification to get cleared when then you should add this

    mBuilder.setAutoClear(true);

  • Prevent user from dismissing notification
    A user may also dismiss the notification by swiping it. You can disable
    this default behavior by adding this while building your notification

    mBuilder.setOngoing(true);

  • Positioning of notification
    You can set the relative priority to your notification by

    mBuilder.setOngoing(int pri);

If your app runs on lower API than 11 then your notification will
work without above mentioned additional features. This is the advantage
to choosing NotificationCompat.Builder over Notification.Builder

Notification after API 16 (More informative)

With the introduction of API 16, notifications were given so many new features
Notification can be so much more informative.
You can add a bigPicture to your logo. Say you get a message from a
person now with the mBuilder.setLargeIcon(Bitmap bitmap) you can show
that person's photo. So in the statusbar you will see the icon when you
scroll you will see the person photo in place of the icon.
There are other features too

  • Add a counter in the notification
  • Ticker message when you see the notification for the first time
  • Expandable notification
  • Multiline notification and so on
answered Mar 9 at 4:51

Rohit Singh

2,37812131

You can try this code this works fine for me:

    NotificationCompat.Builder mBuilder= new NotificationCompat.Builder(this);

    Intent i = new Intent(noti.this, Xyz_activtiy.class);
PendingIntent pendingIntent= PendingIntent.getActivity(this,0,i,0); mBuilder.setAutoCancel(true);
mBuilder.setDefaults(NotificationCompat.DEFAULT_ALL);
mBuilder.setWhen(20000);
mBuilder.setTicker("Ticker");
mBuilder.setContentInfo("Info");
mBuilder.setContentIntent(pendingIntent);
mBuilder.setSmallIcon(R.drawable.home);
mBuilder.setContentTitle("New notification title");
mBuilder.setContentText("Notification text");
mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)); NotificationManager notificationManager= (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(2,mBuilder.build());

simple way for make notifications

 NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher) //icon
.setContentTitle("Test") //tittle
.setAutoCancel(true)//swipe for delete
.setContentText("Hello Hello"); //content
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(1, builder.build()
);
answered May 31 at 23:06

Use this code

            Intent intent = new Intent(getApplicationContext(), SomeActvity.class);
PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(),
(int) System.currentTimeMillis(), intent, 0); NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.your_notification_icon)
.setContentTitle("Notification title")
.setContentText("Notification message!")
.setContentIntent(pIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, mBuilder.build());
 
https://stackoverflow.com/questions/13902115/how-to-create-a-notification-with-notificationcompat-builder

How to create a notification with NotificationCompat.Builder?AAAA的更多相关文章

  1. Android开发——Notification通知的使用及NotificationCopat.Builder常用设置API

    想要看全部设置的请看这一篇 [转]NotificationCopat.Builder全部设置 常用设置: 设置属性 说明 setAutoCancel(boolean autocancel) 设置点击信 ...

  2. Android notification的使用

    notification出现在通知栏中的提示,特别是在4.0以后改进了不少,这里讲得都是基于4.0及4.1以后的. 分类: 1.普通Notification 2.大布局Notification 图1 ...

  3. Notification

    一:普通Notification 1.内容标题setContentTitle(...) 2.大图标setLargeIcon(Bitmap) 3.内容setContentText(...) 4.内容附加 ...

  4. Android Wear 开发入门——怎样创建一个手机与可穿戴设备关联的通知(Notification)

    创建通知 为了创建在手机与可穿戴设备中都能展现的通知,能够使用 NotificationCompat.Builder.通过该类创建的通知,系统会处理该通知是否展如今手机或者穿戴设备中. 导入必要的类库 ...

  5. android wear开发:为可穿戴设备创建一个通知 - Creating a Notification for Wearables

    注:本文内容来自:https://developer.android.com/training/wearables/notifications/creating.html 翻译水平有限,如有疏漏,欢迎 ...

  6. Android Notification 消息通知 相关资料.md

    目录 Android Notification 消息通知 相关资料 Android 5.0 Lollipop (API 21)无法正常显示通知图标,只能看到一个白色方块或灰色方块的问题 解决方案 参考 ...

  7. android笔记:Notification通知的使用

    通知(Notification),当某个应用程序希望向用户发出一些提示信息,而该应用程序又不在前台运行时,就可以借助通知来实现. 发出一条通知后,手机最上方的状态栏中会显示一个通知的图标,下拉状态栏后 ...

  8. Notification通知

    manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); button = (Button) fi ...

  9. Android自定义Notification并没有那么简单

    背景 最近需要实现一个自定义Notification的功能.网上找了找代码,解决方案就是通过RemoteViews来实现.但是在实现过程中遇到不少问题,网上也没有很好的文章描述这些问题,所以在这里做个 ...

随机推荐

  1. (转)javascript日期格式化扩展

    转自:http://blog.csdn.net/vbangle/article/details/5643091 javascript Date format(js日期格式化)   方法一:这个很不错, ...

  2. 【Python】Webpy

    http://webpy.org/install.zh-cn 官网学习,对于No socket could be created 一般是默认的8080端口已经被某些服务占用,可以换一个端口.

  3. vue生成图片验证码

    最近做项目接触Vue,前端生成验证码.原理其实很简单,首先是生成随机数,然后用canvas绘制. 网上有一些现成的资料,没必要重复造轮子,我是在他们基础上完善了父组件,简化了子组件的调用: ident ...

  4. (转)Unity笔记之编辑器(BeginFadeGroup、BeginHorizontal、BeginScrollView) ... ...

    1. BeginFadeGroup(float value) 这是EditorGUILayout中的一个函数,用来隐藏/显示在它包含的组中的内容.value则是显示内容的量,范围是0-1 . 比较下未 ...

  5. 化学绘图软件ChemDraw真的什么都能干!

    今天要介绍的就是一款无所不能的化学绘图软件——ChemDraw,绘制平面化学结构.生成立体化学模型.查询化学信息.编写化学脚本.计算化学数据等等,堪称化学界的必备神器. 化学软件ChemDraw免费获 ...

  6. 模拟ORA-26040: Data block was loaded using the NOLOGGING option

    我们知道通过设置nologging选项.能够加快oracle的某些操作的运行速度,这在运行某些维护任务时是非常实用的,可是该选项也非常危急,假设使用不当,就可能导致数据库发生ORA-26040错误. ...

  7. windows 中 Eclipse 打开当前文件所在文件夹

    默认情况下使用eclipse打开当前文件所在文件夹很麻烦,需要右键点击 Package Explorer 中的节点选择属性,然后复制路径,再打开资源管理器,然后再把路径粘贴进去.而MyEclipse一 ...

  8. 【BZOJ3875】[Ahoi2014&Jsoi2014]骑士游戏 SPFA优化DP

    [BZOJ3875][Ahoi2014&Jsoi2014]骑士游戏 Description  [故事背景] 长期的宅男生活中,JYY又挖掘出了一款RPG游戏.在这个游戏中JYY会扮演一个英勇的 ...

  9. 滚动监听: bootstrap 的scrollspy

    滚动监听 bootstrap 的scrollspy,需要借助.nav样式,活动的部分是加 .active类.本身导航没有position:fixed,需要自己加入 滚动监听.只有滚动和监听,只有默认锚 ...

  10. 局域网查看工具Lansee注册码

    相信好多人为查看局域网IP发愁,今天给大家推荐一个工具 lansee 猛戳下载