gpt4 book ai didi

android - 如何阻止android通知重复自身

转载 作者:行者123 更新时间:2023-11-29 23:17:27 26 4
gpt4 key购买 nike

我试图在电池状态低于 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);
}
}

关于android - 如何阻止android通知重复自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55078715/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com