What is better for ScheduledExecutorService or AlarmManager in android?

I am starting, and I am developing an Android application that will continue to send SMS to the user after a certain delay (which takes place after a few days). I want a user registered once to receive an SMS, regardless of whether he is logged in or not. SMS content and mobile phone number are retrieved from the database. Therefore, after research, I found two ways.

  • ScheduledExecutorService

  • Alarmmanager

The problem is that alarmManager will turn off when the phone turns off or reboots. Does this also apply to ScheduledExecutorService? And how many threads should I use in ThreadPool when using the Executor service?

+6
source share
1 answer

Alarm manager

The alarm manager holds the processor tracking lock while the onReceive() receiver is onReceive() . This ensures that the phone will not sleep until you finish working with the broadcast. As soon as onReceive() returns, the alarm manager releases this tracking lock. This means that the phone will sleep in some cases as soon as your onReceive() method completes. If your alarm receiver called Context.startService() , it is possible that the phone will sleep before starting the requested service. To avoid this, your BroadcastReceiver and service will need to implement a separate tracking lockout policy to ensure that the phone continues to work until the service is available.

ScheduledThreadPoolExecutor.

You can use java.util.Timer or ScheduledThreadPoolExecutor (preferred) to schedule an action that happens at regular intervals in the background thread.

Here is an example with the latter:

 ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); scheduler.scheduleAtFixedRate (new Runnable() { public void run() { // call service } }, 0, 10, TimeUnit.MINUTES); 

So I preferred ScheduledExecutorService

But if updates will be performed while your application is running, you can use a timer, as suggested in other answers, or the new ScheduledThreadPoolExecutor. If your application will be updated, even if it is not running, you should go with AlarmManager.

The alarm manager is designed for cases where you want your application code to run at a specific time, even if your application is currently not working.

Please note that if you plan to update when the application is disconnected, then every 10 minutes are quite frequent and may be too energy-intensive.

Also check out this post.

+6
source

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


All Articles