androidbroadcastreceiverandroid-intentservice

create a service always for every broadcast receiver?


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?


Solution

  • 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:

    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.

    1. If the work is really light, there's no issues with doing the work in the BroadcastReceiver.

    2. If the work is light but the data is important and can't be risked, then consider doing it in a Service.

    3. 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.