0

I have the following piece of code in my android application. Whenever these lines of code run in my application, the mobile screen goes blank for 10 seconds. This 'problem' is most probably caused by '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

Joel
  • 4,732
  • 9
  • 39
  • 54

2 Answers2

3

The reason you are getting a blank screen for 10 seconds is because this section of code is blocking the UI thread. It has nothing to do with the call to System.currentTimeMillis().

On each for loop iteration, you are checking the time over and over until 1 second has passed. Since you execute the for loop 10 times, you are effectively blocking the UI thread for 10 seconds.

EDIT: If you would like to pause execution for a few seconds, take a look at the Java Timer Class

Joel
  • 4,732
  • 9
  • 39
  • 54
  • Okay thanks for that. I am a relatively new user of eclipse and java. Can you tell me how I can avoid this blank screen? Basically I just want to wait for a few seconds before proceeding to the next part of the code. I am executing it in onActivityResult() – user2904943 Oct 21 '13 at 22:32
  • 1
    Any reason you need to wait so long? Nobody likes watching nothing happen in an app for 10 seconds. – dymmeh Oct 21 '13 at 22:34
  • dymmeh has a fair point.. not sure as to why, but you can take a look at timers in java. See edit – Joel Oct 21 '13 at 22:35
  • I am trying to do some Auto-connect to Wifi.. Since it takes some time to connect to wifi, so i have to wait a few seconds before checking if the connection has been established successfully or has it failed to connect – user2904943 Oct 21 '13 at 22:37
  • 2
    @user2904943 Don't do that. There are better solutions to discover if you are connected and when it connects http://stackoverflow.com/questions/6362314/wifi-connect-disconnect-listener – dymmeh Oct 21 '13 at 22:40
  • Then a timer isn't a good solution. Use a BroadcastReceiver to look at wifi events – Joel Oct 21 '13 at 22:42
2

This is probably happening because you are running that piece of code in the UI thread. In order to avoid the blank screen try running this in a separate thread.

The easiest way to do it is using an AsyncTask. See http://developer.android.com/reference/android/os/AsyncTask.html

Carlos Paulino
  • 736
  • 6
  • 9