SoFunction
Updated on 2025-03-11

Solution to optimize the display of toast content in Android


/**   
 * Toast util class.   
 *    
 * @author <A href=""></A>   
 * @version 2011/11/30   
 *    
 */  
public class ToastUtil { 

    private static Handler handler = new Handler(()); 

    private static Toast toast = null; 

    private static Object synObj = new Object(); 

    public static void showMessage(final Context act, final String msg) { 
        showMessage(act, msg, Toast.LENGTH_SHORT); 
    } 

    public static void showMessage(final Context act, final int msg) { 
        showMessage(act, msg, Toast.LENGTH_SHORT); 
    } 

    public static void showMessage(final Context act, final String msg, 
            final int len) { 
        new Thread(new Runnable() { 
            public void run() { 
                (new Runnable() { 
                    @Override 
                    public void run() { 
                        synchronized (synObj) { 
                            if (toast != null) { 
                                (); 
                                (msg); 
                                (len); 
                            } else { 
                                toast = (act, msg, len); 
                            } 
                            (); 
                        } 
                    } 
                }); 
            } 
        }).start(); 
    } 

 
    public static void showMessage(final Context act, final int msg, 
            final int len) { 
        new Thread(new Runnable() { 
            public void run() { 
                (new Runnable() { 
                    @Override 
                    public void run() { 
                        synchronized (synObj) { 
                            if (toast != null) { 
                                (); 
                                (msg); 
                                (len); 
                            } else { 
                                toast = (act, msg, len); 
                            } 
                            (); 
                        } 
                    } 
                }); 
            } 
        }).start(); 
    }