Timer Task stops working after indefinite time in android

I am new to android. I am developing an application in which a specific piece of code runs every 5 seconds in the background. For this, I use a timer service with a timer. For some time it works fine, but after some indefinite time my service works, but the timer task automatically stops in android. Here is my code, please help. Thanks in advance.

public void onStart(Intent intent, int startid) { //this is the code for my onStart in service class int delay = 1000; // delay for 1 sec. final int period = 5000; // repeat 5 sec. timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { executeCode(); }, delay, period); }; 
+4
source share
3 answers

In my opinion, you should use AlarmManager with IntentService to schedule repeated background tasks instead of Timer tasks. The timer is unreliable and does not always work correctly in the Android Framework. In addition, the timer will not run if the phone is asleep. You have an alarm that wakes up the phone to execute the code using the AlarmManager.

Cm:

https://developer.android.com/reference/android/app/AlarmManager.html

http://mobile.tutsplus.com/tutorials/android/android-fundamentals-scheduling-recurring-tasks/

http://android-er.blogspot.in/2010/10/simple-example-of-alarm-service-using.html

If the phone restarts, you need to start the alarm manager again. See this tutorial for exact instructions on how to do this:

http://www.androidenea.com/2009/09/starting-android-service-after-boot.html

+4
source

Typically, TimerTask stops when the device goes into sleep mode for a long time. Try using the AlarmManager class for your requirement. AlarmManager also uses less power.

Here is an example how to use AlarmManager

+1
source

I think you can achieve this better if you use CountDown Timer, which has a built-in method that is called after you specify

Example

 public class CountDownTest extends Activity { TextView tv; //textview to display the countdown /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); tv = new TextView(this); this.setContentView(tv); //5000 is the starting number (in milliseconds) //1000 is the number to count down each time (in milliseconds) MyCount counter = new MyCount(5000,1000); counter.start(); } //countdowntimer is an abstract class, so extend it and fill in methods public class MyCount extends CountDownTimer{ public MyCount(long millisInFuture, long countDownInterval) { super(millisInFuture, countDownInterval); } @Override public void onFinish() { tv.setText("done!"); } @Override public void onTick(long millisUntilFinished) { tv.setText("Left: " + millisUntilFinished/1000); } } 

Edit
you can execute any function in the OnTick method that will be called in every 1000 milliseconds in the above example

Read more about it here.

0
source

Source: https://habr.com/ru/post/1443220/


All Articles