1

每当电池状态低于 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);
            }
4

1 回答 1

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);
           }
        }
于 2019-03-09T15:29:37.110 回答