首页 > 解决方案 > 为什么即使应用程序调用了 onDestroy(),Toast 仍然显示?

问题描述

假设我有这段代码onCreate()

   for (int i = 0; i < 20; i++) {
        Toast.makeText(MainActivity.this, "Toast "+i, Toast.LENGTH_SHORT).show();
    }

当我启动应用程序时,Toasts 开始弹出。

现在,当我按下后退按钮时(比如说在 Toast 5 之后)。被onDestroy()调用,应用程序已关闭。

但是我仍然可以看到 Toast 弹出,直到它达到 20 或者我从内存中清除应用程序。

问题:

为什么我的代码用完了应用程序?

我已经给出了我的活动的上下文,那么它不应该在活动被破坏后立即停止吗?

这里不重要context吗?

如果您链接任何文档,将会很有帮助。

标签: androidandroid-toast

解决方案


Toast课堂上,Toast.makeText()是一个静态的method。当您调用此方法时,将Toast创建一个新对象并将您的传递Context保存在其中,系统的默认布局用于创建一个view附加到您的Toast对象的重力,并且还设置了重力来管理您toast将在屏幕上显示的位置。

toast由系统服务显示。该服务维护一个要显示的,并使用它自己queue的来显示它们。当您调用then时,它会将您排入系统服务的消息队列。因此,当您在创建后被销毁时,系统服务已经开始行动,并且其中包含要显示的消息。通过在您的(销毁时)系统上按后按,不能断定您可能不打算显示剩余的 toast 消息。只有当您从内存中清除您的应用程序时,系统才能自信地推断出它不再需要从您的应用程序中显示。toast messagesThreadshow()toast objecttoastactivity20 toastmessage queueactivitytoast message

有关更多信息,您可以查看Toast class. 我为你包括了相关的方法。顺便说一句,好问题

Toast.makeText 的实现

 /**
 * Make a standard toast to display using the specified looper.
 * If looper is null, Looper.myLooper() is used.
 * @hide
 */
public static Toast makeText(@NonNull Context context, @Nullable Looper looper,
        @NonNull CharSequence text, @Duration int duration) {
    Toast result = new Toast(context, looper);

    LayoutInflater inflate = (LayoutInflater)
            context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);
    TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message);
    tv.setText(text);

    result.mNextView = v;
    result.mDuration = duration;

    return result;
}

创建新的吐司:

/**
 * Constructs an empty Toast object.  If looper is null, Looper.myLooper() is used.
 * @hide
 */
public Toast(@NonNull Context context, @Nullable Looper looper) {
    mContext = context;  // your passed `context` is saved.
    mTN = new TN(context.getPackageName(), looper);
    mTN.mY = context.getResources().getDimensionPixelSize(
            com.android.internal.R.dimen.toast_y_offset);
    mTN.mGravity = context.getResources().getInteger(
            com.android.internal.R.integer.config_toastDefaultGravity);
}

show() 的实现

/**
 * Show the view for the specified duration.
 */
public void show() {
    if (mNextView == null) {
        throw new RuntimeException("setView must have been called");
    }

    INotificationManager service = getService(); 
    String pkg = mContext.getOpPackageName();
    TN tn = mTN;
    tn.mNextView = mNextView;
    final int displayId = mContext.getDisplayId();

    try {
        service.enqueueToast(pkg, tn, mDuration, displayId);
    } catch (RemoteException e) {
        // Empty
    }
}

推荐阅读