Sanshayan
Sanshayan

Reputation: 1076

how to Calculate the screen on time of android device

I am building an application that can calculate the screen on time of a day.
This is my implementation i can't figure out what could be the part in do-while loop

PowerManager powerManager=(PowerManager) getSystemService(POWER_SERVICE);
boolean isScreenOn= powerManager.isScreenOn();
do{

}while(isScreenOn);

Upvotes: 0

Views: 2391

Answers (1)

John Cipponeri
John Cipponeri

Reputation: 892

You can use a modified version of this answer to keep time: https://stackoverflow.com/a/8154095/4380308

Modified Version:


You will only need 2 fields: startTime and elapsedTime

When you want to start recording time, initialise elapsedTime to 0 and startTime to System.currentTimeMillis()

When onPause() is called, initialise elapsedTime using

elapsedTime = elapsedTime + (System.currentTimeMillis() - startTime);

When onResume() is called, initialise startTime to System.currentTimeMillis()

When you're done recording time, the time is

elapsedTime = elapsedTime + (System.currentTimeMillis() - startTime);

Besides onPause() and onResume() you may wish to re-initialize startTime when isScreenOn is false and the loop is broken until isScreenOn is true again, or whatever implementation you decide to use to determine when to and not to record time.

Upvotes: 3

Related Questions