Ram
Ram

Reputation: 2530

How to check if a timer is still running or not?

I try to send sms in service.If the sms is not sent means I restart the service after some time, for that I Using the timer.If the sms sent means I want to stop the timer,for stop the timer I use timer.cancel(); before that I've to check the timer is running or not.how to check it?.

             int resultCode = getResultCode();
                 switch (resultCode) 
                 {
                case Activity.RESULT_OK:                 
                             timer.cancel();//Here I want to check timer running or not
                 break;

                 case SmsManager.RESULT_ERROR_GENERIC_FAILURE:  
                     timer_run();
                 break;

                 case SmsManager.RESULT_ERROR_NO_SERVICE:     
                     timer_run();
                 break;

                 case SmsManager.RESULT_ERROR_NULL_PDU:        
                      timer_run();
                  break;

                 case SmsManager.RESULT_ERROR_RADIO_OFF:        
                     timer_run();
                  break;

                 }

Timer Schedule function

    public void timer_run(){        

    TimerTask hourlyTask = new TimerTask () {
        @Override
        public void run () {
             Intent myIntent = new Intent(Myservice.this,Myservice.class); 
             startService(myIntent);


        }
    };
     timer.schedule (hourlyTask, 0l, 500*5*5);
   }    

Upvotes: 6

Views: 21446

Answers (2)

Hasni
Hasni

Reputation: 355

why you don't use Try .... and printStackTrace to do not get the crash message java.lang.IllegalStateException : Timer already cancelled

simply use :

try {
            timer.cancel();
        } catch (Exception r) {
            r.printStackTrace();
        }

Upvotes: -2

Jave
Jave

Reputation: 31846

There is no need to check if the timer is running if all you want to do is cancel() it (This is true for both the Timer and the TimerTask).

The documentation states that

This method may be called repeatedly; the second and subsequent calls have no effect.

Upvotes: 12

Related Questions