欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android中的Notification机制深入理解

程序员文章站 2022-03-08 16:39:34
本文需要解决的问题 笔者最近正在做一个项目,里面需要用到 android notification 机制来实现某些特定需求。我正好通过这个机会研究一下 android...

本文需要解决的问题

笔者最近正在做一个项目,里面需要用到 android notification 机制来实现某些特定需求。我正好通过这个机会研究一下 android notification 相关的发送逻辑和接收逻辑,以及整理相关的笔记。我研究 notification 机制的目的是解决以下我在使用过程中所思考的问题:

  • 我们创建的 notification 实例最终以什么样的方式发送给系统?
  • 系统是如何接收到 notification 实例并显示的?
  • 我们是否能拦截其他 app 的 notification 并获取其中的信息?

什么是 android notification 机制?

notification,中文名翻译为通知,每个 app 可以自定义通知的样式和内容等,它会显示在系统的通知栏等区域。用户可以打开抽屉式通知栏查看通知的详细信息。在实际生活中,android notification 机制有很广泛的应用,例如 im app 的新消息通知,资讯 app 的新闻推送等等。

源码分析

本文的源码基于 android 7.0。

notification 的发送逻辑

一般来说,如果我们自己的 app 想发送一条新的 notification,可以参照以下代码:

notificationcompat.builder mbuilder =
  new notificationcompat.builder(this)
  .setsmallicon(r.drawable.notification_icon)
  .setwhen(system.currenttimemillis())
  .setcontenttitle("test notification title")
  .setcontenttext("test notification content!");
intent resultintent = new intent(this, resultactivity.class);

pendingintent contentintent =
  pendingintent.getactivity(
   this, 
   0, 
   resultintent, 
   pendingintent.flag_update_current
  );
mbuilder.setcontentintent(resultpendingintent);
notificationmanager mnotificationmanager =
 (notificationmanager) getsystemservice(context.notification_service);
// mid allows you to update the notification later on.
mnotificationmanager.notify(mid, mbuilder.build());

可以看到,我们通过 notificationcompat.builder 新建了一个 notification 对象,最后通过 notificationmanager#notify() 方法将 notification 发送出去。

notificationmanager#notify()

public void notify(int id, notification notification)
{
 notify(null, id, notification);
}

// 省略部分注释
public void notify(string tag, int id, notification notification)
{
 notifyasuser(tag, id, notification, new userhandle(userhandle.myuserid()));
}

/**
 * @hide
 */
public void notifyasuser(string tag, int id, notification notification, userhandle user)
{
 int[] idout = new int[1];
 inotificationmanager service = getservice();
 string pkg = mcontext.getpackagename();
 // fix the notification as best we can.
 notification.addfieldsfromcontext(mcontext, notification);
 if (notification.sound != null) {
  notification.sound = notification.sound.getcanonicaluri();
  if (strictmode.vmfileuriexposureenabled()) {
   notification.sound.checkfileuriexposed("notification.sound");
  }
 }
 fixlegacysmallicon(notification, pkg);
 if (mcontext.getapplicationinfo().targetsdkversion > build.version_codes.lollipop_mr1) {
  if (notification.getsmallicon() == null) {
   throw new illegalargumentexception("invalid notification (no valid small icon): "
     + notification);
  }
 }
 if (locallogv) log.v(tag, pkg + ": notify(" + id + ", " + notification + ")");
 final notification copy = builder.maybeclonestrippedfordelivery(notification);
 try {
  // !!!
  service.enqueuenotificationwithtag(pkg, mcontext.getoppackagename(), tag, id,
    copy, idout, user.getidentifier());
  if (locallogv && id != idout[0]) {
   log.v(tag, "notify: id corrupted: sent " + id + ", got back " + idout[0]);
  }
 } catch (remoteexception e) {
  throw e.rethrowfromsystemserver();
 }
}

我们可以看到,到最后会调用 service.enqueuenotificationwithtag() 方法,这里的是 service 是 inotificationmanager 接口。如果熟悉 aidl 等系统相关运行机制的话,就可以看出这里是代理类调用了代理接口的方法,实际方法实现是在 notificationmanagerservice 当中。

notificationmanagerservice#enqueuenotificationwithtag()

