NotificationManagerService笔记

Notification相关分析是基于5.0的代码。

    我们知道应用程序如果要在通知栏弹一个消息需要加上类似于下面这样的一段代码,看起来只有几行代码,实际上有两个比较大的框架在里面。一个是通过PendingIntent的静态函数getActivity()获取一个PendingIntent对象;一个是获取NotificationManagerService的服务代理对象调用notify()来post一个消息出去。

        long when = System.currentTimeMillis();
        notification = new Notification(R.drawable.ic_launcher, tickerText, when);
        Context context = getApplicationContext();
        CharSequence contentTitle = "通知栏标展开标题";
        CharSequence contentText = "通知栏展开详细内容";
        Intent notificationIntent = new Intent(this, TwoActivity1.class);
        notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);
        notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
        mNotificationManager.notify(1, notification);

    通过PendingIntent的静态函数getActivity()获取一个PendingIntent对象,这个里面其实做了几件隐蔽的事情:①调用了AMS的getIntentSender()函数,在AMS中创建了一个PendingIntentRecord记录块并保存在mIntentSenderRecords中;②PendingIntentRecord继承IIntentSender.Stub,getIntentSender()函数返回了PendingIntentRecord的binder引用,binder引用保存在PendingIntent.mTarget变量中;③上层应用的创建的Intent保存在PendingIntentRecord中供后续触发。

一、通知栏接口注册

    获取NotificationManagerService的服务代理对象调用notify()来post一个消息到通知栏显示,这个里面包含了应用把消息发送到系统中去、系统找到通知栏相关的接口并发送到通知栏显示。我们先来研究通知栏给系统提供了什么接口,及是如何将接口注册到系统中去的。很容易发现INotificationListenerWrapper类就是系统跟通知栏的交互类,INotificationListenerWrapper的本地对象保存在SystemUI中,binder引用会通过NotificationListenerService.registerAsSystemService()函数传递到系统服务中去,系统服务会为之创建一个ManagedServiceInfo对象来封装,这样系统服务来通知时就通过INotificationListenerWrapper的binder引用来将notification发送到通知栏显示。接口的注册过程如下:

《NotificationManagerService笔记》

相关类图:

《NotificationManagerService笔记》

注意通知栏注册下来的接口保存在ManagedServiceInfo.service中。

二、notification发送

《NotificationManagerService笔记》

    notification的发送也很简单,首先将消息发送到系统层,NotificationManagerService会为之创建一个NotificationRecord,保存在mNotificationList、mNotificationsByKey.put中,然后把ManagedServices.services中所有对象取出来(第一部分中为通知栏的INotificationListenerWrapper的binder引用创建了一个ManagedServiceInfo),然后调用onNotificationPosted()将通知发送给通知栏。

至此整个通知栏的显示通知框架就分析完了,具体细节需进一步仔细分析。

    原文作者:高山流水29
    原文地址: https://blog.csdn.net/guoqifa29/article/details/44133905
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