问题
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
回答1:
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
回答2:
- Try using the stuff that you are doing in a separate thread,
- run it continuously till you require,
- make it sleep for 2sec, do your stuff,
- update the main thread from it,
- loop this process
Hope this will help a bit.
来源:https://stackoverflow.com/questions/4203579/sleep-command-for-android