@override
public void enqueuenotificationwithtag(string pkg, string oppkg, string tag, int id,
   notification notification, int[] idout, int userid) throws remoteexception {
 enqueuenotificationinternal(pkg, oppkg, binder.getcallinguid(),
   binder.getcallingpid(), tag, id, notification, idout, userid);
}

void enqueuenotificationinternal(final string pkg, final string oppkg, final int callinguid,
  final int callingpid, final string tag, final int id, final notification notification,
  int[] idout, int incominguserid) {
 if (dbg) {
  slog.v(tag, "enqueuenotificationinternal: pkg=" + pkg + " id=" + id
    + " notification=" + notification);
 }
 checkcallerissystemorsameapp(pkg);
 final boolean issystemnotification = isuidsystem(callinguid) || ("android".equals(pkg));
 final boolean isnotificationfromlistener = mlisteners.islistenerpackage(pkg);

 final int userid = activitymanager.handleincominguser(callingpid,
   callinguid, incominguserid, true, false, "enqueuenotification", pkg);
 final userhandle user = new userhandle(userid);

 // fix the notification as best we can.
 try {
  final applicationinfo ai = getcontext().getpackagemanager().getapplicationinfoasuser(
    pkg, packagemanager.match_debug_triaged_missing,
    (userid == userhandle.user_all) ? userhandle.user_system : userid);
  notification.addfieldsfromcontext(ai, userid, notification);
 } catch (namenotfoundexception e) {
  slog.e(tag, "cannot create a context for sending app", e);
  return;
 }

 musagestats.registerenqueuedbyapp(pkg);

 if (pkg == null || notification == null) {
  throw new illegalargumentexception("null not allowed: pkg=" + pkg
    + " id=" + id + " notification=" + notification);
 }
 final statusbarnotification n = new statusbarnotification(
   pkg, oppkg, id, tag, callinguid, callingpid, 0, notification,
   user);

 // limit the number of notifications that any given package except the android
 // package or a registered listener can enqueue. prevents dos attacks and deals with leaks.
 if (!issystemnotification && !isnotificationfromlistener) {
  synchronized (mnotificationlist) {
   if(mnotificationsbykey.get(n.getkey()) != null) {
    // this is an update, rate limit updates only
    final float appenqueuerate = musagestats.getappenqueuerate(pkg);
    if (appenqueuerate > mmaxpackageenqueuerate) {
     musagestats.registeroverratequota(pkg);
     final long now = systemclock.elapsedrealtime();
     if ((now - mlastoverratelogtime) > min_package_overrate_log_interval) {
      slog.e(tag, "package enqueue rate is " + appenqueuerate
        + ". shedding events. package=" + pkg);
       mlastoverratelogtime = now;
     }
     return;
    }
   }

   int count = 0;
   final int n = mnotificationlist.size();
   for (int i=0; i<n; i++) {
    final notificationrecord r = mnotificationlist.get(i);
    if (r.sbn.getpackagename().equals(pkg) && r.sbn.getuserid() == userid) {
     if (r.sbn.getid() == id && textutils.equals(r.sbn.gettag(), tag)) {
      break; // allow updating existing notification
     }
     count++;
     if (count >= max_package_notifications) {
      musagestats.registerovercountquota(pkg);
      slog.e(tag, "package has already posted " + count
        + " notifications. not showing more. package=" + pkg);
      return;
     }
    }
   }
  }
 }

 // whitelist pending intents.
 if (notification.allpendingintents != null) {
  final int intentcount = notification.allpendingintents.size();
  if (intentcount > 0) {
   final activitymanagerinternal am = localservices
     .getservice(activitymanagerinternal.class);
   final long duration = localservices.getservice(
     deviceidlecontroller.localservice.class).getnotificationwhitelistduration();
   for (int i = 0; i < intentcount; i++) {
    pendingintent pendingintent = notification.allpendingintents.valueat(i);
    if (pendingintent != null) {
     am.setpendingintentwhitelistduration(pendingintent.gettarget(), duration);
    }
   }
  }
 }

 // sanitize inputs
 notification.priority = clamp(notification.priority, notification.priority_min,
   notification.priority_max);

 // setup local book-keeping
 final notificationrecord r = new notificationrecord(getcontext(), n);
 mhandler.post(new enqueuenotificationrunnable(userid, r));

 idout[0] = id;
}

