63360

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. 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); } }

Answer1:

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(); }`

<strong>Notes:</strong>

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

Thanks. Sorry for bad English.

Answer2:

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 .

Answer3:

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.

Recommend

  • Plotting points on a map with size depending on category count
  • Cassandra not working with php
  • Set the port number in windows service
  • Android GPS not working in service
  • Testing differences between SqlDecimal and C# Decimal
  • Android - Issue with async tasks
  • using a Looper in a Service is the same as using a separate thread?
  • Must I persist Activity data when onStop() fires?
  • PHP Objects broken, $this is undefined
  • WiX Custom Action Project - BadImageFormatException
  • Current activities onResume() is not called when another Activity is launched from lock screen via n
  • Why do I get this error 'binding to target method' using Delegate.CreateDelegate?
  • Timer inside Android service
  • Wordpress theme Error “Fatal error: Cannot re-assign auto-global variable _POST”
  • $.ajax & passing data to .asmx webservice
  • How to run background service after every 5 sec not working in android 5.1?
  • How to move again MainActivity after sending the mail?
  • Android - Call default browser with and redirect to a designated url
  • Receive custom intent without activity restart
  • Android NFC read Tags issue. Activity starts each time on data received
  • Send data from edittext to listview
  • Fully customized Python Help Usage
  • Swift Initialization Rule Confusion
  • How to upload specific List image using click on Upload button
  • Blackberry 6: how to detect a long click on track pad?
  • How can go in last activity with resume button?
  • Android application: how to use the camera and grab the image bytes?
  • Creating Java object from class name with constructor, which contains parameters [duplicate]
  • how to avoid repetitive constructor in children
  • Dialing with Intent.ACTION_CALL stopps at # in phone number
  • Deleting and Updating values from a cusrsor adapter
  • Possible to stop flickering java tooltip in heavyweight mode?
  • Can a Chrome extension content script make an jQuery AJAX request for an html file that is itself a
  • Upload files with Ajax and Jquery
  • AngularJs get employee from factory
  • Proper way to use connect-multiparty with express.js?
  • How to set the response of a form post action to a iframe source?
  • Change div Background jquery
  • Qt: Run a script BEFORE make
  • reshape alternating columns in less time and using less memory