timer for broadcast receiver android
I'm developing this application were I do a scan for the reachable access points. I have to do it periodicaly only second after second. I started to do it with a ordinary timerTask, but it didn't worked well because it is alaways creating new threads. So, I started using the handler class in android and calling a postDelayed method to schedule the scan!just like this:
protected void setTimer()
{
final long elapse = 100;
Runnable t = new Runnable() {
public void run()
{
Log.i(TAG3, "startedScan");
IntentFilter filter = new Inten开发者_如何学JAVAtFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
registerReceiver(wifiReceiver, filter);
wifiManager.startScan();
if( !isComplete )
{
mHandler.postDelayed( this, elapse );
}
}
};
mHandler.postDelayed( t, elapse );
}
The problem is that the scan is only running 3 times and then it never runns again..I can't find a solution!How can I solve this?
I'm guessing isComplete
is getting set to true, so the Runnable isn't being re-scheduled. I'd suggest moving the Runnable
out of the method, and then adding the reschedule to wifiReceiver
s onReceive
method.
Runnable t = new Runnable() {
public void run()
{
Log.i(TAG3, "startedScan");
IntentFilter filter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
registerReceiver(wifiReceiver, filter);
wifiManager.startScan();
}
};
protected void setTimer()
{
final long elapse = 100;
mHandler.postDelayed( t, elapse );
}
精彩评论