Android之Notification

 最近一直在研究 android 的Notification 栏,Notification 对于大家应该不陌生,下面将 Notification 的使用总结如下:
概述
     通过Activity和Service都可以创建一个Notification 实例, 一般情况下我们都是通过Services来创建一个Notification的,在本次实验中为了便于操作我们使用Activity来创建Notification,其创建过程是一样的,如果你要创建一个Notification,你需要使用如下两个类:
  • Notification:用于定义Notification栏的一些基本属性,比如图标,通知文本信息和一些基本设置(是否可以被清除、提示音等)。
  • NotificationManager:他是Android 的一个系统服务,用于管理我们的Notification。
主要代码
Activity:NotificationTestMain.java
  1. public class NotificationTestMain extends Activity {
  2.          private NotificationManager mNotificationManager;

  3.     /** Called when the activity is first created. */
  4.     @Override
  5.     public void onCreate(Bundle savedInstanceState) {
  6.         super.onCreate(savedInstanceState);
  7.         setContentView(R.layout.main);
  8.         Button button;
  9.         // Get the notification manager serivce.
  10.         mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  11.         
  12.         button = (Button) findViewById(R.id.happy);
  13.         button.setOnClickListener(new Button.OnClickListener() {
  14.                 @Override
  15.             public void onClick(View v) {
  16.                 setMood(R.drawable.stat_happy, R.string.happy,
  17.                         false);
  18.             }
  19.         });

  20.         button = (Button) findViewById(R.id.neutral);
  21.         button.setOnClickListener(new Button.OnClickListener() {
  22.                 @Override
  23.             public void onClick(View v) {
  24.                 setMood(R.drawable.stat_neutral, R.string.neutral,
  25.                         false);
  26.             }
  27.         });

  28.         button = (Button) findViewById(R.id.sad);
  29.         button.setOnClickListener(new Button.OnClickListener() {
  30.                 @Override
  31.             public void onClick(View v) {
  32.                 setMood(R.drawable.stat_sad, R.string.sad, false);
  33.             }
  34.         });
  35.     }
  36.     private void setMood(int moodId, int textId, boolean showTicker) {
  37.         // In this sample, we'll use the same text for the ticker and the expanded notification
  38.         CharSequence text = getText(textId);

  39.         // choose the ticker text
  40.         String tickerText = showTicker ? getString(textId) : null;

  41.         // Set the icon, scrolling text and timestamp
  42.         Notification notification = new Notification(moodId, tickerText,
  43.                 System.currentTimeMillis());

  44.         notification.flags = Notification.FLAG_ONGOING_EVENT; 
  45.         // Set the info for the views that show in the notification panel.
  46.        // notification.setLatestEventInfo(this, getText(R.string.mood),
  47.         ///               text, makeMoodIntent(moodId));

  48.         RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification_layout);
  49.         contentView.setImageViewResource(R.id.image, moodId);
  50.         contentView.setTextViewText(R.id.text, "Hello, this message is in a custom expanded view. My mood is:" +tickerText);
  51.         notification.contentView = contentView;
  52.         notification.contentIntent = makeMoodIntent(moodId);
  53.         
  54.         // Send the notification.
  55.         // We use a layout id because it is a unique number.  We use it later to cancel.
  56.         mNotificationManager.notify(R.layout.main, notification);
  57.     }
  58.     private PendingIntent makeMoodIntent(int moodId) {
  59.         // The PendingIntent to launch our activity if the user selects this
  60.         // notification.  Note the use of FLAG_UPDATE_CURRENT so that if there
  61.         // is already an active matching pending intent, we will update its
  62.         // extras (and other Intents in the array) to be the ones passed in here.
  63.             Intent intent = new Intent(this, NotificationTestMain.class).putExtra("moodimg", moodId);
  64.             intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK); 
  65.             
  66.         PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
  67.                         intent,
  68.                 PendingIntent.FLAG_UPDATE_CURRENT);
  69.         return contentIntent;
  70.     }

  71. }
