简体   繁体   中英

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. 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).

So I created this code in my MainActivity which is in onCreate():

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. The problem here is, notificationtrue is displayed gray and android studio says:

"The value false assigned to notificationtrue is never used"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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