Java tutorial
//package com.java2s; import java.lang.ref.SoftReference; import android.app.Activity; import android.content.Context; import android.os.Looper; import android.widget.Toast; public class Main { private static SoftReference<Toast> sToastRef = null; public static void showToast(Context context, int s) { showToast(context, context.getString(s)); } public static void showToast(final Context context, final String s) { if (Looper.getMainLooper() == Looper.myLooper()) { Toast toast = Toast.makeText(context, s, Toast.LENGTH_SHORT); hideToast(); toast.show(); sToastRef = new SoftReference<Toast>(toast); } else { if (context instanceof Activity) { ((Activity) context).runOnUiThread(new Runnable() { @Override public void run() { showToast(context, s); } }); } } } public static void showToast(final Context context, Toast toast, final String s) { if (Looper.getMainLooper() == Looper.myLooper()) { hideToast(); toast.show(); sToastRef = new SoftReference<Toast>(toast); } else { if (context instanceof Activity) { ((Activity) context).runOnUiThread(new Runnable() { @Override public void run() { showToast(context, s); } }); } } } public static void hideToast() { if (sToastRef != null) { Toast previousToast = sToastRef.get(); if (previousToast != null) { previousToast.cancel(); } } } }