这里代码比较多,但通过注释可以清晰地理清整个逻辑:

  • 首先检查通知发起者是系统进程或者是查看发起者发送的是否是同个 app 的通知信息,否则抛出异常;
  • 除了系统的通知和已注册的监听器允许入队列外,其他 app 的通知都会限制通知数上限和通知频率上限;
  • 将 notification 的 pendingintent 加入到白名单;
  • 将之前的 notification 进一步封装为 statusbarnotification 和 notificationrecord,最后封装到一个异步线程 enqueuenotificationrunnable 中

这里有一个点,就是 mhandler,涉及到切换线程,我们先跟踪一下 mhandler 是在哪个线程被创建。

mhandler 是 workerhandler 类的一个实例,在 notificationmanagerservice#onstart() 方法中被创建,而 notificationmanagerservice 是系统 service,所以 enqueuenotificationrunnable 的 run 方法会运行在 system_server 的主线程。

notificationmanagerservice.enqueuenotificationrunnable#run()

@override
public void run() {
 synchronized(mnotificationlist) {
  // 省略代码
  if (notification.getsmallicon() != null) {
   statusbarnotification oldsbn = (old != null) ? old.sbn : null;
   mlisteners.notifypostedlocked(n, oldsbn);
  } else {
   slog.e(tag, "not posting notification without small icon: " + notification);
   if (old != null && !old.iscanceled) {
    mlisteners.notifyremovedlocked(n);
   }
   // attention: in a future release we will bail out here
   // so that we do not play sounds, show lights, etc. for invalid
   // notifications
   slog.e(tag, "warning: in a future release this will crash the app: " + n.getpackagename());
  }
  buzzbeepblinklocked(r);
 }
}
  1. 省略的代码主要的工作是提取 notification 相关的属性,同时通知 notification ranking service,有新的 notification 进来,然后对所有 notification 进行重新排序;
  2. 然后到最后会调用 mlisteners.notifypostedlocked() 方法。这里 mlisteners 是 notificationlisteners 类的一个实例。

notificationmanagerservice.notificationlisteners#notifypostedlocked()  -> notificationmanagerservice.notificationlisteners#notifyposted()

public void notifypostedlocked(statusbarnotification sbn, statusbarnotification oldsbn) {
 // lazily initialized snapshots of the notification.
 trimcache trimcache = new trimcache(sbn);
 for (final managedserviceinfo info: mservices) {
  boolean sbnvisible = isvisibletolistener(sbn, info);
  boolean oldsbnvisible = oldsbn != null ? isvisibletolistener(oldsbn, info) : false;
  // this notification hasn't been and still isn't visible -> ignore.
  if (!oldsbnvisible && !sbnvisible) {
   continue;
  }
  final notificationrankingupdate update = makerankingupdatelocked(info);
  // this notification became invisible -> remove the old one.
  if (oldsbnvisible && !sbnvisible) {
   final statusbarnotification oldsbnlightclone = oldsbn.clonelight();
   mhandler.post(new runnable() {
    @override
    public void run() {
     notifyremoved(info, oldsbnlightclone, update);
    }
   });
   continue;
  }
  final statusbarnotification sbntopost = trimcache.forlistener(info);
  mhandler.post(new runnable() {
   @override
   public void run() {
    notifyposted(info, sbntopost, update);
   }
  });
 }
}

private void notifyposted(final managedserviceinfo info, final statusbarnotification sbn, notificationrankingupdate rankingupdate) {
 final inotificationlistener listener = (inotificationlistener) info.service;
 statusbarnotificationholder sbnholder = new statusbarnotificationholder(sbn);
 try {
  listener.onnotificationposted(sbnholder, rankingupdate);
 } catch (remoteexception ex) {
  log.e(tag, "unable to notify listener (posted): " + listener, ex);
 }
}

调用到最后会执行 listener.onnotificationposted() 方法。通过全局搜索得知,listener 类型是 notificationlistenerservice.notificationlistenerwrapper 的代理对象。

notificationlistenerservice.notificationlistenerwrapper#onnotificationposted()

