当前位置: 代码迷 >> Android >> Android Notification详解——创设notification
  详细解决方案

Android Notification详解——创设notification

热度:37   发布时间:2016-05-01 13:42:40.0
Android Notification详解——创建notification

最近需要给项目添加各种通知,通知一多,再加上各种设备上调试,总是出现各种意想不到的问题,索性把Notification的API Guide全部看了一遍,顺便做点记录。

?

首先简单复习下怎么创建一个Notification。创建通知需要两个比较重要的类:Notification和NotificationManager

?

Notification?类用来定义状态栏通知的各种属性,比如图标、消息、显示通知时是否需要声音、震动等。

NotificationManager 类是一个Android系统的服务,它用来管理所有的通知。

?

?

下面的代码用来创建一个简单的通知:

?

// 获取NotificationManager的引用NotificationManager mNM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);	// 创建一个Notification对象int icon = R.drawagle.notification_icon;CharSequence tickerText = "Hello";long when = System.currentTimeMills();Notification notification = new Notification(icon, tickerText, when);notification.flags |= Notification.DEFAULT_ALL;// 定义Notification的title、message、和pendingIntentContext 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);// 通知状态栏显示Notificationprivate static final int HELLO_ID = 1;mNM.notify(HELLO_ID, notification);
?

下面详细讨论创建一个Notification需要考虑些什么问题

?

一个通知必须包含如下的内容:

?

  1. 状态栏的图标
  2. 一个title和一个message(如果是自定义的layout,就不需要这项)
  3. PendingIntent,当点击通知时,该Intent会被触发

另外有一些可选的选项:

  1. ticker-text,就是当通知来时,在status bar上滚动的内容
  2. 震动、声音、led灯指示

创建Notification对象需要使用Notification的构造函数

?

Notification notification = Notification(int icon, CharSequence tickerText, long when);
??

使用下面的函数创建PendingIntent

?

PendingIntent contentIntent = PendingIntent.getActivity (Context context, int requestCode, Intent intent, int flags);
??

然后使用下面的函数设置创建好的Notification对象

?

notification.setLatestEventInfo(Context context, CharSequence  contentTitle, CharSequence  contentText, PendingIntent contentIntent);
??

我们可以定义notification的各种属性,比如声音、震动等

为notification添加一个声音:

?

notification.defaults |= Notification.DEFAULT_SOUND; //使用用户设置的默认声音

?或者

notification.sound = Uri.parse("file:///sdcard/notification/ringer.mp3"); //使用一个URI指向一个特定的音频文件作为消息声音

?或者

notification.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6"); //使用系统提供的铃音

?

为notification添加震动:

?

notification.defaults |= Notification.DEFAULT_VIBRATE; //使用用户设置

?或者

long[] vibrate = {0,100,200,300};notification.vibrate = vibrate; //使用自定义的震动效果
?

为notification添加led指示:

notification.defaults |= Notification.DEFAULT_LIGHTS; //使用用户设置

?或者

notification.ledARGB = 0xff00ff00;notification.ledOnMS = 300;notification.ledOffMS = 1000;notification.flags |= Notification.FLAG_SHOW_LIGHTS; //自定义效果
?

另外其他的属性可以参考Notification的文档?http://developer.android.com/reference/android/app/Notification.html

?

  相关解决方案