# Notification 源码分析

引言

首先推荐个我整理的Notification样式

notification.jpg

Notification 在v7版本下从4.0后增加了Media Style. 今天我们分析下Notification在v7版本的源码。有助于我们针对不同版本的Notification做出合适样式选择。

Notification使用流程

现在我们使用Notification基本都是如下步骤:

  • NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
  • builder.setContentText

    .setSmallIcon

    .set...
  • Notification notification = builder.build();
  • notificationManager.notify(TYPE_BigText,notification);

我们看一下涉及到的类定义:

NotificationCompat

Helper for accessing features in Notification introduced after API level 4 in a backwards compatible fashion.

帮助Notification存储细节。

NotificationCompat.Builder

Builder class for NotificationCompat objects. Allows easier control over all the flags, as well as help constructing the typical notification layouts.

NotificationCompat对象的构造器类,构造Notification的样式。

当Notification构建好之后最后一个步骤:

NotificationManager

Post a notification to be shown in the status bar. If a notification with the same id has already been posted by your application and has not yet been canceled, it will be replaced by the updated information.

推送一个Notification到状态栏,如果应用中已经有了一个同样的Notification Id 将会被代替并更新。

Android support v7中的Notification相关类

v7对v4中的Notification进行扩展。

v7下NotificationCompat的定义

v7_NotificationCompat.jpg

然后我来看下NotificationCompat.Builder的定义

v7_NotificationCompat.Builder.jpg

Builder重写了v4下的getExtender() method,看下返回类型BuilderExtender 找到这样的定义

Interface for appcompat to extend v4 builder with media style.

appcompat 用来扩增v4 media style 的接口

我们再仔细看getExtender中的代码,针对不同版本sdk,返回不同版本的BuilderExtender.

针对ICE_CREAM_SANDWICH版本的BuilderExtender的代码看下:

v7_Notification_Extend.jpg

内部调用add方法进行整理样式

用table显示不同版本扩展mediastyle的method.

版本 | 整理样式的方法
------------- | -------------| -------------
LOLLIPOP (>=Android 5.1) | addMediaStyleToBuilderLollipop
JELLY_BEAN (>=Android4.1&&<Android 5.1) | addMediaStyleToBuilderIcs
ICE_CREAM_SANDWICH (>=Android4.0&&<Android 4.1) | addBigMediaStyleToBuilderJellybean
<Android 4.0 | 使用v4里的样式整理方法

从这个表格可以知道 4.0以后才出现的Media Style.

再看v4下Builder.build method

v4_NotificationCompat_Builder_build.jpg

最终是通过BuilderExtender构造Notification.

总结

  • Builder构造好样式后,会根据不同版本生成不同的BuilderExtender.
  • 如果你想知道Notification在不同版本上的限制,你只需要查看不同版本的BuilderExtender的区别即可。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容