public void onnotificationposted(istatusbarnotificationholder sbnholder, notificationrankingupdate update) {
 statusbarnotification sbn;
 try {
  sbn = sbnholder.get();
 } catch (remoteexception e) {
  log.w(tag, "onnotificationposted: error receiving statusbarnotification", e);
  return;
 }
 try {
  // convert icon metadata to legacy format for older clients
  createlegacyiconextras(sbn.getnotification());
  maybepopulateremoteviews(sbn.getnotification());
 } catch (illegalargumentexception e) {
  // warn and drop corrupt notification
  log.w(tag, "onnotificationposted: can't rebuild notification from " + sbn.getpackagename());
  sbn = null;
 }
 // protect subclass from concurrent modifications of (@link mnotificationkeys}.
 synchronized(mlock) {
  applyupdatelocked(update);
  if (sbn != null) {
   someargs args = someargs.obtain();
   args.arg1 = sbn;
   args.arg2 = mrankingmap;
   mhandler.obtainmessage(myhandler.msg_on_notification_posted, args).sendtotarget();
  } else {
   // still pass along the ranking map, it may contain other information
   mhandler.obtainmessage(myhandler.msg_on_notification_ranking_update, mrankingmap).sendtotarget();
  }
 }
}

这里在一开始会从 sbnholder 中获取到 sbn 对象,sbn 隶属于 statusbarnotificationholder 类,继承于 istatusbarnotificationholder.stub 对象。注意到这里捕获了一个 remoteexception,猜测涉及到跨进程调用,但我们不知道这段代码是在哪个进程中执行的,所以在这里暂停跟踪代码。

笔者之前是通过向系统发送通知的方式跟踪源码,发现走不通。故个人尝试从另一个角度入手,即系统接收我们发过来的通知并显示到通知栏这个方式入手跟踪代码。

系统如何显示 notification,即对于系统端来说,notification 的接收逻辑

系统显示 notification 的过程,猜测是在 phonestatusbar.java 中,因为系统启动的过程中,会启动 systemui 进程,初始化整个 android 显示的界面,包括系统通知栏。

phonestatusbar#start()  -> basestatusbar#start()

public void start() {
 // 省略代码
 // set up the initial notification state.
 try {
  mnotificationlistener.registerassystemservice(mcontext,
    new componentname(mcontext.getpackagename(), getclass().getcanonicalname()),
    userhandle.user_all);
 } catch (remoteexception e) {
  log.e(tag, "unable to register notification listener", e);
 }
 // 省略代码
}

这段代码中,会调用 notificationlistenerservice#registerassystemservice() 方法,涉及到我们之前跟踪代码的类。我们继续跟进去看一下。

notificationlistenerservice#registerassystemservice()

public void registerassystemservice(context context, componentname componentname,
  int currentuser) throws remoteexception {
 if (mwrapper == null) {
  mwrapper = new notificationlistenerwrapper();
 }
 msystemcontext = context;
 inotificationmanager noman = getnotificationinterface();
 mhandler = new myhandler(context.getmainlooper());
 mcurrentuser = currentuser;
 noman.registerlistener(mwrapper, componentname, currentuser);
}

这里会初始化一个 notificationlistenerwrapper 和 mhandler。由于这是在 systemui 进程中去调用此方法将 notificationlistenerservice 注册为系统服务,所以在前面分析的那里:

notificationlistenerservice.notificationlistenerwrapper#onnotificationposted(),这段代码是运行在 systemui 进程,而 mhandler 则是运行在 systemui 主线程上的 handler。所以,onnotificationposted() 是运行在 systemui 进程中,它通过 sbn 从 system_server 进程中获取到 sbn 对象。下一步是通过 mhandler 处理消息,查看 notificationlistenerservice.myhandler#handlemessage() 方法,得知当 message.what 为 msg_on_notification_posted 时,调用的是 onnotificationposted() 方法。

但是,notificationlistenerservice 是一个抽象类,onnotificationposted() 为空方法,真正的实现是它的实例类。

观察到之前 basestatusbar#start() 中,是调用了 mnotificationlistener.registerassystemservice() 方法。那么,mnotificationlistener 是在哪里进行初始化呢?

basestatusbar.mnotificationlistener#onnotificationposted

