Ashokkumar
Ashokkumar

Reputation: 67

How to find the how long my application is visible to the user?

I need to find how long my application is visible on the screen.
But I don't want to calculate the time when the application runs in the background.
I tried the life cycle methods, but it didn't work for me.
Is there any effective method to find how long an application is visible on the screen?

Upvotes: 0

Views: 85

Answers (2)

Joel Fernandes
Joel Fernandes

Reputation: 4856

Get hold of the time at which the activity was put in foreground and the time when it goes into background. Calculate the difference in start and end time, and you'll have the duration of time user has spend.

Example:

@Override
protected void onStart() {
    // TODO Auto-generated method stub
    super.onStart();
    start = 0;
    start = System.currentTimeMillis();
}
@Override
protected void onStop() {
    // TODO Auto-generated method stub
    super.onStop();

    end = System.currentTimeMillis();
    Log.w("activity time ", "" + ((end - start))*0.001); //convert to seconds
}

P.S. Declare long start, end; globally

Upvotes: 1

JanBo
JanBo

Reputation: 2933

Maybe you can try something like this:

Start measuring time in onResume()->when user starts your app so its visible, and stop measuring it in onPause()->you are has been paused and gone of the screen or stopped by the user himself.


Also you can incorporate this in the system to check if the screen is actually on if that suits you better, check the links bellow....but when your app is in the background, the onPause method has been called, so its a pretty efficient way imo.

How can I tell if the screen is on in android?

From an Android service, how to determine whether screen WAS on or off

How to detect whether screen is on or off if API level is 4?

Upvotes: 4

Related Questions