I am currently trying to set up a WiFi Scan in my Android application that scans for WiFi access points every 30 seconds.
I have used Timer and TimerTask to get the scan running correctly at the intervals which I require.
However I want to be able to stop and start the scanning when the user presses a button and I am currently having trouble stopping and then restarting the Timer and TimerTask.
Here is my code
TimerTask scanTask;
final Handler handler = new Handler();
Timer t = new Timer();
public void doWifiScan(){
scanTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
wifiManager.scan(context);
Log.d("TIMER", "Timer set off");
}
});
}};
t.schedule(scanTask, 300, 30000);
}
public void stopScan(){
if(scanTask!=null){
Log.d("TIMER", "timer canceled");
scanTask.cancel();
}
}
So the Timer and Task start fine and the scan happens every 30 seconds however I cant get it to stop, I can stop the Timer but the task still occurs and scanTask.cancel() doesn't seem to work either.
Is there a better way to do this? Or am I missing something in the Timer/TimerTask classes?
question from:
https://stackoverflow.com/questions/2161750/android-controlling-a-task-with-timer-and-timertask 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…