You should try to work with events based on the display and when it was last turned on.
Register the broadcast receiver for ACTION_SCREEN_ON , ACTION_SCREEN_OFF and ACTION_USER_PRESENT and save the timestamp correctly.
Note that screen events can also be triggered by applications such as WhatsApp if they automatically activate the display to display a new message. In this regard, you should adhere to ACTION_USER_PRESENT .
Here is the 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) { if(intent.getAction().equals(Intent.ACTION_USER_PRESENT)){ } } }
Credits for code go to Chathura Wijesinghe
Note. To compare this timestamp with the current time, you need a separate thread (preferably a daemon thread).
source share