I'm trying to push a notification whenever battery status is below 5% but I want it once only. With below code it's keep on repeating unless battery level gets out of condition.
else if((level<=5)&(level>0)){
batteryState.setImageResource(R.drawable.ic_batterylow);
Notification notificationobject=new NotificationCompat.Builder(MainActivity.this,Notifications.CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_stat_name)
.setContentTitle("Battery Warning")
.setContentText("Your battery is low, please plugin the charger.")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.build();
mNotificationManagerCompatObject.notify(1,notificationobject);
}
You can use a variable to check if you have called this method already or not :
boolean isCalled = false;
else if((level<=5)&(level>0)){
//if you did not called your method once
if(isCalled == false){
//make sure that this will only get called once
isCalled = true;
batteryState.setImageResource(R.drawable.ic_batterylow);
Notification notificationobject=new NotificationCompat.Builder(MainActivity.this,Notifications.CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_stat_name)
.setContentTitle("Battery Warning")
.setContentText("Your battery is low, please plugin the charger.")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.build();
mNotificationManagerCompatObject.notify(1,notificationobject);
}
}