Skip to content Skip to sidebar Skip to footer

Timer In Android Service

I want to create an android service that can check on required files every 15 mins. For which, I have created a sample program that plays a text using TTS every ten 10 seconds. An

Solution 1:

In your onStart() method you are initializing the Timer() but you have to check is the timer is running? If it is running then cancel it and start a new timer. Here is the sample code:

publicstaticfinallongNOTIFY_INTERVAL= YOUR_REQUIRED_INTERVAL_IN_SECODE* 1000;

// run on another Thread to avoid crashprivateHandleryourHandler=newHandler();
// timer handlingprivateTimeryourTimer=null;

@OverridepublicvoidonCreate() {
    // cancel if already existedif(yourTimer != null) {
        yourTimer.cancel();
    }
        // recreate new
        yourTimer = newTimer();
    
    // schedule task
    yourTimer.scheduleAtFixedRate(newTimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
}

Here is your TimeDisplayTimerTask():

classTimeDisplayTimerTaskextendsTimerTask {

    @Overridepublicvoidrun() {
        // run on another thread
        yourHandler.post(newRunnable() {

            @Overridepublicvoidrun() {
                // display toastToast.makeText(getApplicationContext(), "some message",
                        Toast.LENGTH_SHORT).show();
            }

        });
    }

To cancel the timer you can just call this

if(yourTimer != null) {
            yourTimer.cancel();
        }`

Notes:

  1. Fixed-rate timers (scheduleAtFixedRate()) are based on the starting time (so each iteration will execute at startTime + iterationNumber * delayTime). Link here
  2. To learn about on Schedule and timer task then view this Link

Thanks. Sorry for bad English.

Solution 2:

TimerTask refresher;

                  timer = new Timer();    
                 refresher = new TimerTask() {
                     publicvoidrun() {


                        //your code 

                     };
                 };
                first event immediately,  following after 1 seconds each
                 timer.scheduleAtFixedRate(refresher, 0,1000); 

//you can change 1000 as your required time. 1000 is equal to 1 second.

You can put this code as in your service class oncreate.. you can call the method which you want to call every fifteen mins in your code section.

Hope this help you .

Solution 3:

You have to reset your timer for every 10 seconds.

sample code:

publicvoidstartTimer(){
  t = newTimer();   
  task = newTimerTask() {

    @Overridepublicvoidrun() {
    runOnUiThread(newRunnable() {

      @Overridepublicvoidrun() {
      TextView tv1 = (TextView) findViewById(R.id.timer);
      tv1.setText(time + "");
      if (time > 0)
       time -= 1;
      else {
       tv1.setText("Welcome");           
      }
     }
    });
   }
  };
  t.scheduleAtFixedRate(task, 0, 1000);
 }

for breif example see my blog post.

I hope this will help you.

Post a Comment for "Timer In Android Service"