简体   繁体   English

Android使用System.currentTimeMillis()显示空白屏幕

[英]Android shows blank screen with System.currentTimeMillis()

I have the following piece of code in my android application. 我的Android应用程序中有以下代码。 Whenever these lines of code run in my application, the mobile screen goes blank for 10 seconds. 只要这些代码行在我的应用程序中运行,移动屏幕就会空白10秒钟。 This 'problem' is most probably caused by 'System.currentTimeMillis()' 这个“问题”很可能是由“ System.currentTimeMillis()”引起的


        for (i=0;i<10;i++)
        {
            time0 = System.currentTimeMillis();
            do
            {
            time1 = System.currentTimeMillis();
            }
            while ((time1 - time0) < 1000);
        } 

Is there any way that the blank screen can be avoided? 有什么办法可以避免黑屏?

Thanks 谢谢

The reason you are getting a blank screen for 10 seconds is because this section of code is blocking the UI thread. 出现空白屏幕10秒钟的原因是因为此部分代码阻止了UI线程。 It has nothing to do with the call to System.currentTimeMillis() . 它与对System.currentTimeMillis()的调用无关。

On each for loop iteration, you are checking the time over and over until 1 second has passed. 在每个for循环迭代中,您要反复检查直到1秒过去的时间。 Since you execute the for loop 10 times, you are effectively blocking the UI thread for 10 seconds. 由于执行了10次for循环,因此有效地将UI线程阻塞了10秒钟。

EDIT: If you would like to pause execution for a few seconds, take a look at the Java Timer Class 编辑:如果您想暂停执行几秒钟,请看一下Java Timer Class

This is probably happening because you are running that piece of code in the UI thread. 这可能是由于您正在UI线程中运行那段代码而发生的。 In order to avoid the blank screen try running this in a separate thread. 为了避免出现黑屏,请尝试在单独的线程中运行它。

The easiest way to do it is using an AsyncTask. 最简单的方法是使用AsyncTask。 See http://developer.android.com/reference/android/os/AsyncTask.html 参见http://developer.android.com/reference/android/os/AsyncTask.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM