如何检查计时器是否仍在运行?

Ram*_*Ram 6 android timer

我尝试在服务中发送短信.如果没有发送短信意味着我在一段时间后重新启动服务,为此我使用定时器.如果发送的短信意味着我想停止定时器,为了停止定时器我使用定时器.取消(); 在此之前,我要检查计时器是否正在运行或不检查它.

             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;

                 }
Run Code Online (Sandbox Code Playgroud)

定时器计划功能

    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);
   }    
Run Code Online (Sandbox Code Playgroud)

Jav*_*ave 11

如果您想要做的就是cancel()它,则无需检查定时器是否正在运行(对于Timer和它都是如此TimerTask).

文件说明了这一点

可以重复调用该方法; 第二次和后续的通话都没有效果.

  • 如果我在已经取消的“Timer”对象上调用“cancel()”,我就会得到这个信息。- `java.lang.IllegalStateException:计时器已取消。` (2认同)