android开发之Notification_通知栏消息

Notification简介

  Notification看名字就知道,是一个和提醒有关的东西,它通常和NotificationManager一块使用。具体来说,其主要功能如下。

  1.NotificationManager和Notification用来设置通知

  通知的设置等操作相对比较简单,基本的使用方式就是新建一个Notification对象,设置好通知的各项参数,然后使用系统后台运行的NotificationManager服务将通知发出来。基本步骤如下。

  1)得到NotificationManager,代码如下。

    String ns = Context.NOTIFICATION_SERVICE;

  NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

  2)创建一个新的Notification对象,代码如下。

    Notification notification = new Notification();

  notification.icon = R.drawable.notification_icon;

  也可以使用稍微复杂一些的方式创建Notification,代码如下。

   int icon = R.drawable.notification_icon; //通知图标

  CharSequence tickerText = "Hello"; //状态栏(Status Bar)显示的通知文本提示

  long when = System.currentTimeMillis(); //通知产生的时间,会在通知信息里显示

  Notification notification = new Notification(icon, tickerText, when);

  3)填充Notification的各个属性,代码如下。

    Context context = getApplicationContext();

  CharSequence contentTitle = "My notification";

  CharSequence contentText = "Hello World!";

  Intent notificationIntent = new Intent(this, MyClass.class);

  PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

  notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

  状态栏(Status Bar)显示的通知文本提示,例如:

    notification.tickerText = "hello";


  发出提示音,例如:

    notification.defaults |= Notification.DEFAULT_SOUND;

  notification.sound = Uri.parse("file:///sdcard/notification/ringer.mp3");

  notification.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6");

  手机振动,例如:

    notification.defaults |= Notification.DEFAULT_VIBRATE;

  long[] vibrate = {0,100,200,300};

  notification.vibrate = vibrate;

  LED灯闪烁,例如:

    notification.defaults |= Notification.DEFAULT_LIGHTS;

  notification.ledARGB = 0xff00ff00;

  notification.ledOnMS = 300;

  notification.ledOffMS = 1000;

  notification.flags |= Notification.FLAG_SHOW_LIGHTS;

  4)发送通知,代码如下。

    private static final int ID_NOTIFICATION = 1;

  mNotificationManager.notify(ID_NOTIFICATION, notification);

  5)实现点击后不消失

notification.flags = Notification.FLAG_NO_CLEAR;

2.更新通知

  如果需要更新一个通知,只需要在设置好Notification之后,再调用setLatestEventInfo,然后重新发送一次通知即可。

  为了更新一个已经触发过的Notification,传入相同的ID。用户既可以传入相同的Notification对象,也可以是一个全新的对象。只要ID相同,新的Notification对象会替换状态条图标和扩展的状态窗口的细节。

  另外,还可以使用ID来取消Notification,通过调用NotificationManager的cancel方法,代码如下。

  notificationManager.cancel(notificationRef);

  当取消一个Notification时,会移除它的状态条图标以及清除在扩展的状态窗口中的信息。

 

作者:jason0539

微博:http://weibo.com/2553717707

博客:http://blog.csdn.net/jason0539(转载请说明出处)

 

  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值