private final notificationlistenerservice mnotificationlistener = new notificationlistenerservice() {
 // 省略代码
 
 @override
 public void onnotificationposted(final statusbarnotification sbn, final rankingmap rankingmap) {
  if (debug) log.d(tag, "onnotificationposted: " + sbn);
  if (sbn != null) {
   mhandler.post(new runnable() {
    @override
    public void run() {
     processforremoteinput(sbn.getnotification());
     string key = sbn.getkey();
     mkeyskeptforremoteinput.remove(key);
     boolean isupdate = mnotificationdata.get(key) != null;
     // in case we don't allow child notifications, we ignore children of
     // notifications that have a summary, since we're not going to show them
     // anyway. this is true also when the summary is canceled,
     // because children are automatically canceled by noman in that case.
     if (!enable_child_notifications && mgroupmanager.ischildingroupwithsummary(sbn)) {
      if (debug) {
       log.d(tag, "ignoring group child due to existing summary: " + sbn);
      }
      // remove existing notification to avoid stale data.
      if (isupdate) {
       removenotification(key, rankingmap);
      } else {
       mnotificationdata.updateranking(rankingmap);
      }
      return;
     }
     if (isupdate) {
      updatenotification(sbn, rankingmap);
     } else {
      addnotification(sbn, rankingmap, null /* oldentry */ );
     }
    }
   });
  }
 }
 // 省略代码
}

通过上述代码,我们知道了在 basestatusbar.java 中,创建了 notificationlistenerservice 的实例对象,实现了 onnotificationpost() 这个抽象方法;

onnotificationpost() 中,通过 handler 进行消息处理,最终调用 addnotification() 方法

phonestatusbar#addnotification()

@override
public void addnotification(statusbarnotification notification, rankingmap ranking, entry oldentry) {
 if (debug) log.d(tag, "addnotification key=" + notification.getkey());
 mnotificationdata.updateranking(ranking);
 entry shadeentry = createnotificationviews(notification);
 if (shadeentry == null) {
  return;
 }
 boolean isheadsuped = shouldpeek(shadeentry);
 if (isheadsuped) {
  mheadsupmanager.shownotification(shadeentry);
  // mark as seen immediately
  setnotificationshown(notification);
 }
 if (!isheadsuped && notification.getnotification().fullscreenintent != null) {
  if (shouldsuppressfullscreenintent(notification.getkey())) {
   if (debug) {
    log.d(tag, "no fullscreen intent: suppressed by dnd: " + notification.getkey());
   }
  } else if (mnotificationdata.getimportance(notification.getkey()) < notificationlistenerservice.ranking.importance_max) {
   if (debug) {
    log.d(tag, "no fullscreen intent: not important enough: " + notification.getkey());
   }
  } else {
   // stop screensaver if the notification has a full-screen intent.
   // (like an incoming phone call)
   awakendreams();
   // not immersive & a full-screen alert should be shown
   if (debug) log.d(tag, "notification has fullscreenintent; sending fullscreenintent");
   try {
    eventlog.writeevent(eventlogtags.sysui_fullscreen_notification, notification.getkey());
    notification.getnotification().fullscreenintent.send();
    shadeentry.notifyfullscreenintentlaunched();
    metricslogger.count(mcontext, "note_fullscreen", 1);
   } catch (pendingintent.canceledexception e) {}
  }
 }
 // !!!
 addnotificationviews(shadeentry, ranking);
 // recalculate the position of the sliding windows and the titles.
 setaretherenotifications();
}

在这个方法中,最关键的方法是最后的 addnotificationviews() 方法。调用这个方法之后,你创建的 notification 才会被添加到系统通知栏上。

总结

跟踪完整个过程中,之前提到的问题也可以一一解决了:

q:我们创建的 notification 实例最终以什么样的方式发送给系统?

a:首先,我们在 app 进程创建 notification 实例,通过跨进程调用,传递到 system_server 进程的 notificationmanagerservice 中进行处理,经过两次异步调用,最后传递给在 notificationmanagerservice 中已经注册的 notificationlistenerwrapper。而 android 系统在初始化 systemui 进程的时候,会往 notificationmanagerservice 中注册监听器(这里指的就是 notificationlistenerwrapper)。这种实现方法就是基于我们熟悉的一种设计模式:监听者模式。

q:系统是如何获取到 notification 实例并显示的?

a:上面提到,由于初始化的时候已经往 notificationmanagerservice 注册监听器,所以系统 systemui 进程会接收到 notification 实例之后经过进一步解析,然后构造出 notification views 并最终显示在系统通知栏上。

q:我们是否能拦截 notification 并获取其中的信息?

a:通过上面的流程,我个人认为可以通过 xposed 等框架去 hook 其中几个重要的方法去捕获 notification 实例,例如 hook notificationmanager#notify() 方法去获取 notification 实例。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。