Android Telling how much time a user has been playing
<p>I have an activity with a Game, and i want to measure the time that a user has been playing.</p>

<p>In the game activity, I have two long variables,</p>

<pre><code>static long stopTime = 0;
static long startTime = -99;
</code></pre>

<p>I have tried to set the starting time in <code>onResume()</code> and ending time in <code>onPause()</code> like this:</p>

<p>onPause:</p>

<pre><code>@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    stopTime = SystemClock.currentThreadTimeMillis();
    Log.d("OnPause","stopTime: "+stopTime);
}
</code></pre>

<p>onResume:</p>

<pre><code>@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    if (startTime == -99)
    {
        startTime = SystemClock.currentThreadTimeMillis();
        Log.d("OnPause","THIS IS RESUME : startTime: "+startTime);
    }
}
</code></pre>

<p>When I initiate <code>startTime</code> at first i give it a value of -99 so only if this is it's value in <code>onResume</code> I update it's value to currentmillis.</p>

<p>Then pass a long which is <code>stopTime - startTime</code> with<br>
<code>putExtra("totalTime", this.stopTime - this.startTime);</code> to another activity which gets this value and presents it to the user. i do this, using a method called moveToEndScreen() that's called when the game ends:</p>

<pre><code>private void moveToEndScreen() {
    // TODO Auto-generated method stub
    Intent i = new Intent(con, EndScreen.class);
    i.putExtra("err", errTimes);
    i.putExtra("timeScore", stopTime - startTime);
    startActivity(i);
}
</code></pre>

<p>and this is what happens on the next activity:</p>

<pre><code>public class EndScreen extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    Intent i = getIntent();
    long timeScore = i.getLongExtra("timeScore",15);
    Log.d("END SCREEN timeScore THAT I GOT IS",timeScore+"");
    float timeResult = timeScore / 1000;
    int errors = i.getIntExtra("err", -1);
    setContentView(R.layout.endscreen);
    TextView stat = (TextView) findViewById(R.id.errMsg);
    stat.setText("You have completed the puzzle in "+errors+" false matches total, and it took you "+timeResult+ " seconds. Can you do better? :)");

}
</code></pre>

<p>}</p>

<p>Having Log.d in <code>onResume</code> and <code>onPause</code> methods with the values of the stop and start times, I see that these methods are running more times than I expect, and give me unreasonable values (negative or zero). Also, i now see when the game ends that the number is changing after 1 sec on the layout from 0 to 3.</p>

<p>How should I go around this?</p>
