public static void toastSafely ( final Context context , final int resId , final int duration ) { Long lastToastTime = LAST_TOAST_TIME . get ( resId ) ; if ( lastToastTime != null && ( lastToastTime + TOAST_MIN_REPEAT_DELAY ) < System . currentTimeMillis ( ) ) { return ; } Looper mainLooper = Looper . getMainLooper ( ) ; if ( Thread . currentThread ( ) . equals ( mainLooper . getThread ( ) ) ) { LAST_TOAST_TIME . put ( resId , System . currentTimeMillis ( ) ) ; Toast . makeText ( context , resId , duration ) . show ( ) ; } else { Handler handler = new Handler ( mainLooper ) ; handler . post ( new Runnable ( ) { @ Override public void run ( ) { LAST_TOAST_TIME . put ( resId , System . currentTimeMillis ( ) ) ; Toast . makeText ( context , resId , duration ) . show ( ) ; } } ) ; } }
Helper method for showing a toast message checking to see if user is on ui thread and not showing the same toast if it has already been shown within TOAST_MIN_REPEAT_DELAY time .