Android的 - 控制与定时器和TimerTask任务? [英] Android - Controlling a task with Timer and TimerTask?

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

问题描述

目前我正在试图建立一个无线扫描在我的Andr​​oid应用程序,扫描每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.

不过,我希望能够停止和启动,当用户presses一键扫描和我目前遇到问题停止,然后重新启动定时器和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.

下面是我的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();
 }

}

因此​​,定时器和任务启动精细扫描发生每隔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.

有没有更好的方式来做到这一点?还是我失去了一些东西,在定时器/ TimerTask的班?

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

推荐答案

您可能会考虑:

  • 从调用取消检查布尔结果()你的任务,因为它应该指出,如果你的要求是成功还是失败
  • 尝试清除()取消()定时器而不是在的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

如果你并不一定需要定时器的TimerTask ,你可以随时使用 postDelayed ()(可在处理器和任何查看)。这将安排的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的 - 控制与定时器和TimerTask任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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