Search code examples
androidandroid-emulatorrssiwifimanager

Sleep command for Android


I am writing a small program to periodically poll the RSSI of the WIFI connection. I am using SystemClock.Sleep(2000) in the program.

The problem, I would like to display the RSSI every 2 seconds. But, currently, even though it polls every 2 seconds, the result is displayed only at the end of the loop.

Here is the code snippet:

for(int i=0;i<10;i++)
        {
            Date dt=new Date();
            WifiInfo info = wifi.getConnectionInfo();
            int rssi = info.getRssi();
            textStatus.append("\n\nRSSI :" +Integer.toString(rssi)); 
            SystemClock.sleep(2000);
        }

Would be glad, if you have some suggestion.

Regards Kiran


Solution

  • Don't use sleep in the UI thread.

    Do the following instead:

    • create a MessageHandler (android.os.Handler) that handles messages to be displayed (textStatus.append(...))
    • create a working thread that runs your loop that contains the sleep
    • now the working thread can't directly update the textStatus. Instead send a message from the working thread to the message handler.

    ADDED:

    Here is a useful link that might help you:

    See section "Handling Expensive Operations in the UI Thread"

    http://developer.android.com/guide/appendix/faq/commontasks.html#threading