How to make the counter add only once a day (android)?

Hi, I made an Android application that allows the user to upload a photo taken in the application to facebook or allows you to save the photo on your phone, but I wanted to add a “rating”.

So, if someone uploaded or saved the photo, they would get a point, but I want to limit the number of points received to one point per day, and I'm not sure how I would do it.

+4
source share
1 answer

You may have a SharedPreferencevalue that stores the timestamp of the last photo in milliseconds. Then, whenever the user saves the photo, check the preference value if it does nothing today and if the next day adds an account to the user and updates the preference value to the new timestamp.

Here is the code structure with Joda DateTime.

public void onSavePhoto() {
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    long lastSaveTime = settings.getLong("last_save", 0);
    int lastDay = new DateTime(lastSaveTime).getDayOfYear();
    int today = DateTime.now().getDayOfYear();

    if (lastDay < today) {
        //add score
        addScore();
        //update preference value
        SharedPreferences.Editor editor = settings.edit();
        editor.putLong("last_save", today);
    }
}
+4
source

Source: https://habr.com/ru/post/1530337/


All Articles