I want to run a Service only when the user is active or more general: when the phone is active. There is no need that the service runs when the screen is off. But as soon as the user unlocks his phone, I want the service to run again.
How do I achieve this behaviour?
My actual task: I want to capture logcat. Therefore I created a Service which spawns a thread that reads the output of the “logcat” process.
How exactly does that background thread behave when the phone gets locked? It does not hold any wake locks or stuff. Will Android pause the thread when the phone goes to sleep or will that thread keep Android from going to sleep? How will it be resumed after the phone awakes?
I also thought about registering an alarm via ´AlarmManager´ that fires every 15 minutes and parses the logcat. But with this approach I will likely miss some of the logcat lines.
For restarting service:You can register a receiver for
ACTION_USER_PRESENTorACTION_SCREEN_ON: this Intent Sent by system when the user is present(when the phone is active) after device wakes up (e.g when the keyguard is gone). or when phone screen on.For stopping service: use
ACTION_SCREEN_OFFintent this intent send by deivce when user is not present or mobile screen is OFF