Android - Controlling a task with Timer and TimerTask?

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() {
       Runnable() {
                        public void run() {
                         Log.d("TIMER", "Timer set off");

    t.schedule(scanTask, 300, 30000); 


  public void stopScan(){

      Log.d("TIMER", "timer canceled");


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?

Asked by: Walter566 | Posted: 20-01-2022

Answer 1

You might consider:

  • 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

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

Answered by: Paul842 | Posted: 21-02-2022

Answer 2

using your code, instead of


the correct way is to cancel your timer (not timerTask):


Answered by: Patrick399 | Posted: 21-02-2022

Answer 3

The Android documentation says that cancel() Cancels the Timer and all scheduled tasks. If there is a currently running task it is not affected. No more tasks may be scheduled on this Timer. Subsequent calls do nothing. Which explains the issue.

Answered by: Kellan275 | Posted: 21-02-2022

Similar questions

Android Service controlling MediaPlayer

All I want to do is simply control background music in my app through a service so I am able to start it and stop it from any activity. I have everything set up perfectly when I tell the service to Toast when it is started and destroyed but as soon as I put the media playin in there instead It starts fine and starts playing the music but as soon as a click a button to stop the service I get an error and a force clo...

java - controlling vibration intensity in android phones? is it possible?

I am developing a game. In which, i want do set different vibration intensities for different events. I just want know if its really possible to control the vibration intensity and duration. Any advice or reference links, could be very helpful. Thanks in advance.

android - Controlling Animation Speed

My app has a small web view that I want to animate into place once the page has finished loading. My code looks like this: view.setVisibility(View.VISIBLE); TranslateAnimation anim=new TranslateAnimation(0.0f, 0.0f, view.getLayoutParams().height, 0.0f); anim.setDuration(5); anim.setInterpolator(new LinearInterpolator()); view.startAnimation(anim); It anim...

android - controlling state of RadioButton

i am gettin 1 problem in d android application that i have made. -> i have a 3 RadioButton's on 1 activity screen -> after a Button is pressed(on same activity) the text associated with all of them should change and all RadioButton's must be unchecked and should be clickable the text is changing properly and the RadioButton's are becoming unchecked but the problem am facing is that: if...

Controlling PC loudness via Android

I want to create an intent on an android phone that sets (or increases/decreases) the loudness of music that gets played on a PC running Windows. Is there some API that helps me?

android - Controlling Activities

I'd like the activity stack for my app to contain multiple instances of the same activity, each working on different data. So I'd have activity A working with data a, b, c and d in my activity stack ad I'd have 4 instances of activity A that I'd call A(a), A(b), A(c) & A(d). I'd also like to arrange it so that if the user asks to work with data c again then it won't start a new activity, but rather will just bring th...

statusbar - controlling the android status bar icon

I am trying to exercise a little control over the state of an icon in the status bar. I want to be able to do the following: Keep the icon visible in the status bar, as long as the app is running, EVEN IF the user chooses to clear the status bar. Clear the icon from the status bar if the app is exited, even (especially) if it is killed? I realize I can remove it when the app is exited explicitly, b...

Controlling Display Refresh Rate on Android Device

Not yet a developer, just trying to find out if an android app can do what I need.. What I need: Simple app that displays a full frame of a single color onscreen at a certain intensity at a fixed frequency! I need it for a synchronization purpose with as high a resolution as possible (achieved by changing an intensity in a known pattern with as high a fixed frequency as possible).

Android - issue in controlling builtin app using Robotium

I am writing an android testing application which automates testing on the device. I am targeting facebook as my base application and writing an app using the Robotium framework in order to accomplish my requirement. Until now i have successfully implemented a few features, but I am stuck at one point: I want to automate the "upload picture" functionality, but as soon as the upload button is clicked, the ...

android - controlling IME show search action instead of enter

Hi I'm trying to override IME action to show search on virtual keyboard. My EditText is in the control that is placed onto the activity. Here is what I have: <EditText android:id="@+id/txtSearch" android:textSize="18dp" android:textColor="@color/main_text_black" android:layout_width="247dp" android:layout_height="fill_parent" android:imeOptions="actionSearch" ...

Still can't find your answer? Check out these communities...

Android Google Support | Android Community | Android Community (Facebook) | Android