Question

I have something in my app that I want the users to only be able to do every 24 hours. how can I do this? I basically want them to click a button and if it has been less than 24 hours since the last time they clicked the button, then a toast pops up telling them to wait. I know I can do getTime() but I dont know how to store that time persistently.

Was it helpful?

Solution 2

SharedPreferences allows you to store persistent data within your app, and you can get current time by System.currentTimeMillis()

final long DURATION = 24 * 60 * 60 * 1000; // 24 hours in milliseconds

yourButton.setOnClickListener(
    new OnClickListener(){

        @Override
        public void onClick(View v) {
            long currentTime = System.currentTimeMillis();
            SharedPreferences settings = getPreferences(MODE_PRIVATE);
            if((currentTime - settings.getLong("last_click", 0)) > DURATION) {
                // Save the new click time
                settings.edit().putLong("last_click", currentTime).commit();

                // Do your stuff here!
            } else {
                // Less than 24 hours, show your toast here!
            }
        }
    }
);

OTHER TIPS

There are a few options you can use, check out this link: http://developer.android.com/guide/topics/data/data-storage.html .

The easiest of these will probably be using Shared Preferences, for example:

   SharedPreferences settings = getPreferences(MODE_PRIVATE);
   // to read a value:
   last_click= settings.getLong("last_click", default_value);

   //to write a value:
   SharedPreferences.Editor editor = settings.edit();
   editor.putLong("last_click", time);
   editor.commit();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top