Notification首页投稿(暂停使用,暂停投稿)程序员

# Notification 源码分析

2016-04-26  本文已影响378人  伍零一

引言

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

notification.jpg

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

Notification使用流程

现在我们使用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.

总结

上一篇 下一篇

猜你喜欢

热点阅读