Android中聲名Handler變量的內存泄露問題

##This Handler class should be static or leaks might occur 有以下代碼:html

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

會提示以下信息:android

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.ide

##解決辦法oop

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);
         }
    }
}

##參考 stackoverflowthis

How to Leak a Context: Handlers & Inner Classescode

相關文章
相關標籤/搜索