复制代码
layout: Main.xml
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.         android:orientation="vertical" android:layout_width="fill_parent"
  4.         android:layout_height="fill_parent">
  5.         <TextView android:layout_width="fill_parent"
  6.                 android:layout_height="wrap_content" android:text="@string/mood" />
  7.         <Button android:text="@string/happy" android:id="@+id/happy" android:layout_height="wrap_content" android:layout_width="match_parent"></Button>
  8.         <Button android:text="@string/neutral" android:id="@+id/neutral" android:layout_height="wrap_content" android:layout_width="match_parent"></Button>
  9.         <Button android:text="@string/sad" android:id="@+id/sad" android:layout_height="wrap_content" android:layout_width="match_parent"></Button>

  10. </LinearLayout>
复制代码
Layout:custom_notification_layout.xml
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2.               android:orientation="horizontal"
  3.               android:layout_width="fill_parent"
  4.               android:layout_height="fill_parent"
  5.               android:padding="3dp"
  6.               >
  7.     <ImageView android:id="@+id/image"
  8.               android:layout_width="wrap_content"
  9.               android:layout_height="fill_parent"
  10.               android:layout_marginRight="10dp"
  11.               />
  12.     <TextView android:id="@+id/text"
  13.               android:layout_width="wrap_content"
  14.               android:layout_height="fill_parent"
  15.               android:textColor="#000"
  16.               />
  17. </LinearLayout>
复制代码


String: String.xml
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3.     <string name="hello">Hello World, NotificationTestMain!</string>
  4.     <string name="app_name">NotificationTest</string>
  5.     <string name="mood">My Mood</string>
  6.     <string name="happy">I\'m happy</string>
  7.     <string name="sad">I\'m sad</string>
  8.     <string name="neutral">I\'m ok</string>
  9. </resources>
复制代码
Drawable:

关键代码分析
  1. mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
复制代码
通过getSystemService得到系统服务NotificationManager。
  1.         // Set the icon, scrolling text and timestamp
  2.         Notification notification = new Notification(moodId, tickerText,
  3.                 System.currentTimeMillis());
复制代码
创建Notification 实例,并制定Notification 在状态栏上的图标,提示文字和时间。
  1. notification.flags = Notification.FLAG_ONGOING_EVENT;
复制代码
设置Notification的flags,此处主要有以下几个flags可选:
  • FLAG_AUTO_CANCEL:表示在点击Clear后可以清除Notification
  • FLAG_ONGOING_EVENT:表示程序一直在运行,可以是前台也可以是后台
  • FLAG_NO_CLEAR:表示Notification信息不能被清除掉
更多的选项信息参见 Creating Status Bar Notifications
  1.     private PendingIntent makeMoodIntent(int moodId) {
  2.         // The PendingIntent to launch our activity if the user selects this
  3.         // notification.  Note the use of FLAG_UPDATE_CURRENT so that if there
  4.         // is already an active matching pending intent, we will update its
  5.         // extras (and other Intents in the array) to be the ones passed in here.
  6.             Intent intent = new Intent(this, NotificationTestMain.class).putExtra("moodimg", moodId);
  7.             intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK); 
  8.             
  9.         PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
  10.                         intent,
  11.                 PendingIntent.FLAG_UPDATE_CURRENT);
  12.         return contentIntent;
  13.     }
