如何阻止 android 通知自己重复

How to stop android notification from repeating itself

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