处理器postDelayed和视频下载() [英] Handler postDelayed and Thread.sleep()

查看:162
本文介绍了处理器postDelayed和视频下载()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的code进行了Thread.Sleep和处理postDelayed:

I have a thread.sleep and a handler postDelayed in my code:

handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        Log.e(TAG, "I ran");
        mIsDisconnect = false;
    }
}, DISCONNECT_DELAY);

在处理程序code和用户preSS按钮后,我有这样的:

After the handler code and after the user press the button I have this:

while (mIsDisconnect) {
    try {
        Thread.sleep(DELAY);
    } catch (InterruptedException e) {
        Log.e(TAG, "problem sleeping");
    }
}

如果用户等待足够长的时间,我可以让我的日志我跑了。但是,如果用户preSS按钮上的延迟,之后到了,似乎从来没有postDelayed得到执行的机会。我的问题是,是否有处理程序的Thread.sleep()方法的混乱postDelayed?

If the user wait long enough I can get the "I ran" in my log. But if the user press the button before the delay is up, it seems that the postDelayed never gets a chance to execute. My question is, does the thread.sleep() mess with the handler postDelayed?

编辑:此code的目的是我想继续后才DISCONNECT_DELAY秒已通过该计划。因此,如果用户点击早,我必须等待经过的时间来完成。

The purpose of this code is that I want to continue the program only after DISCONNECT_DELAY seconds has already passed. So if the user clicks to early, I have to wait for the elapsed time to finish.

推荐答案

我假设你的处理程序与其他环路上运行同一个线程关联。 (A 处理程序与它在创建线程关联。)

I'm assuming your handler is associated with the same thread the other loop is running on. (A Handler is associated with the thread it is created in.)

postDelayed()的Runnable 在处理线程的消息队列。消息队列进行处理时,控制返回到线程的尺蠖

postDelayed() puts the Runnable in the handler thread's message queue. The message queue is processed when control returns to the thread's Looper.

视频下载()简单地阻止该线程。控制不会返回到尺蠖和消息无法处理。在UI线程睡觉几乎总是错的。

Thread.sleep() simply blocks the thread. The control does not return to the Looper and messages cannot be processed. Sleeping in the UI thread is almost always wrong.

要完成你正在试图做的,除去睡眠,只是用什么 postDelayed()来发布的Runnable 改变您的应用程序的状态(如您已通过设置一个成员变量做 mIsDisconnect )。然后在的onClick()只是检查应用程序的状态( mIsDisconnect 标志)是否确定继续与否。

To accomplish what you're trying to do, remove the sleep and simply use postDelayed() to post a Runnable that changes your app state (like you already do by setting a member variable mIsDisconnect). Then in the onClick() just check the app state (mIsDisconnect flag) whether it is ok to proceed or not.

这篇关于处理器postDelayed和视频下载()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