Skip to content

Instantly share code, notes, and snippets.

@jsaund
Last active March 15, 2016 20:18
Show Gist options
  • Save jsaund/cafaac7e06743530e142 to your computer and use it in GitHub Desktop.
Save jsaund/cafaac7e06743530e142 to your computer and use it in GitHub Desktop.
A safer Android Handler for use with Activities or other components that require posting back on to the UI thread via an Activity reference.
public abstract class UIHandler<T extends Activity> extends Handler {
private final WeakReference<T> mRef;
public UIHandler(T a) {
mRef = new WeakReference<>(a);
}
@Override
public void handleMessage(Message msg) {
final T a = mRef.get();
if (a == null || a.isFinishing()) {
return;
}
handleMessage(msg, a);
}
abstract void handleMessage(Message msg, final T activity);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment