我试图在电池电量低于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);
}
答案 0 :(得分:1)
您可以使用变量来检查是否已经调用了此方法:
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);
}
}