Skip to content

Instantly share code, notes, and snippets.

@yeoupooh
Last active August 28, 2018 06:26
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save yeoupooh/5268411 to your computer and use it in GitHub Desktop.
Save yeoupooh/5268411 to your computer and use it in GitHub Desktop.
Avoiding "This Handler class should be static or leaks might occur".
// This is OLD way of usnig Handler which shows an warning.
private Handler oldHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// Handle a message as you want.
}
}
// This is NEW way to avoid the warning.
private IStaticHandler newHandler = new IStaticHandler() {
@Override
public void handleMessage(Message msg) {
// Handle a message as the same as old handler is doing.
}
}
public void exampleOfOldHandler() {
// No initialization
Handler handler = oldHandler;
handler.sendEmptyMessage(0);
}
public void exampleOfNewHandler() {
// Initialize from factory class
Handler handler = StaticHandlerFactory.create(newHandler);
handler.sendEmptyMessage(0);
}
import android.os.Message;
public interface IStaticHandler {
void handleMessage(Message msg);
}
import java.lang.ref.WeakReference;
import android.os.Handler;
import android.os.Message;
public class StaticHandlerFactory {
public static StaticHandler create(IStaticHandler ref) {
return new StaticHandler(ref);
}
// This has to be nested.
static class StaticHandler extends Handler {
WeakReference<IStaticHandler> weakRef;
public StaticHandler(IStaticHandler ref) {
this.weakRef = new WeakReference<IStaticHandler>(ref);
}
@Override
public void handleMessage(Message msg) {
if (weakRef.get() == null) {
throw new RuntimeException("Something goes wrong.");
} else {
weakRef.get().handleMessage(msg);
}
}
}
}
@KANGOD
Copy link

KANGOD commented May 24, 2016

Generally you don't want to throw a RuntimeException when weakRef.get() == null. Or you may convert the memory leak to crashes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment