You should try working with events based on the display and when it has been enabled the last time.
Register a Broadcast Receiver for ACTION_SCREEN_ON
, ACTION_SCREEN_OFF
and ACTION_USER_PRESENT
and save the timestamp properly.
Please note, that the Screen-Events could be also fired by applications like WhatsApp if they automatically enable the display to show a new message. Due to this fact should you rather stick to ACTION_USER_PRESENT.
Here is some code:
Android-Manifest.xml
<receiver android:name=".UserPresentBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
Broadcast Receiver
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class UserPresentBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent intent) {
/*Sent when the user is present after
* device wakes up (e.g when the keyguard is gone)
* */
if(intent.getAction().equals(Intent.ACTION_USER_PRESENT)){
}
}
}
Credits for the code go to Chathura Wijesinghe
Note: You will need a seperate thread (preferably a daemon-thread) to compare that timestamp with the current time.