Question: What is the most efficient way to update periodically variables in Android?

I have the Integers which values have to be increased every second (only when the app is open) and it should be accessible through all activities/fragments.

Right now this is my code:

*onCreate()* in *MainActivity*:

```
Timer timer = new Timer();
TimerTask updateValues = new UpdateValues();
timer.scheduleAtFixedRate(updateValues, 0, 1000);

```

and *UpdateValues* class:

```
public static final String MY_PREFS_NAME = "MyPrefsFile"
class UpdateValues extends TimerTask {
    public void run() {
        SharedPreferences sharedPref = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();

        int first = sharedPref.getInt("first_key", 0);
        editor.putInt("first_key", first + 1);
        // a lot of stuff in here

        editor.apply();
    }
}

```

Answer: 
Isn't it easier to record how much time the application has been opened and calculate the value of your integer from this? Something like that:

```
public int getValue() {
    return (System.currentMillis() - startTimeMillis) / MILLIS_PER_SECOND;
}

```

You don't really need to mutate any state to count the number of seconds since the application was started, unless I misunderstood your question.
start a NOT\_STICKY Service and put the Timer code in service. So as long as your app is in either foreground or background the variable will keep incrementing itself and as soon as the app closes the service will stop and variable will not increment itself.