Java 你如何让代码在 android 中暂停几秒钟?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4111905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:44:24  来源:igfitidea点击:

How do you have the code pause for a couple of seconds in android?

javaandroidtimewait

提问by Ivan S

Basically I need a pause (based on just a few seconds) to be put into one action so that the user can see what happens before the next action is taken. So for blackHyman, when it's the dealer's turn and he decides to hit, he hits, a card is added, and then he decides what to do next. So before he decides on what to do next, I want the code to pause so it can be "seen" as to what the dealer is doing this way the dealer doesn't complete his actions in less than a second and the player only sees the results.

基本上我需要暂停(仅基于几秒钟)以执行一个操作,以便用户可以在执行下一个操作之前看到发生了什么。所以对于二十一点,当轮到庄家决定打牌时,他打牌,加一张牌,然后他决定下一步做什么。因此,在他决定下一步做什么之前,我希望代码暂停,以便可以“看到”庄家这样做的方式,庄家不会在不到一秒钟的时间内完成他的操作,而玩家只能看到结果。

Thanks in advance!

提前致谢!

I should note I have tried using wait(insert number here); but i am told by eclipse that it causes a stack interception error or something of the sort and throws an exception, thus doing nothing : (

我应该注意到我已经尝试过使用 wait(insert number here); 但是 eclipse 告诉我它会导致堆栈拦截错误或类似的东西并抛出异常,因此什么都不做:(

Well this is interesting, (the way I've programed the things is "interesting" to say the least) I did the Thread.sleep(5000) and threw it under a try catch, it does sleep for 5 seconds and then continues doing the code. However my updates to views don't show until after I press a button(Is really hating event driven programming).

嗯,这很有趣,(我对事物进行编程的方式至少可以说是“有趣的”)我做了 Thread.sleep(5000) 并将其置于 try catch 之下,它确实休眠了 5 秒钟,然后继续执行编码。然而,我对视图的更新直到我按下按钮后才会显示(真的很讨厌事件驱动编程)。

采纳答案by adamp

Learning to think in terms of events is indeed the key here. You can do it. :)

学会从事件的角度思考确实是这里的关键。你能行的。:)

The first rule is: never stall the UI thread. The UI thread is responsible for keeping your app feeling responsive. Any work you do there should not block; do what you need to do and return as quickly as possible. Definitely avoid doing I/O on the UI thread. (There are some places where you can't really help it due to lifecycle requirements, for example saving app state in onPause.) If you evercall Thread.sleepon the UI thread you are doing it wrong.

第一条规则是:永远不要停止 UI 线程。UI 线程负责让您的应用程序感觉响应。你在那里做的任何工作都不应该阻塞;做你需要做的事情并尽快返回。绝对避免在 UI 线程上进行 I/O。(由于生命周期的要求,有些地方您无法真正帮助它,例如将应用程序状态保存在onPause.)如果您曾经调用Thread.sleepUI 线程,那么您就做错了。

Android enforces this with the "Application not responding" (or "ANR") error that the user sees. Whenever you see this in an Android app it means the developer did something that caused the UI thread to stall for too long. If the device is really bogged down for some reason this error might not actually be the app developer's fault, but usually it means the app is doing something wrong.

Android 通过用户看到的“应用程序无响应”(或“ANR”)错误强制执行此操作。每当您在 Android 应用程序中看到这种情况时,就意味着开发人员做了一些导致 UI 线程停滞太久的事情。如果设备由于某种原因真的陷入困境,这个错误实际上可能不是应用程序开发人员的错,但通常意味着应用程序做错了。

You can use this model to your advantage by posting your own events. This gives you an easy way to tell your app, "do this later." In Android the key to posting your own events is in the Handlerclass. The method postDelayedlets you schedule a Runnablethat will be executed after a certain number of milliseconds.

您可以通过发布自己的事件来利用此模型。这为您提供了一种告诉您的应用程序“稍后再做”的简单方法。在 Android 中,发布您自己的事件的关键在于Handler课堂。该方法postDelayed允许您安排Runnable将在特定毫秒数后执行的 a。

If you have an Activity that looks something like this:

如果你有一个看起来像这样的活动:

public class MyActivity extends Activity {
    private Handler mHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mHandler.postDelayed(new Runnable() {
            public void run() {
                doStuff();
            }
        }, 5000);
    }

    private void doStuff() {
        Toast.makeText(this, "Delayed Toast!", Toast.LENGTH_SHORT).show();
    }
}

Then 5 seconds after the activity is created you will see the toast created in doStuff.

然后在创建活动 5 秒后,您将看到在 中创建的吐司doStuff

If you're writing a custom Viewit's even easier. Views have their own postDelayedmethod that will get everything posted to the correct Handlerand you don't need to create your own.

如果您正在编写自定义View,则更容易。视图有自己的postDelayed方法,可以将所有内容发布到正确的位置Handler,您无需创建自己的方法。

The second rule is: Views should onlybe modified on the UI thread. Those exceptions you're getting and ignoring mean something went wrong and if you ignore them your app will probably start misbehaving in interesting ways. If your app does most of its work in other threads you can postevents directly to the view you want to modify so that the modifications will run correctly.

第二条规则是:视图只能在 UI 线程上修改。你得到和忽略的那些异常意味着出现问题,如果你忽略它们,你的应用程序可能会开始以有趣的方式行为不端。如果您的应用程序在其他线程中完成大部分工作,您可以将post事件直接发送到要修改的视图,以便修改正确运行。

If you have a reference to your Activityfrom that part of your code you can also use Activity#runOnUIThread, which does exactly what the name implies. You might prefer this approach if posting to a single view doesn't really make sense in context.

如果您Activity在代码的那部分有对您的引用,您也可以使用Activity#runOnUIThread,这正是名称所暗示的。如果发布到单个视图在上下文中没有真正意义,您可能更喜欢这种方法。

As for updates to views not appearing until you hit a button, what kind of views are these? Are they custom views that are drawing these updates? If so, are you remembering to call invalidateafter data changes to trigger the redraw? Views only redraw themselves after they have been invalidated.

至于直到你点击按钮才出现的视图更新,这些是什么类型的视图?它们是绘制这些更新的自定义视图吗?如果是这样,您是否记得invalidate在数据更改后调用以触​​发重绘?视图只有在它们失效后才会重绘。