复制代码
此处代码主要用于创建一个PendingIntent ,PendingIntent 是对Intent的包装,主要用于在用户点击Notification后的动作,此处我们为什么要使用PendingIntent 呢?大家都知道使用Intent可以启动Activity , Service 或发送Broadcast,当用户点击一个Notification后,由系统发出一条Intent,如果我们不告知此Intent用于启动什么的话,系统是不知道此Intent是用来启动Activity , Service 还是发送Broadcast。
在上述代码中我们先创建一个Intent对象,让后再用PendingIntent对其封装。
注意在创建Intent对象的时候一定要设置其Flags,其中Intent.FLAG_ACTIVITY_NEW_TASK 标记表示启动一个新的Activity,系统会检查当前所有已创建的Task中是否有该要启动的Activity的Task,若有,则在该Task上创建Activity,若没有则新建具有该Activity属性的Task,并在该新建的Task上创建Activity,而 Intent.FLAG_ACTIVITY_CLEAR_TOP 表示如果在当前Task中,有要启动的Activity,那么把该Acitivity之前的所有Activity都关掉,并把此Activity置前以避免创建Activity的实例,
更多关于Activity Task的信息可以参见: Tasks and Back Stack

  1. // Set the info for the views that show in the notification panel.
  2. notification.setLatestEventInfo(this, getText(R.string.mood),
  3. text, makeMoodIntent(moodId));

  4. /*RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification_layout);
  5. contentView.setImageViewResource(R.id.image, moodId);
  6. contentView.setTextViewText(R.id.text, "Hello, this message is in a custom expanded view. My mood is:" +tickerText);
  7. notification.contentView = contentView;
  8. notification.contentIntent = makeMoodIntent(moodId);*/

  9. // Send the notification.
  10. // We use a layout id because it is a unique number. We use it later to cancel.
  11. mNotificationManager.notify(R.layout.main, notification);
复制代码
做完上述操作后我们就可以使用setLatestEventInfo()设置Notification的信息,并用notify()更新Notification显示。
在设置Notification信息的时候我们可以使用系统默认的样式,通过调用setLatestEventInfo()进行设置。我们也可以使用自定义的样式,通过创建RemoteViews ,这样我们就可以定义Notification的样式了,比如我们可以在Notification中显示精度条等。注意RemoteViews 和setLatestEventInfo()不能同时使用的,如果同时使用,后使用的会覆盖前面使用。
这样我们就显示出了我们的通知栏了,当然通栏还可以进行更多的设置,比如我们可以设置有新通知是播放声音,震动等,要达到这种效果我们只需要为我们的Notification对象设置相应的属性
添加提示音:
  1. notification.defaults |= Notification.DEFAULT_SOUND;
  2. notification.sound = Uri.parse("url for sound);
复制代码
添加提示音只需设置defaults属性为 Notification.DEFAULT_SOUND即可。然后添加播放的声音,声音可以来自
存储卡,也可以来自于媒体库,通过contentprovider获取。
如果我们想让声音重复播放可以设置
notification.flags |=
Notification.FLAG_INSISTENT;这样声音就会重复播放,知道用户点击通知后才停止。
添加震动:
  1. notification.defaults |= Notification.DEFAULT_VIBRATE;
  2. long[] vibrate = {0,100,200,300};
  3. notification.vibrate = vibrate
复制代码

和添加声音一样我们只需设置defaults属性为Notification.DEFAULT_VIBRATE即可,我们用一个long形的
数组来表示震动,第一个值表示开始震动的时间,第二个值表示第一次震动的时长,第三个值下一次震动的
时间以此类推,这个数组可以按照你需要进行设置,但是我们不能设置重复震动。


当然要达到震动效果我们需要相应的权限
  1. <uses-permission android:name="android.permission.VIBRATE"/>
复制代码
添加屏幕闪烁:
  1. notification.defaults |= Notification.DEFAULT_LIGHTS;
  2. notification.ledARGB = 0xff00ff00;
  3. notification.ledOnMS = 300;
  4. notification.ledOffMS = 1000;
  5. notification.flags |= Notification.FLAG_SHOW_LIGHTS;
复制代码
同样我们只需设置defaults 为 Notification.DEFAULT_LIGHTS即可,ledARGB屏幕闪烁的颜色,ledOnMS 和ledOffMS 表示闪烁开始结束时间,最后我们添加flags为Notification.FLAG_SHOW_LIGHTS。
当然上述效果你也可同时使用,你可以设置即震动也播放声音。 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值