Handler postDelayed and Thread.sleep()

怎甘沉沦 提交于 2019-12-05 09:40:45

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() puts the Runnable in the handler thread's message queue. The message queue is processed when control returns to the thread's Looper.

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.

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.

I guess that the second section runs on the main thread and you didn't move between threads.
You can't put the main thread on sleep, you stop all UI issues and other stuff that should be run on this thread (the main thread).

Use postDelayed of the handler instead.

The best way is with a sentinel:

runnable = new Runnable() {
    @Override
    public void run() {

    // condition to pass (sentinel == 1)
        if (isActive == 0) {
            handler.postDelayed(this, 1000); // 1 seconds
        }
        else {
        // isActive == 1, we pass!

        // Do something aweseome here!

        }


     }
};
handler = new Handler();
handler.postDelayed(runnable, 100);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!