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

转载自:

http://blog.csdn.net/rev_fycd/article/details/8557158

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

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

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


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

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

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

由RemoteView内部定一个Action类:

[java]  view plain copy
  1. /** 
  2.  * Base class for all actions that can be performed on an  
  3.  * inflated view. 
  4.  * 
  5.  *  SUBCLASSES MUST BE IMMUTABLE SO CLONE WORKS!!!!! 
  6.  */  
  7. private abstract static class Action implements Parcelable {  


RemoteView维护一个Action抽象类的数组:

[java]  view plain copy
  1. /** 
  2.      * An array of actions to perform on the view tree once it has been 
  3.      * inflated 
  4.      */  
  5.     private ArrayList<Action> mActions;  


每一个对RemoteView内View控件的操作都对应一个ReflectionAction(继承于Action):

[java]  view plain copy
  1. /** 
  2.  * Base class for the reflection actions. 
  3.  */  
  4. private class ReflectionAction extends Action {  


ReflectionAction的作用是利用反射调用View的相关方法,用来操作View绘图。

绘图时候遍历RemoteView的Action数组,获得数据利用反射调用相关View的方法:

[java]  view plain copy
  1. @Override  
  2. public void apply(View root, ViewGroup rootParent) {  
  3.     ...  
  4.     Class klass = view.getClass();  
  5.     Method method;  
  6.     try {  
  7.         method = klass.getMethod(this.methodName, getParameterType());  
  8.     ...  
  9.         method.invoke(view, this.value);  
  10.     }  
  11.     ...  
  12. }  

导致应用卡死的根源问题就是,这个RemoteView维护的Action数组是只会增加不会减少的:

[java]  view plain copy
  1. private void addAction(Action a) {  
  2.         if (mActions == null) {  
  3.             mActions = new ArrayList<Action>();  
  4.         }  
  5.         mActions.add(a);  
  6.   
  7.         // update the memory usage stats  
  8.         a.updateMemoryUsageEstimate(mMemoryUsageCounter);  
  9.     }  

也就是说,如果每次都使用同一个RemoteView发送通知,那么每次发送通知就会把之前所有的操作都重复的执行一遍。消耗比上次更多的时间,如果通知栏里布局复杂,notify(int id, Notification notification)方法就会消耗很长时间,导致应用卡死:

[java]  view plain copy
  1. private void performApply(View v, ViewGroup parent) {  
  2.     if (mActions != null) {  
  3.         final int count = mActions.size();  
  4.         for (int i = 0; i < count; i++) {  
  5.             Action a = mActions.get(i);  
  6.             a.apply(v, parent);  
  7.         }  
  8.     }  
  9. }  

个人认为,这个是Android的一个bug,但是确实没有有效的方法在根源上解决这个问题,只有再每次发通知前,new一个新RemoteView出来,这样Action里就没有多余的操作。花费时间很短。需要注意的是,不要clone原有的RemoteView,clone()会将Action数组都拷贝下来,最终一样会很慢。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值