Skip to content

Instantly share code, notes, and snippets.

@leasual
Forked from yeoupooh/ExampleStaticHandler.java
Created October 21, 2015 09:53
Show Gist options
  • Save leasual/d7b591ae96e75b96e6b6 to your computer and use it in GitHub Desktop.
Save leasual/d7b591ae96e75b96e6b6 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);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment