2

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. And also used a alarm manager to call the service every 30 seconds

The service is call perfectly and even the TTS is played perfectly the first time but when the service is called again after 50 seconds, the timer is not starting from 0 instead starts from 11, 12, 13 - even though I have given cancel().

Can some body help me out on how to solve this?

Below are the code:

public class ServiceLocation extends Service implements OnInitListener
{

TextToSpeech talker;
Timer t;
public int time = 0;

    @Override
public void onCreate() 
{
    super.onCreate();
    Log.e("Location1", "Inside onCreate");
}

public void onStart(Intent intent, int startId) 
{
    super.onStart(intent, startId);

    t = new Timer();
    Log.e("Location1", "Inside onStart");

    talker = new TextToSpeech(this, this);
    testMethod();
 }

 public void testMethod()
 {      
    //Set the schedule function and rate
    t.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run()    {  

            time += 1;
            String todis = String.valueOf(time);


            if(todis.contains("20"))
            {

                talker.speak("Testing Service in a App",TextToSpeech.QUEUE_ADD,null);

                t.cancel();
                t.purge();
            }
        }   

    }, 0, 1000);
}

  public void onInit(int status) 
  {             
   talker.speak("Testing Service in a App",TextToSpeech.QUEUE_ADD,null);
  }
 }
DevAndro
  • 205
  • 1
  • 6
  • 18

3 Answers3

0

TimerTask refresher;

                  timer = new Timer();    
                 refresher = new TimerTask() {
                     public void run() {


                        //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 .

itsrajesh4uguys
  • 4,610
  • 3
  • 20
  • 31
0

You have to reset your timer for every 10 seconds.

sample code:

 public void startTimer(){
  t = new Timer();   
  task = new TimerTask() {

    @Override
   public void run() {
    runOnUiThread(new Runnable() {

      @Override
     public void run() {
      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.

Gunaseelan
  • 14,415
  • 11
  • 80
  • 128
0

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:

public static final long NOTIFY_INTERVAL = YOUR_REQUIRED_INTERVAL_IN_SECODE* 1000;

// run on another Thread to avoid crash
private Handler yourHandler = new Handler();
// timer handling
private Timer yourTimer = null;

@Override
public void onCreate() {
    // cancel if already existed
    if(yourTimer != null) {
        yourTimer.cancel();
    }
        // recreate new
        yourTimer = new Timer();
    
    // schedule task
    yourTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
}

Here is your TimeDisplayTimerTask():

 class TimeDisplayTimerTask extends TimerTask {

    @Override
    public void run() {
        // run on another thread
        yourHandler.post(new Runnable() {

            @Override
            public void run() {
                // display toast
                Toast.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.

Community
  • 1
  • 1
Md. Sajedul Karim
  • 6,749
  • 3
  • 61
  • 87