Android handler for repeated task - will it overlap? Task timer VS handler VS alarm-manager

I am trying to create an Android app that will run several processes every 10 minutes. As I found out, Handlers more reliable than timers or scheduling. Therefore, I will develop my application using Handlers using the codes below.

I am a little worried that the codes below will create separate Handlers each time the application is launched and keep them working in parallel, maybe since I am creating a Handler on onCreate .

So what is the best way to keep only one Handler running in the background at a time?

 private Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); handler = new Handler(); // new handler handler.postDelayed(runnable, 1000*60*10); // 10 mins int. setContentView(R.layout.activity_pro__sms); } private Runnable runnable = new Runnable() { @Override public void run() { /* my set of codes for repeated work */ foobar(); handler.postDelayed(this, 1000*60*10); // reschedule the handler } }; 
+6
source share
2 answers

I decided to answer my question, as I learned how to do it right. Android way. First of all, what I am trying to do and published in this question is the wrong approach to my requirement. Now I am publishing this so that someone else does not do it wrong, but as follows.

Android has several synchronization options.

  • Timer-task → works while the application is running. best suited for short term. Resource utilization above.

  • The handler → works while the application is running. But not suitable for use as a planner. (this is what I requested, and this is not the right way to do this). Handlers are the best way to do something repeatedly until the application is killed.

  • Alarm-manager → The best way to plan something in the future, even if the application is killed. (this is what I have to apply for my application).

Here is what I understood. Correct me if I am wrong.

+4
source

You can extend the Application class and do your job.

 public class App extends Application { private Handler handler; @Override protected void onCreate() { super.onCreate(); handler = new Handler(); // new handler handler.postDelayed(runnable, 1000*60*10); // 10 mins int. setContentView(R.layout.activity_pro__sms); } private Runnable runnable = new Runnable() { @Override public void run() { /* my set of codes for repeated work */ foobar(); handler.postDelayed(this, 1000*60*10); // reschedule the handler } }; } 

And declare your class in the manifest:

 <application android:name=".App"> 

Edited

But it will only work if your application is running, otherwise you can use AlarmManager .

+3
source

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


All Articles