Android handle的warning:this Handler Class should be Static or leaks might occur

更新UI是要主线程来更新的,即UI线程更新

众所周知,Android更新UI一般有两种常用方法:
- Handle
- runOnUIThread()

如下Handle更新的代码发出warning警告:

mainhandler = new Handler() {
    public void handleMessage(android.os.Message msg) {
      ...
    }
}



Since this Handler is declared as an inner class, it may prevent the outer class from being garbage collected. If the Handler is using a Looper or MessageQueue for a thread other than the main thread, then there is no issue. If the Handler is using the Looper or MessageQueue of the main thread, you need to fix your Handler declaration, as follows: Declare the Handler as a static class; In the outer class, instantiate a WeakReference to the outer class and pass this object to your Handler when you instantiate the Handler; Make all references to members of the outer class using the WeakReference object.


Apr 4, 2009 Romain Guy 在Google网上论坛提到:

If you want to use the equivalent of an inner-class but not risk a
leak, here’s a simple patter

class OuterClass { 
  class InnerClass { 
    private final WeakReference<OuterClass> mTarget; 

    InnerClass(OuterClass target) { 
      mTarget = new WeakReference<OuterClass>(target); 
    } 

    void doSomething() { 
      OuterClass target = mTarget.get(); 
      if (target != null) target.do(); 
    } 
  } 
} 

因为在Java语言中,非静态匿名内部类将持有一个对外部类的隐式引用,而静态内部类则不会持有引用。
当Activity被finish()掉,Message 将存在于消息队列在很长的时间之后才会被执行到的话,这个Message持有一个对Handler的引用,Handler也会持有一个对于外部类(SampleActivity)的隐式引用,这些引用在Message被执行前将一直保持,这样会保证Activity的上下文不被垃圾回收机制回收,同时也会泄露应用程序的资源。





参考:
http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2014/1106/1922.html

https://groups.google.com/forum/?fromgroups=#!msg/android-developers/1aPZXZG6kWk/lIYDavGYn5UJ

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值