文章转自:http://blog.csdn.net/rev_fycd/article/details/8557158
因为本人记忆力衰退的快,需要做些笔记备忘,因此转载过来,谢谢原创!
项目中发现,连续发送同一个通知会导致应用越来越慢,最终卡死。
调试发现,如果每次都new一个新的RemoteViews就不会卡死,这是为什么?
跟踪进入android源码终于发现原因所在。
应用发送通知是进程交互的过程。app需要将通知类(Notification)传送给通知服务进程。由通知服务进程管理发送通知。
Notification中的组建都实现了Parcelable接口,包括RemoteViews。卡死的原因就在于RemoteViews的实现原理上。
RemoteViews提供了一系列方法,方便我们操作其中的View控件,比如setImageViewResource()等,其实现的机制是:
由RemoteViews内部定一个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 {
RemoteViews维护一个Action抽象类的数组:
/**
* An array of actions to perform on the view tree once it has been
* inflated
*/
private ArrayList<Action> mActions;
每一个对RemoteViews内View控件的操作都对应一个ReflectionAction(继承于Action):
/**
* Base class for the reflection actions.
*/
private class ReflectionAction extends Action {
ReflectionAction的作用是利用反射调用View的相关方法,用来操作View绘图。
绘图时候遍历RemoteViews的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);
}
...
}
导致应用卡死的根源问题就是,这个RemoteViews维护的Action数组是只会增加不会减少的:
private void addAction(Action a) {
if (mActions == null) {
mActions = new ArrayList<Action>();
}
mActions.add(a);
// update the memory usage stats
a.updateMemoryUsageEstimate(mMemoryUsageCounter);
}
也就是说,如果每次都使用同一个RemoteViews发送通知,那么每次发送通知就会把之前所有的操作都重复的执行一遍。消耗比上次更多的时间,如果通知栏里布局复杂, 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);
}
}
}
只有再每次发通知前,new一个新RemoteViews出来< 即在调用notify方法之前> ,这样Action里就没有多余的操作。花费时间很短。需要注意的是, 不要clone原有的RemoteViews ,clone()会将Action数组都拷贝下来,最终一样会很慢。