##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
来源:oschina
链接:https://my.oschina.net/u/1243457/blog/541920