Search code examples
androidservicebroadcastreceiverintentservice

What is better for battery_changed? broadcast receivers, or service, or intentService?


I want my app to know battery percentage change if the phone is charging.

So I used BroadcastReceiver with ACTION_POWER_CONNECTED and ACTION_POWER_DISCONNECTED to register another BroadcastReceiver with ACTION_BATTERY_CHANGED when the phone is charging, and then I thought "wouldn't it be better if I used Service?"

Then I searched about Service, and I saw IntentService, so now I wonder what is better for ACTION_POWER_CONNECTED and ACTION_POWER_DISCONNECTED, and what is better for ACTION_BATTERY_CHANGED?

I think I should use BroadcastReceiver for ACTION_POWER_CONNECTED and ACTION_POWER_DISCONNECTED, and IntentService for ACTION_BATTERY_CHANGED, am I wrong?

I want ACTION_POWER_CONNECTED and ACTION_POWER_DISCONNECTED to run always and forever(except if I found a better way), and run ACTION_BATTERY_CHANGED when the phone is charging.


Solution

  • BroadcastReceivers and service are two different things

    Broadcast receivers are designed to listen to some events and perform action on it while services are used to do some task in background(without activity) like playing music in background service

    Intent service is designed on top of service for long running tasks that are to be performed on a separate thread

    In your scenario the best answer would be to use a broadcast receiver. It will be called everytime and there is no need to shut it down after you have performed your task unlike services