Android - 使用 Timer 和 TimerTask 控制任务? [英] Android - Controlling a task with Timer and TimerTask?

查看:17
本文介绍了Android - 使用 Timer 和 TimerTask 控制任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试在我的 Android 应用程序中设置 WiFi 扫描,每 30 秒扫描一次 WiFi 接入点.

I am currently trying to set up a WiFi Scan in my Android application that scans for WiFi access points every 30 seconds.

我使用 Timer 和 TimerTask 使扫描按我需要的时间间隔正确运行.

I have used Timer and TimerTask to get the scan running correctly at the intervals which I require.

但是,我希望能够在用户按下按钮时停止和开始扫描,而我目前无法停止然后重新启动 Timer 和 TimerTask.

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.

这是我的代码

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();
 }

}

所以计时器和任务开始正常,扫描每 30 秒发生一次,但我无法停止,我可以停止计时器但任务仍然发生,并且 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.

有没有更好的方法来做到这一点?还是我在 Timer/TimerTask 类中遗漏了什么?

Is there a better way to do this? Or am I missing something in the Timer/TimerTask classes?

推荐答案

您可能会考虑:

  • 检查对您的任务调用 cancel() 的布尔结果,因为它应该表明您的请求是成功还是失败
  • Timer 上尝试 purge()cancel() 而不是 TimerTask
  • Examining the boolean result from calling cancel() on your task, as it should indicate if your request succeeds or fails
  • Try purge() or cancel() on the Timer instead of the TimerTask

如果你不一定需要 TimerTimerTask,你总是可以使用 postDelayed()(在 Handler 和任何 查看).这将安排一个 Runnable 在延迟后在 UI 线程上执行.要让它再次发生,只需在完成您的定期工作后重新安排它自己.然后,您可以监视布尔标志以指示此过程何时结束.例如:

If you do not necessarily need Timer and TimerTask, you can always use postDelayed() (available on Handler and on any View). This will schedule a Runnable to be executed on the UI thread after a delay. To have it recur, simply have it schedule itself again after doing your periodic bit of work. You can then monitor a boolean flag to indicate when this process should end. For example:

private Runnable onEverySecond=new Runnable() {
    public void run() {
        // do real work here

        if (!isPaused) {
            someLikelyWidget.postDelayed(onEverySecond, 1000);
        }
    }
};

这篇关于Android - 使用 Timer 和 TimerTask 控制任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