我试图在电池状态低于5%时发出通知,但我只想要一次。使用以下代码,除非电池电量超出状态,否则它会继续重复。
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);
}
您可以使用变量来检查是否已经调用此方法:
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);
}
}