项目中发现,连续发送同一个通知会致使应用愈来愈慢,最终卡死。android
调试发现,若是每次都new一个新的RemoteView就不会卡死,这是为何?数组
跟踪进入android源码终于发现缘由所在。app
应用发送通知是进程交互的过程。app须要将通知类(Notification)传送给通知服务进程。由通知服务进程管理发送通知。ide
Notification中的组建都实现了Parcelable接口,包括RemoteView。卡死的缘由就在于RemoteView的实现原理上。
布局
RemoteView提供了一系列方法,方便咱们操做其中的View控件,好比setImageViewResource()等,其实现的机制是:this
由RemoteView内部定一个Action类:spa
/** * Base class for all actions that can be performed on an * inflated view. * * SUBCLASSES MUST BE IMMUTABLE SO CLONE WORKS!!!!! */ private abstract static class Action implements Parcelable {
RemoteView维护一个Action抽象类的数组:.net
/** * An array of actions to perform on the view tree once it has been * inflated */ private ArrayList<Action> mActions;
每个对RemoteView内View控件的操做都对应一个ReflectionAction(继承于Action):调试
/** * Base class for the reflection actions. */ private class ReflectionAction extends Action {
ReflectionAction的做用是利用反射调用View的相关方法,用来操做View绘图。code
绘图时候遍历RemoteView的Action数组,得到数据利用反射调用相关View的方法:
@Override public void apply(View root, ViewGroup rootParent) { ... Class klass = view.getClass(); Method method; try { method = klass.getMethod(this.methodName, getParameterType()); ... method.invoke(view, this.value); } ... }
致使应用卡死的根源问题就是,这个RemoteView维护的Action数组是只会增长不会减小的:
private void addAction(Action a) { if (mActions == null) { mActions = new ArrayList<Action>(); } mActions.add(a); // update the memory usage stats a.updateMemoryUsageEstimate(mMemoryUsageCounter); }
也就是说,若是每次都使用同一个RemoteView发送通知,那么每次发送通知就会把以前全部的操做都重复的执行一遍。消耗比上次更多的时间,若是通知栏里布局复杂,notify(int id, Notification notification)方法就会消耗很长时间,致使应用卡死:
private void performApply(View v, ViewGroup parent) { if (mActions != null) { final int count = mActions.size(); for (int i = 0; i < count; i++) { Action a = mActions.get(i); a.apply(v, parent); } } }
我的认为,这个是Android的一个bug,可是确实没有有效的方法在根源上解决这个问题,只有再每次发通知前,new一个新RemoteView出来,这样Action里就没有多余的操做。花费时间很短。须要注意的是,不要clone原有的RemoteView,clone()会将Action数组都拷贝下来,最终同样会很慢。