全面了解 Android Notification

satan0103 7年前
   <p>最近时不时地有人问我这样或那样的通知如何实现,所以本文将根据个人经验对Notification做个总结,以供参考!</p>    <h3>什么是通知(Notification)</h3>    <p>通知是一个可以在应用程序正常的用户界面之外显示给用户的消息。</p>    <p>通知发出时,它首先出现在状态栏的通知区域中,用户打开通知抽屉可查看通知详情。通知区域和通知抽屉都是用户可以随时查看的系统控制区域。</p>    <p>作为安卓用户界面的重要组成部分,通知有自己的设计指南。在Android 5.0(API level 21)中引入的 <a href="/misc/goto?guid=4959666604437130923" rel="nofollow,noindex">Material Design</a> 的变化是特别重要的,更多信息请阅读 <a href="/misc/goto?guid=4958533902770981295" rel="nofollow,noindex">通知设计指南</a> 。</p>    <h3>如何创建通知</h3>    <p>随着Android系统不断升级,Notification的创建方式也随之变化,主要变化如下:</p>    <p>Android 3.0之前</p>    <p>Android 3.0 (API level 11)之前,使用 new Notification() 方式创建通知:</p>    <pre>  <code class="language-java">NotificationManager mNotifyMgr =         (NotificationManager) getSystemService(NOTIFICATION_SERVICE);  PendingIntent contentIntent = PendingIntent.getActivity(        this, 0, new Intent(this, ResultActivity.class), 0);    Notification notification = new Notification(icon, tickerText, when);  notification.setLatestEventInfo(this, title, content, contentIntent);    mNotifyMgr.notify(NOTIFICATIONS_ID, notification);</code></pre>    <p>Android 3.0 (API level 11)及更高版本</p>    <p>Android 3.0开始弃用 new Notification() 方式,改用 Notification.Builder() 来创建通知:</p>    <pre>  <code class="language-java">NotificationManager mNotifyMgr =         (NotificationManager) getSystemService(NOTIFICATION_SERVICE);  PendingIntent contentIntent = PendingIntent.getActivity(        this, 0, new Intent(this, ResultActivity.class), 0);    Notification notification = new Notification.Builder(this)              .setSmallIcon(R.drawable.notification_icon)              .setContentTitle("My notification")              .setContentText("Hello World!")              .setContentIntent(contentIntent)              .build();// getNotification()    mNotifyMgr.notify(NOTIFICATIONS_ID, notification);</code></pre>    <p>这里需要注意: "build()" 是Androdi 4.1(API level 16)加入的,用以替代</p>    <p>"getNotification()"。API level 16开始弃用"getNotification()"</p>    <p>兼容Android 3.0之前的版本</p>    <p>为了兼容 API level 11 之前的版本, v4 Support Library 中提供了</p>    <p>NotificationCompat.Builder() 这个替代方法。它与 Notification.Builder() 类似,二者没有太大区别。</p>    <pre>  <code class="language-java">NotificationManager mNotifyMgr =         (NotificationManager) getSystemService(NOTIFICATION_SERVICE);  PendingIntent contentIntent = PendingIntent.getActivity(        this, 0, new Intent(this, ResultActivity.class), 0);    NotificationCompat.Builder mBuilder =         new NotificationCompat.Builder(this)              .setSmallIcon(R.drawable.notification_icon)              .setContentTitle("My notification")              .setContentText("Hello World!")              .setContentIntent(contentIntent);    mNotifyMgr.notify(NOTIFICATIONS_ID, mBuilder.build());</code></pre>    <p>注:除特别说明外,本文将根据 NotificationCompat.Builder() 展开解析,<br> Notification.Builder()类似。</p>    <h3>通知基本用法</h3>    <p>通知的必要属性</p>    <p>一个通知必须包含以下三项属性:</p>    <ul>     <li>小图标,对应 setSmallIcon()</li>     <li>通知标题,对应 setContentTitle()</li>     <li>详细信息,对应 setContentText()</li>    </ul>    <p>其他属性均为可选项,更多属性方法请参考 <a href="/misc/goto?guid=4959665642427557798" rel="nofollow,noindex">NotificationCompat.Builder</a> 。</p>    <p>尽管其他都是可选的,但一般都会为通知添加至少一个动作(Action),这个动作可以是跳转到Activity、启动一个Service或发送一个Broadcas等。 通过以下方式为通知添加动作:</p>    <ul>     <li>使用PendingIntent</li>     <li>通过大视图通知的 Action Button //仅支持Android 4.1 (API level 16)及更高版本,稍后会介绍</li>    </ul>    <p>创建通知</p>    <p>1、实例化一个NotificationCompat.Builder对象</p>    <pre>  <code class="language-java">NotificationCompat.Builder mBuilder =         new NotificationCompat.Builder(this)              .setSmallIcon(R.drawable.notification_icon)              .setContentTitle("My notification")              .setContentText("Hello World!");</code></pre>    <p>NotificationCompat.Builder自动设置的默认值:</p>    <ul>     <li>priority: PRIORITY_DEFAULT</li>     <li>when: System.currentTimeMillis()</li>     <li>audio stream: STREAM_DEFAULT</li>    </ul>    <p>2、定义并设置一个通知动作(Action)</p>    <pre>  <code class="language-java">Intent resultIntent = new Intent(this, ResultActivity.class);  PendingIntent resultPendingIntent = PendingIntent.getActivity(              this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);  mBuilder.setContentIntent(resultPendingIntent);</code></pre>    <p>3、生成 Notification 对象</p>    <pre>  <code class="language-java">Notificatioin notification = mBuilder.build();</code></pre>    <p>4、使用 NotificationManager 发送通知</p>    <pre>  <code class="language-java">// Sets an ID for the notification  int mNotificationId = 001;    // Gets an instance of the NotificationManager service  NotificationManager mNotifyMgr =         (NotificationManager) getSystemService(NOTIFICATION_SERVICE);    // Builds the notification and issues it.  mNotifyMgr.notify(mNotificationId, notification);</code></pre>    <p>更新通知</p>    <p>更新通知很简单,只需再次发送相同ID的通知即可,如果之前的通知依然存在则会更新通知属性,如果之前通知不存在则重新创建。</p>    <p>示例代码:</p>    <pre>  <code class="language-java">NotificationManager mNotifyMgr =         (NotificationManager) getSystemService(NOTIFICATION_SERVICE);  // Sets an ID for the notification, so it can be updated  int notifyID = 1;  NotificationCompat.Builder mNotifyBuilder =         new NotificationCompat.Builder(this)            .setContentTitle("New Message")            .setContentText("You've received new messages.")            .setSmallIcon(R.drawable.ic_notify_status);    int numMessages = 0;  ...      mNotifyBuilder.setContentText("new content text")              .setNumber(++numMessages);      mNotifyMgr.notify(notifyID, mNotifyBuilder.build());  ...</code></pre>    <p>取消通知</p>    <p>取消通知有如下4种方式:</p>    <ul>     <li>点击通知栏的清除按钮,会清除所有可清除的通知</li>     <li>设置了 setAutoCancel() 或 FLAG_AUTO_CANCEL的通知,点击该通知时会清除它</li>     <li>通过 NotificationManager 调用 cancel() 方法清除指定ID的通知</li>     <li>通过 NotificationManager 调用 cancelAll() 方法清除所有该应用之前发送的通知</li>    </ul>    <h3>通知类型</h3>    <p>大视图通知</p>    <p>通知有两种视图:普通视图和大视图。</p>    <p>普通视图:</p>    <p><img src="https://simg.open-open.com/show/8cf192aaf1bc0e6df73afa4679c86940.png"></p>    <p>大视图:</p>    <p><img src="https://simg.open-open.com/show/9d32ca5119d45718c6e0d49956aaa304.png"></p>    <p>默认情况下为普通视图,可通过 NotificationCompat.Builder.setStyle() 设置大视图。</p>    <p>注: 大视图(Big Views)由Android 4.1(API level 16)开始引入,且仅支持Android 4.1及更高版本。</p>    <p>构建大视图通知</p>    <p>以上图为例:</p>    <p>1、构建Action Button的PendingIntent</p>    <pre>  <code class="language-java">Intent dismissIntent = new Intent(this, PingService.class);  dismissIntent.setAction(CommonConstants.ACTION_DISMISS);  PendingIntent piDismiss = PendingIntent.getService(        this, 0, dismissIntent, 0);    Intent snoozeIntent = new Intent(this, PingService.class);  snoozeIntent.setAction(CommonConstants.ACTION_SNOOZE);  PendingIntent piSnooze =         PendingIntent.getService(this, 0, snoozeIntent, 0);</code></pre>    <p>2、构建NotificatonCompat.Builder对象</p>    <pre>  <code class="language-java">NotificationCompat.Builder builder =         new NotificationCompat.Builder(this)            .setSmallIcon(R.drawable.ic_stat_notification)            .setContentTitle(getString(R.string.notification))            .setContentText(getString(R.string.ping))            .setDefaults(Notification.DEFAULT_ALL)          // 该方法在Android 4.1之前会被忽略            .setStyle(new NotificationCompat.BigTextStyle()                  .bigText(msg))          //添加Action Button          .addAction (R.drawable.ic_stat_dismiss,                  getString(R.string.dismiss), piDismiss)          .addAction (R.drawable.ic_stat_snooze,                  getString(R.string.snooze), piSnooze);</code></pre>    <p>3、其他步骤与普通视图相同</p>    <p>进度条通知</p>    <ul>     <li> <p>明确进度的进度条</p> <p>使用 setProgress(max, progress, false) 来更新进度。</p> <p>max: 最大进度值</p> <p>progress: 当前进度</p> <p>false: 是否是不明确的进度条</p> <p>模拟下载过程,示例如下:</p> <pre>  <code class="language-java">int id = 1;  ...  mNotifyManager = (NotificationManager)       getSystemService(Context.NOTIFICATION_SERVICE);  mBuilder = new NotificationCompat.Builder(this);  mBuilder.setContentTitle("Picture Download")      .setContentText("Download in progress")      .setSmallIcon(R.drawable.ic_notification);    // Start a lengthy operation in a background thread  new Thread(      new Runnable() {          @Override          public void run() {              int incr;              for (incr = 0; incr <= 100; incr+=5) {                  mBuilder.setProgress(100, incr, false);                  mNotifyManager.notify(id, mBuilder.build());                  try {                      // Sleep for 5 seconds                      Thread.sleep(5*1000);                  } catch (InterruptedException e) {                      Log.d(TAG, "sleep failure");                  }              }              mBuilder.setContentText("Download complete")//下载完成                                 .setProgress(0,0,false);    //移除进度条              mNotifyManager.notify(id, mBuilder.build());          }      }  ).start();</code></pre> <p><img src="https://simg.open-open.com/show/f4a516d6f658209656a480c35d7de411.png"></p> <p>上图,分别为下载过程中进度条通知 和 下载完成移除进度条后的通知。</p> </li>     <li> <p>不确定进度的进度条</p> <p>使用 setProgress(0, 0, true) 来表示进度不明确的进度条</p> <p>mBuilder.setProgress(0, 0, true); mNotifyManager.notify(id, mBuilder.build());</p> <p><img src="https://simg.open-open.com/show/824f63e4eeabe15d84e685f3bccc1bba.png"></p> </li>    </ul>    <p>浮动通知(Heads-up Notifications)</p>    <p>Android 5.0(API level 21)开始,当屏幕未上锁且亮屏时,通知可以以小窗口形式显示。用户可以在不离开当前应用前提下操作该通知。</p>    <p>如图:</p>    <p><img src="https://simg.open-open.com/show/aa6a056e90350d6a32f50f67ae491e56.png"></p>    <pre>  <code class="language-java">NotificationCompat.Builder mNotifyBuilder =       new NotificationCompat.Builder(this)          .setContentTitle("New Message")          .setContentText("You've received new messages.")          .setSmallIcon(R.drawable.ic_notify_status)          .setFullScreenIntent(pendingIntent, false);</code></pre>    <p>以下两种情况会显示浮动通知:</p>    <ul>     <li>setFullScreenIntent(),如上述示例。</li>     <li>通知拥有高优先级且使用了铃声和振动</li>    </ul>    <p>锁屏通知</p>    <p>Android 5.0(API level 21)开始,通知可以显示在锁屏上。用户可以通过设置选择是否允许敏感的通知内容显示在安全的锁屏上。</p>    <p>你的应用可以通过 setVisibility() 控制通知的显示等级:</p>    <ul>     <li>VISIBILITY_PRIVATE : 显示基本信息,如通知的图标,但隐藏通知的全部内容</li>     <li>VISIBILITY_PUBLIC : 显示通知的全部内容</li>     <li>VISIBILITY_SECRET : 不显示任何内容,包括图标</li>    </ul>    <p>自定义通知</p>    <p>Android系统允许使用 <a href="/misc/goto?guid=4959730140002703441" rel="nofollow,noindex">RemoteViews</a> 来自定义通知。</p>    <p>自定义普通视图通知高度限制为64dp,大视图通知高度限制为256dp。同时,建议自定义通知尽量简单,以提高兼容性。</p>    <p>自定义通知需要做如下操作:</p>    <p>1、创建自定义通知布局</p>    <p>2、使用RemoteViews定义通知组件,如图标、文字等</p>    <p>3、调用 setContent() 将RemoteViews对象绑定到NotificationCompat.Builder</p>    <p>4、同正常发送通知流程</p>    <p>注意: 避免为通知设置背景,因为兼容性原因,有些文字可能看不清。</p>    <p>定义通知文本样式</p>    <p>通知的背景颜色在不同的设备和版本中有所不同,Android2.3开始,系统定义了一套标准通知文本样式,建议自定义通知使用标准样式,这样有助于通知文本可见。</p>    <p>通知文本样式:</p>    <pre>  <code class="language-java">Android 5.0之前可用:  android:style/TextAppearance.StatusBar.EventContent.Title    // 通知标题样式    android:style/TextAppearance.StatusBar.EventContent             // 通知内容样式      Android 5.0及更高版本:    android:style/TextAppearance.Material.Notification.Title         // 通知标题样式    android:style/TextAppearance.Material.Notification                  // 通知内容样式</code></pre>    <p>更多通知的标准样式和布局,可参考源码 frameworks/base/core/res/res/layout 路径下的通知模版如:</p>    <pre>  <code class="language-java">Android 5.0之前:    notification_template_base.xml    notification_template_big_base.xml    notification_template_big_picture.xml    notification_template_big_text.xml      Android 5.0 及更高版本:    notification_template_material_base.xml    notification_template_material_big_base.xml    notification_template_material_big_picture.xml    notification_template_part_chronometer.xml    notification_template_progressbar.xml      等等。</code></pre>    <h3>保留Activity返回栈</h3>    <p>常规Activity</p>    <p>默认情况下,从通知启动一个Activity,按返回键会回到主屏幕。但某些时候有按返回键仍然留在当前应用的需求,这就要用到 TaskStackBuilder 了。</p>    <p>1、在manifest中定义Activity的关系</p>    <pre>  <code class="language-java">Android 4.0.3 及更早版本  <activity      android:name=".ResultActivity">      <meta-data          android:name="android.support.PARENT_ACTIVITY"          android:value=".MainActivity"/>  </activity>    Android 4.1 及更高版本  <activity      android:name=".ResultActivity"      android:parentActivityName=".MainActivity">  </activity></code></pre>    <p>2、创建返回栈PendingIntent</p>    <pre>  <code class="language-java">Intent resultIntent = new Intent(this, ResultActivity.class);  TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);  // 添加返回栈  stackBuilder.addParentStack(ResultActivity.class);  // 添加Intent到栈顶  stackBuilder.addNextIntent(resultIntent);  // 创建包含返回栈的pendingIntent  PendingIntent resultPendingIntent =          stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);  builder.setContentIntent(resultPendingIntent);  NotificationManager mNotificationManager =      (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  mNotificationManager.notify(id, builder.build());</code></pre>    <p>上述操作后,从通知启动ResultActivity,按返回键会回到MainActivity,而不是主屏幕。</p>    <p>特殊Activity</p>    <p>默认情况下,从通知启动的Activity会在近期任务列表里出现。如果不需要在近期任务里显示,则需要做以下操作:</p>    <p>1、在manifest中定义Activity</p>    <pre>  <code class="language-java"><activity      android:name=".ResultActivity"      android:launchMode="singleTask"      android:taskAffinity=""      android:excludeFromRecents="true">  </activity></code></pre>    <p>2、构建PendingIntent</p>    <pre>  <code class="language-java">NotificationCompat.Builder builder = new NotificationCompat.Builder(this);  Intent notifyIntent = new Intent(this, ResultActivity.class);    // Sets the Activity to start in a new, empty task  notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK           | Intent.FLAG_ACTIVITY_CLEAR_TASK);    PendingIntent notifyPendingIntent =          PendingIntent.getActivity(this, 0, notifyIntent,           PendingIntent.FLAG_UPDATE_CURRENT);    builder.setContentIntent(notifyPendingIntent);  NotificationManager mNotificationManager =      (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  mNotificationManager.notify(id, builder.build());</code></pre>    <p>上述操作后,从通知启动ResultActivity,此Activity不会出现在近期任务列表中。</p>    <h3>通知常见属性和常量</h3>    <p>通知的提醒方式</p>    <p>1、声音提醒</p>    <ul>     <li>默认声音<br> notification.defaults |= Notification.DEFAULT_SOUND;</li>     <li>自定义声音<br> notification.sound = Uri.parse("file:///sdcard0/notification.ogg");</li>    </ul>    <p>2、震动提醒</p>    <ul>     <li>默认振动<br> notification.defaults |= Notification.DEFAULT_VIBRATE;</li>     <li>自定义振动<br> long[] vibrate = {100, 200, 300, 400}; //震动效果<br> // 表示在100、200、300、400这些时间点交替启动和关闭震动 notification.vibrate = vibrate;</li>    </ul>    <p>3、闪烁提醒</p>    <ul>     <li>默认闪烁<br> notification.defaults |= Notification.DEFAULT_LIGHTS;</li>     <li>自定义闪烁<br> notification.ledARGB = 0xff00ff00; // LED灯的颜色,绿灯<br> notification.ledOnMS = 300; // LED灯显示的毫秒数,300毫秒<br> notification.ledOffMS = 1000; // LED灯关闭的毫秒数,1000毫秒<br> notification.flags |= Notification.FLAG_SHOW_LIGHTS; // 必须加上这个标志</li>    </ul>    <p>常见的Flags</p>    <ul>     <li>FLAG_AUTO_CANCEL<br> 当通知被用户点击之后会自动被清除(cancel)</li>     <li>FLAG_INSISTENT<br> 在用户响应之前会一直重复提醒音</li>     <li>FLAG_ONGOING_EVENT<br> 表示正在运行的事件</li>     <li>FLAG_NO_CLEAR<br> 通知栏点击“清除”按钮时,该通知将不会被清除</li>     <li>FLAG_FOREGROUND_SERVICE<br> 表示当前服务是前台服务<br> 更多Notification属性详见 <a href="/misc/goto?guid=4959730140089213111" rel="nofollow,noindex">Notification</a> 。</li>    </ul>    <p>That's all! 更多通知知识点等待你来发掘,欢迎补充!</p>    <p>参考资料</p>    <p><a href="/misc/goto?guid=4959730140170072901" rel="nofollow,noindex">Notifications</a></p>    <p> </p>    <p>来自:http://www.jianshu.com/p/22e27a639787</p>    <p> </p>