Last active
August 28, 2018 06:26
-
-
Save yeoupooh/5268411 to your computer and use it in GitHub Desktop.
Avoiding "This Handler class should be static or leaks might occur".
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.os.Message; | |
public interface IStaticHandler { | |
void handleMessage(Message msg); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Generally you don't want to throw a RuntimeException when
weakRef.get() == null
. Or you may convert the memory leak to crashes.