[英]Thread.sleep does not pause the app in Android
I would like to pause my android app for 1 second after I inserted something into the Firebase database.在将某些内容插入 Firebase 数据库后,我想暂停我的 android 应用程序 1 秒钟。 For that I use the following code insider a liistener:
为此,我在内部使用以下代码作为侦听器:
firebase_DB.child(id).setValue(currentOrder).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
orderSuccesfullyWritten[0] =true;
orderCouldNotBeSendAfterMutipleAttemps[0] = false;
Log.e("dbTAG", "Data successfully written.");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
Log.e("dbTAG", task.getException().getMessage());
}
}
});
The code is being executed (and I get the message that "Data successfully written" but the Threas.sleep(1000)
does not have any effects. The app just directly continues with the next actions. Any idea why this is the case? I'll appreciate every comment.代码正在执行(我收到“数据成功写入”的消息,但
Threas.sleep(1000)
没有任何影响。应用程序只是直接继续下一步操作。知道为什么会这样吗?我会感谢每一条评论。
You are putting thread.sleep once the firebase query has already completed.一旦 firebase 查询已经完成,您将放置 thread.sleep。
Simply move Thread.sleep to after your firebase query只需将 Thread.sleep 移动到您的 firebase 查询之后
firebase_DB.child(id).setValue(currentOrder).addOnCompleteListener(do something);
Thread.sleep(1000);
A firebase query runs asynchronously, meaning it is running on a background thread. firebase 查询异步运行,这意味着它在后台线程上运行。 So with this code the main thread will sleep for a second while the firebase query is executing
因此,使用此代码,主线程将在执行 firebase 查询时休眠一秒钟
But be reminded that using Thread.sleep()
is bad practice但请注意,使用
Thread.sleep()
是不好的做法
Just some additional information why Thread.sleep() called on main thread is bad idea:只是一些附加信息,为什么在主线程上调用 Thread.sleep() 是个坏主意:
Basically I would like to pause the UI in case of not being able to submit the data to the firebase query.
基本上我想暂停 UI,以防无法将数据提交到 firebase 查询。
I would suggest you to put a loading screen telling the user the data is uploading... or smth like that.我建议您放置一个加载屏幕,告诉用户数据正在上传......或者类似的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.