【Android笔记】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);

 

Notification提供了丰富的手机提示方式:

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

     notification.tickerText = “hello”;

 

b)发出提示音,如:

     notification.defaults |= Notification.DEFAULT_SOUND;

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

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

 

c)手机振动,如:

     notification.defaults |= Notification.DEFAULT_VIBRATE;

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

     notification.vibrate = vibrate;

 

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

 

2. 通知的更新

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

 

3. 自定义通知视图

    这部分可以参考官方文档,讲的很详细了。

    AndroidSDK: docs/guide/topics/ui/notifiers/notifications.html

 

 

    参考文档:

    AndroidSDK1.5 : docs/guide/topics/ui/notifiers/notifications.html

    原文作者:ddna
    原文地址: https://blog.csdn.net/ddna/article/details/5122083
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