Skip to content

Instantly share code, notes, and snippets.

@baleen37
Created May 8, 2017 05:40
Show Gist options
  • Select an option

  • Save baleen37/f786cfde2879af6ce72ab42275fdf239 to your computer and use it in GitHub Desktop.

Select an option

Save baleen37/f786cfde2879af6ce72ab42275fdf239 to your computer and use it in GitHub Desktop.
Thread safe toast
public class SafeToast {
public static final int LENGTH_SHORT = 0;
public static final int LENGTH_LONG = 1;
private Context context;
private CharSequence text;
private int duration;
public SafeToast(Context context) {
this.context = context;
}
public static SafeToast makeText(Context context, CharSequence text, @Duration int duration) {
SafeToast safeToast = new SafeToast(context);
safeToast.text = text;
safeToast.duration = duration;
return safeToast;
}
public static SafeToast makeText(Context context, int resId, int duration)
throws Resources.NotFoundException {
return makeText(context, context.getResources().getString(resId), duration);
}
@SuppressLint("ShowToast") private Toast createInternal() {
return Toast.makeText(context, text, duration);
}
public void show() {
if (Looper.myLooper() == Looper.getMainLooper()) {
createInternal().show();
} else {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new PriorityRunnable() {
public void run() {
createInternal().show();
}
});
}
}
/** @hide */
@IntDef({ LENGTH_SHORT, LENGTH_LONG }) @Retention(RetentionPolicy.SOURCE)
public @interface Duration {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment