Android源生代码bug导致连续发通知应用卡死

项目中发现,连续发送同一个通知会导致应用越来越慢,最终卡死。

调试发现,如果每次都new一个新的RemoteView就不会卡死,这是为什么?

跟踪进入android源码终于发现原因所在。


应用发送通知是进程交互的过程。app需要将通知类(Notification)传送给通知服务进程。由通知服务进程管理发送通知。

Notification中的组建都实现了Parcelable接口,包括RemoteView。卡死的原因就在于RemoteView的实现原理上。

RemoteView提供了一系列方法,方便我们操作其中的View控件,比如setImageViewResource()等,其实现的机制是:

由RemoteView内部定一个Action类:

    /**
     * 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抽象类的数组:

/**
     * 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绘图。

绘图时候遍历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数组都拷贝下来,最终一样会很慢。

原文地址:https://www.cnblogs.com/wangsx/p/3288080.html