简体   繁体   English

只启动一次方法

[英]Initiating a method only once

So this is probably a very basic question, but I couldn't find an answer for it that has worked for me. 因此,这可能是一个非常基本的问题,但是我找不到适合我的答案。 I have a method "notificationsetter()" which starts an alarm for displaying a notification and goes off every 24hrs. 我有一个方法“ notificationsetter()”,它会启动一个警报以显示通知,并且每24小时关闭一次。 The problem is, I have to call the method only once, because if I use it at a time AFTER the alarm has gone off, the notification appears immediately (for example, alarm is set to 7AM, I use the method 10AM, the notification appears immediately at 10AM). 问题是,我只需要调用一次该方法,因为如果在警报消失后一次使用它,通知会立即出现(例如,警报设置为7AM,我使用方法10AM,则该通知会在上午10点立即出现)。

So I created this code in my MainActivity which is in onCreate(): 所以我在onCreate()的MainActivity中创建了以下代码:

boolean notificationtrue = false;
    if(notificationtrue==false) {
        notificationsetter();
        notificationtrue = false;

    }

So the code "should" call the method once, and then, as notificationtrue is always set to true, it is never called again. 因此,代码“应该”调用一次该方法,然后,由于notificationtrue始终设置为true,因此不再调用它。 The problem here is, notificationtrue is displayed gray and android studio says: 这里的问题是,notificationtrue显示为灰色,并且android studio说:

"The value false assigned to notificationtrue is never used" “从未使用分配给notificationtrue的false值”

That means, my code won't work. 就是说,我的代码行不通。 Is there another way to call the method only once? 还有另一种方法可以只调用一次方法吗?

Save a boolean in your preference like this 像这样保存一个布尔值

/**
     * Checks that application runs first time and write flag at SharedPreferences
     *
     * @return true if 1st time
     */
    private boolean isFirstTime() {

        SharedPreferences preferences = getPreferences(MODE_PRIVATE);
        boolean ranBefore = preferences.getBoolean(RetailStoreConstants.FIRST_TIME, false);
        if (!ranBefore) {
            // first time
            SharedPreferences.Editor editor = preferences.edit();
            editor.putBoolean(RetailStoreConstants.FIRST_TIME, true);
            editor.commit();
        }
        return !ranBefore;
    }

then do what you are doing with this boolean. 然后使用此布尔值执行操作。

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

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