(安卓)Toast消息隊列輸出


package sc.tool;

import java.util.ArrayList;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;


/** 示例:ToastQueue.ShowToastQueue(this, "Toast消息隊列逐個輸出");
 * 
 * ToastQueue.java: Toast消息隊列輸出,Android 9.0 版本後Toast消息連續輸出,後出現的Toast會替換掉之前的Toast消息,使得Toast展示不全(同一時間,僅展示最後一條);
 * 此類用於實現Toast消息的隊列輸出,按調用順序,逐個展示,不覆蓋、不丟失。
 * 
 * ----- 2020-1-10 下午2:56:44 scimence */
public class ToastQueue
{
	// 示例:ToastQueue.ShowToastQueue(this, "");
	// Toast.makeText(activity, info, Toast.LENGTH_SHORT).show();
	// ShowToastQueue(activity.getApplicationContext(), info);
	
	// ---------------------
	// Toast消息隊列輸出邏輯
	
	public static void ShowToastQueue(final Context context, String info)
	{
		synchronized (ToastList)
		{
			ToastList.add(info);
			if (!ToastQueueisShowing) ShowToastQueueProcess(context.getApplicationContext());
		}
	}
	
	/** 獲取主線程Handler */
	private static Handler getMainHandler()
	{
		return new Handler(Looper.getMainLooper());
	}
	
	private static boolean ToastQueueisShowing = false;
	private static ArrayList<String> ToastList = new ArrayList<String>();
	
	private static Context ToastQueueContext = null;
	
	public static void ShowToastQueueProcess(final Context context)
	{
		synchronized (ToastList)
		{
			if (ToastList != null && ToastList.size() > 0)
			{
				ToastQueueisShowing = true;
				if (ToastQueueContext == null) ToastQueueContext = context;
				
				final String info = ToastList.get(0);
				ToastList.remove(0);
				
				getMainHandler().post(new Runnable()
				{
					@Override
					public void run()
					{
						Toast.makeText(ToastQueueContext, info, Toast.LENGTH_SHORT).show();
					}
				});
				
				getMainHandler().postDelayed(new Runnable()
				{
					@Override
					public void run()
					{
						ShowToastQueueProcess(context);
					}
				}, 2500);
			}
			else ToastQueueisShowing = false;
		}
	}

	// ---------------------
	
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章