解释context memory leak的文章

http://www.androiddesignpatterns.com/2013/01/inner-class-handler-memory-leak.html

The "static" keyword has different meanings when it comes to "static variables" vs. "static classes" in Java.

A static variable is a variable that belongs to all instances of a particular class. It will not be reclaimed by the GC when a particular instance of the class is garbage collected... it will stay in memory until you explicitly set it to null. The reason why it is bad to hold a static reference to a Drawable is because a Drawable usually holds a reference to a View and that View usually holds a reference to its parent Activity. As a result, the static Drawable will force the Activity to stay in memory even after the Activity is destroyed (unless you explicitly set the static Drawable to null, of course).

Static classes in Java don't really have the same meaning as static variables in Java. A static class declaration gives you a way to declare an inner class as if it was declared in a separate .java file... and that's pretty much it. A non-static inner class on the other hand is implicitly associated with its outer class... unlike static inner classes, an instance of a non-static inner class cannot exist without an instance of its outer class as well.

To answer your second question, declaring the mHandler as static would not have the same effect as the above sample code. Making the handler static means that it would be shared by all instances of the Activity (i.e. if you rotated the screen causing the Activity to be destroyed, the same Handler object would be used by the newly created Activity instance as well). In the sample code above, the Handler is declared as non-static which means that a new Handler will be created for each new Activity that is instantiated.

Yes, the Runnable is static so a single instance will be allocated and will be shared across all Activity instances (a new one will not be created for each new Activity that is created). I explain why it is important for the Runnable to be static in the second to last paragraph of the post.


java static and non-static class and variable
https://drive.google.com/file/d/0B-5-QeQdT3FxQUdnUWNFTUMxdXc/view
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值