I observed a pattern where all BroadcastReceiver
had a Service
created along with it. I agree that long running process requires service
.
Are there any benefits in creating a service
for all BroadcastReceiver
and use BroadcastReceiver
just to receive a broadcast pass it to the service
?
Is it okay to run a non-complex operations/task in BroadcastReceiver
itself ? Any disadvantages or any anti patterns?
When using BroadcastReceivers, it really depends on the amount of work that's needed to be done.
If the work is light enough and can be completed within 10 seconds, then it's alright to run it straight from the onReceive() method. For light work such as these, it makes less sense to start up a Service just to easily finish that work.
There's only 3 real dangers for doing work inside the BroadcastReceiver:
Doing work in a background thread might cause the BroadcastReceiver to be killed before all work is done. Once the end of onReceive()
is reached, the BroadcastReceiver's process will be considered a low-priority process, so it can potentially be killed if the system requires it. Therefore, doing work in the background might cause your work to not finish properly which is quite dangerous if you're inserting data into a database.
Doing work on the Main Thread to avoid
reaching the end of onReceive()
. I've seen developers do this to combat the previous issue, which causes performance problems due to potentially doing too much work on the Main Thread. I'm sure you know why this is a bad thing.
Doing too much work and exceeding 10 seconds will cause the system to consider your app as not-responding.
Of course, you can actually request to extend the limit for background work a bit through the goAsync()
method, but this isn't a method you should use instead of a Service.
So with those 3 dangers I mentioned, it makes sense why the popular solution for doing more work is to pass the work to a proper Service or JobScheduler.
So it's really up to you to decide which is best for your use case.
If the work is really light, there's no issues with doing the work in the BroadcastReceiver.
If the work is light but the data is important and can't be risked, then consider doing it in a Service.
If the work is heavy, definitely do it through a Service or schedule it as a job in the JobScheduler.
But honestly, my general advice is to use BroadcastReceivers sparingly. Only use them if it's necessary, since having too many registered BroadcastReceivers and services can affect your app's performance.