Reputation: 91
I have implemented a BatteryStatusBroadcastReceiver in my Android app to display toast messages indicating whether the device is charging or discharging. However, I'm encountering an issue where the toast messages are displayed frequently every time I plug or unplug the charger. I want the toast message to be displayed only once when the charger is plugged or unplugged. How can I modify my code to achieve this?
i tried to search it but unable to find the solution.Below is the code
class BatteryStatusBroadcastReceiver: BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val batteryState = intent?.getIntExtra(BatteryManager.EXTRA_STATUS,-1)
when(batteryState){
BatteryManager.BATTERY_STATUS_CHARGING, BatteryManager.BATTERY_STATUS_FULL -> {
Toast.makeText(context, "Charging", Toast.LENGTH_SHORT).show()
}
BatteryManager.BATTERY_STATUS_DISCHARGING, BatteryManager.BATTERY_STATUS_NOT_CHARGING -> {
Toast.makeText(context, "Discharging", Toast.LENGTH_SHORT).show()
}
}
}
}
Below is my Activity class from where i am registering my broadcast
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
registerReceiver(BatteryStatusBroadcastReceiver(),
IntentFilter(Intent.ACTION_BATTERY_CHANGED)
)
}
}
UPDATE: I came up with below approach ( it's working )
class BatteryStatusBroadcastReceiver: BroadcastReceiver() {
var isCharging = false
var isDischarging = false
override fun onReceive(context: Context?, intent: Intent?) {
val batteryState = intent?.getIntExtra(BatteryManager.EXTRA_STATUS,-1)
if((batteryState == BatteryManager.BATTERY_STATUS_CHARGING || batteryState == BatteryManager.BATTERY_STATUS_FULL) && !isCharging){
isCharging = true
isDischarging = false
Toast.makeText(context, "Charging", Toast.LENGTH_SHORT).show()
}
if((batteryState == BatteryManager.BATTERY_STATUS_DISCHARGING || batteryState == BatteryManager.BATTERY_STATUS_NOT_CHARGING) && !isDischarging){
isCharging = false
isDischarging = true
Toast.makeText(context, "Discharging", Toast.LENGTH_SHORT).show()
}
}
}
Upvotes: 0
Views: 30
Reputation: 61
In Battery Status Receiver it also give battery temperature , because of that when you put mobile in charging it triggers frequently when battery temperature changes , but this does not occurs when device is not charging because at that time temperature stays stable.
Upvotes: 0