As already mentioned, you use a Service.
In addition, using startForeground makes the system less likely to destroy the service if there is a low-on-memory situation. It doesn’t make it invulnerable.
In addition, using START_STICKY allows the system to “revive” the service after a while:
Constant to return from onStartCommand(Intent, int, int): if this service’s process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don’t retain this delivered intent. Later the system will try to re-create the service. Because it is in the started state, it will guarantee to call onStartCommand(Intent, int, int) after creating the new service instance; if there are not any pending start commands to be delivered to the service, it will be called with a null intent object, so you must take care to check for this.
This mode makes sense for things that will be explicitly started and stopped to run for arbitrary periods of time, such as a service performing background music playback.
(source)
But I would like to express the fact that doing these things does not guarantee the service will “survive” if there is a need for more memory. Even if you use START_STICKY and startForeground() that is no guarantee the service will not be killed by the system.
So you cannot make sure it runs constantly with no risk of system kill, but you can decrease the likelihood of it being killed by the system.
As for the broadcast receivers, these can be used to receive data. for an instance, if you want a service that starts on boot, you can create one for that. If you want it to start when a phone call is made, you can create one for that. The common thing though, is to connect that to a service.
And in this service, you may need a thread or a timer to repeat action.
3
solved How to make sure that a class runs in background as long as needed on all devices?