user6842260
user6842260

Reputation:

Android : Decrement a variable daily

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

Answers (4)

Code-Apprentice
Code-Apprentice

Reputation: 83557

You have several choices:

  1. Every time your app starts, load the value from Shared Preferences and decrement it by the number of days which have passed.

  2. Write a service which decrements the values every day.

  3. Write a BroadcastReceiver which starts when the date changes.

Upvotes: 0

Rishabh Dutt Sharma
Rishabh Dutt Sharma

Reputation: 764

If you want to decrement the variable on Daily Basis then

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

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

pamobo0609
pamobo0609

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

Drakosha
Drakosha

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

Related Questions