How to work out the time a user has opened the app for in android?

100 Views Asked by At

I am trying to implement something that allows me to caluclate the time a user has used the application for, but it seems quite difficult or at least complicated to code. I tried several attempts and logics but failed.

I am not sure whether this is write, but I create two variables as below

    static Date startTime = new Date();
The startTime variable goes in the main activity and it notes the time user launched the app.


     static Date endTime = new Date();
The endTime goes in the onDestroy method and takes the time when the user closes the app.

If this approach is write, I understand I would need to find out the different between the two times but I am not sure how to attempt something like this. Could someone please help, what I want to be able to do is get a final value and pass it to the code below and send it over to Google Analyst for Android;

/*
 * Called after a list of high scores finishes loading.
 *
 * @param loadTime The time it takes, in milliseconds, to load a resource.
 */
public void onLoad(long loadTime) { // I need to put my value instead of loadTime, but I cannot figure out how to find the difference between two times.

  // May return null if EasyTracker has not been initialized with a property
  // ID.
  Tracker easyTracker = EasyTracker.getInstance(this);

  easyTracker.send(MapBuilder
      .createTiming("resources",    // Timing category (required)
                    loadTime,       // Timing interval in milliseconds (required)
                    "high scores",  // Timing name
                    null)           // Timing label
      .build()
  );
}

Thanks and I would really appreciate any help.

1

There are 1 best solutions below

0
On
endTime.getTime() - startTime.getTime()

This will get you the number of milliseconds between two Dates.