Reputation:
Heyyy, I know how to save variables and other data in SharedPreferences, but I like to know how it would be possible to decrement a variable daily.
Already this var (int) will be in the Shared Preferences, and every day we decrements of -1.
How could I decrement, knowing that the user does not necessarily open the app every day for example?
Have a good day :)
Upvotes: 1
Views: 109
Reputation: 83557
You have several choices:
Every time your app starts, load the value from Shared Preferences and decrement it by the number of days which have passed.
Write a service which decrements the values every day.
Write a BroadcastReceiver
which starts when the date changes.
Upvotes: 0
Reputation: 764
If you want to decrement the variable on Daily Basis then
Implement a BroadcastReceiver and declare it in AndroidManifest.xml with action android.intent.action.DATE_CHANGED. This would run the BroadcastReceiver once in a day when the date is changed.
In onReceive() method you can place code (validations) and persist results into SharedPrefs.
Note: 1. Service would incur huge running cost. 2. Activity would run the same code everytime it opens but BroadCast would run it once a day in a clean and independent fashion.
You might need a Broadcast action BOOT_COMPLETED
as if the device is turned on (reboot).
Upvotes: 1
Reputation: 812
I think using JobScheduler
would be a nice way to implement this. It's available from API 21 and allows the app to execute actions under certain circumstances, even if it's not open. Here's the official doc, and a nice tutorial here.
Upvotes: 0
Reputation: 12165
Save the original date, when the application is opened check for current date and you know what your variable should be :)
Upvotes: 1