Android Toast句柄泄露问题

  • 在安卓开发中为防止句柄Toast泄露,全局使用一个Toast。
public final class ToastUtil {

    public static void showToast(Context context, int resourceId) {
        if (context == null) {
            return;
        }
        Toast.makeText(context, resourceId, Toast.LENGTH_SHORT).show();
    }

    public static void showToast(Context context, String message) {
        if (context == null) {
            return;
        }
        try {
            Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
        } catch (Exception e){
            // Can't toast on a thread that has not called Looper.prepare
            Looper.prepare();
            Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
            Looper.loop();
            e.printStackTrace();
        }
    }

    public static void showToast(Context context, String message, int duration) {
        if (context == null) {
            return;
        }
        Toast.makeText(context, message, duration).show();
    }

你可能感兴趣的:(Android)