android - 为什么即使应用程序调用了 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
吗?
如果您链接任何文档,将会很有帮助。
解决方案
在Toast
课堂上,Toast.makeText()
是一个静态的method
。当您调用此方法时,将Toast
创建一个新对象并将您的传递Context
保存在其中,系统的默认布局用于创建一个view
附加到您的Toast
对象的重力,并且还设置了重力来管理您toast
将在屏幕上显示的位置。
您toast
由系统服务显示。该服务维护一个要显示的,并使用它自己queue
的来显示它们。当您调用then时,它会将您排入系统服务的消息队列。因此,当您在创建后被销毁时,系统服务已经开始行动,并且其中包含要显示的消息。通过在您的(销毁时)系统上按后按,不能断定您可能不打算显示剩余的 toast 消息。只有当您从内存中清除您的应用程序时,系统才能自信地推断出它不再需要从您的应用程序中显示。toast messages
Thread
show()
toast object
toast
activity
20 toast
message queue
activity
toast 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
}
}
推荐阅读
- java - Cannot resolve method 'setText(java.lang.String[] with ResultView
- sharepoint - 为什么我的 nintex 上的复选框在第一次用户选择后不接受响应?
- r - R - 折叠观察并创建新列
- php - laravel 基于关系的过滤器集合
- javascript - 样式组件和 AS TS2769 的打字稿错误:没有重载匹配此调用
- python - 在多文件python代码中在哪里初始化类的实例?
- json - Firebase 在上传 .json 时删除文档
- sql - 我应该使用哪个 SQL 表来存储“人气”字段
- python - Tensorflow LSTM 返回什么?
- linux - 我的 lua 文件在 linux 中没有被读取为 lua