1

I am using broad cast receiver to detect when SCREEN_ON and SCREEN_OFF. Only that time i am getting the values. But i want to detect how much time user SCREEN WAS ON on the device?

Could some plz help me out on this?

user3836168
  • 15
  • 1
  • 3
  • 1
    have you searched the world wide web? [link1](http://stackoverflow.com/questions/5960924/how-to-detect-whether-screen-is-on-or-off-if-api-level-is-4) [link2](http://stackoverflow.com/questions/2575666/how-to-detect-when-the-screen-is-on) – Ker p pag Aug 13 '14 at 06:16

2 Answers2

1

we can use Broadcast for Intent.ACTION_SCREEN_OFF and Intent.ACTION_SCREEN_ON to check whether Screen is ON or OFF.

public class ScreenReceiver extends BroadcastReceiver {

    public static boolean wasScreenOn = true;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            // DO WHATEVER YOU NEED TO DO HERE
            // You can use Timer here to grab Time
            wasScreenOn = false;
        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            // AND DO WHATEVER YOU NEED TO DO HERE
            // You can use Timer here to grab Time
            wasScreenOn = true;
        }
    }

}
SilentKiller
  • 6,944
  • 6
  • 40
  • 75
1

The code given below will help you.

public class myReceiver extends BroadcastReceiver {

public static boolean screenStatus = true;

private Date date1;

private Date date2;

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
        date2 = new Date();

        long difference = date2.getTime() - date1.getTime();
        //screen on for *difference* milliseconds 
        screenStatus = false;

    } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
        date1 = new Date();
        screenStatus = true;
    }
}

}
Kamalone
  • 4,045
  • 5
  • 40
  • 64