1. 程式人生 > 其它 >Android中聲名Handler變數的記憶體洩露問題

Android中聲名Handler變數的記憶體洩露問題

2019獨角獸企業重金招聘Python工程師標準>>> hot3.png

##This Handler class should be static or leaks might occur 有如下程式碼:

public class MainActivity extends AppCompatActivity {
    private Handler handler = new Handler(){
        //其他程式碼省略
    };
    //其他程式碼省略
}

會提示如下資訊:

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.

##解決辦法

static class IncomingHandler extends Handler {
    private final WeakReference<UDPListenerService> mService; 

    IncomingHandler(UDPListenerService service) {
        mService = new WeakReference<UDPListenerService>(service);
    }
    @Override
    public void handleMessage(Message msg)
    {
         UDPListenerService service = mService.get();
         if (service != null) {
              service.handleMessage(msg);
         }
    }
}

##參考 stackoverflow

How to Leak a Context: Handlers & Inner Classes

轉載於:https://my.oschina.net/neumeng/blog/541920