Jonathon Charles Loch
Jonathon Charles Loch

Reputation: 133

Set up a timer to measure how long an app is running

I'm interested in adding a "Play Time" line into my apps "Statistics" page. However I need a good method to measure the time my app has been opened. What is the best and most efficient way of setting this up? My app consists of multiple activities, so it needs to be able to run through any activity. My MainActivity never closes, it does open other activities that do close onFinish(). So I guess running a timer could occur during MainActivity?

Upvotes: 0

Views: 671

Answers (3)

mjstam
mjstam

Reputation: 1079

Use a shared preference and store a start time when the application is started.

System.currentTimeMillis() // Current time in milliseconds.

On start

    SharedPreferences preferences = context.getSharedPreferences("SomeApp", 0);

    SharedPreferences.Editor editor = preferences.edit();
    editor.putLong("startTime", System.currentTimeMillis() );
    editor.commit();

Then at any point you can pull up this value and calculate time played.

  SharedPreferences preferences = context.getSharedPreferences("SomeApp", 0);
  long start = preferences.getLong( "startTime" );

  long timeRunInMillis = System.currentTimeMillis() - start;

timeRunInMillis will be how long your application has been running in milliseconds.

Upvotes: 1

Matus Danoczi
Matus Danoczi

Reputation: 137

I also think it is better to do this with timestamps, not running the thread and using system resources, such as memory, cpu... Using timestamps on start/ finish of your application should be more efficient.

Upvotes: 1

Dave S
Dave S

Reputation: 3468

Get a timestamp in onResume, get a new timestamp in onPause and save the difference. Both those methods are guaranteed to be called as part of the Activity lifecycle. You could use user preferences to store the value or pass it around to your new activities if the scope of your Main Activity being in the foreground isn't sufficient.

Upvotes: 1

Related Questions