简体   繁体   English

如何阻止android通知重复自己

[英]How to stop android notification from repeating itself

I'm trying to push a notification whenever battery status is below 5% but I want it once only.我试图在电池电量低于 5% 时推送通知,但我只想要一次。 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);
           }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM