jikazali
jikazali

Reputation: 99

Stop and start timer

Sorry for my english. I have timer and i wand if i click timer is on if i click again timer off. But my timer on only one time. If i click again(off timer) i have exception like this:

E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalStateException: Timer was canceled
    at java.util.Timer.scheduleImpl(Timer.java:561)
    at java.util.Timer.schedule(Timer.java:481)
    at installation.ConnectDevice.callAsynchronousTask(ConnectDevice.java:211)
    at installation.ConnectDevice$1.onClick(ConnectDevice.java:153)
    at android.view.View.performClick(View.java:4240)
    ...

I dont know why its not work, please help. Below my class

My class

private Timer timer;
int time = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.i_connect_device);

    timer = new Timer();

    // my botton
    includeDevice.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (time < 1) {
                callAsynchronousTask();
                time++;
            }

            if (time > 0) {
                stopTimer();
                time--;
            }
        }
    });

}

public void callAsynchronousTask() {
    final Handler handler = new Handler();

    TimerTask doAsynchronousTask = new TimerTask() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    try {
                        Log.e("Timer is work", "Timer is work");
                        // GetMsgs performBackgroundTask = new GetMsgs();
                        // PerformBackgroundTask this class is the class
                        // that extends AsynchTask
                        // performBackgroundTask.execute();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                    }
                }
            });
        }
    };
    timer.schedule(doAsynchronousTask, 0, 1000 * 10); // execute in every
                                                        // 50000 ms
}

public void stopTimer() {
    timer.cancel();
}

Upvotes: 0

Views: 3234

Answers (5)

Krishna V
Krishna V

Reputation: 1821

Change onClick logic as follows (because in your case at the first time only executed callAsynchronousTask() and stopTimer(). so it raises exception at next onClick)

btnTimer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (time == 0) {
                    callAsynchronousTask();
                    time = 1;
                } else {
                    stopTimer();
                    time = 0;
                }
            }
        });

and doAsynchronousTask make it as field and cancel task on stopTimer().

public void stopTimer() {
    doAsynchronousTask.cancel();
}

then it works fine.

Upvotes: 1

Shakeeb Ayaz
Shakeeb Ayaz

Reputation: 6096

Initialize your timer object inside callAsynchronousTask as shown below.

public void callAsynchronousTask() { final Handler handler = new Handler();

    TimerTask doAsynchronousTask = new TimerTask() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    try {
                        Log.e("Timer is work", "Timer is work");
                        //GetMsgs performBackgroundTask = new GetMsgs();
                        // PerformBackgroundTask this class is the class that extends AsynchTask
                        //performBackgroundTask.execute();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                    }
                }
            });
        }
    };
    timer=new Timer();
    timer.schedule(doAsynchronousTask, 0, 1000*10); //execute in every 50000 ms
}

Also modify your in block because it is executing both if condition .

Use boolean flag instead of int

 boolean isTimerRunning;

  if (!isTimerRunning) {
            callAsynchronousTask();
            isTimerRunning=true;
        }

       else (isTimerRunning) {
            stopTimer();
            isTimerRunning=false;
      }

Upvotes: 0

Spencer Williams
Spencer Williams

Reputation: 86

You need an async task it is a class so you can extend it. Public class callAsynchronousTask extends async task And GetMsgs performBackgroundTask = new GetMsgs(); // PerformBackgroundTask this class is the class that extends Async Taskbar goes into the do in background method

Upvotes: 0

AnswerDroid
AnswerDroid

Reputation: 1893

Once you cancel the timer; you cannot start it again because thread is stopped.
See the link:
Pause the timer and then continue it
You have to maintain the state somehow and recreate timer with the current value

Upvotes: 0

Stefan Helmerichs
Stefan Helmerichs

Reputation: 502

From Javadocs:

cancel() : Terminates this timer, discarding any currently scheduled tasks. [...] Once a timer has been terminated, its execution thread terminates gracefully, and no more tasks may be scheduled on it.

and

schedule(Task task, long delay)
throws:
IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.

So basically, your class tells you that it cannot complete the set task due to the fact that the timer has been cancelled. Something you could try is to make the timer sleep until the button is pressed again, instead of cancelling it completely.

Upvotes: 0

Related Questions