Search code examples
androidandroid-serviceandroid-workmanagerandroid-13android-reboot

Launch a service after device is unlocked/rebooted with API level > 26


I want to create a simple service on Android 13 that will do a task after the user unlocks the device. I found different ideas on StackOverflow but most of them target the API 25 or bellow. Since then, we can't declare the BroadcastReceiver in the Manifest anymore and I don't see how I can ensure that my app is launched automatically after the phone is unlocked

This service can definitely be foreground if needed and can be killed once the task is complete to avoid wasting battery but I need something to launch it again when the device is unlocked.

I tried looking at different options including:

  • BroadcastReceiver in the manifest, but it no longer works since API 26
  • BroadcastReceiver in the app, but the app has to be launched once for the BroadcastReceiver to be initialized
  • PeriodicWorkManager with Constraints who looked promising but had nothing related to phone being unlocked or at least phone being booted.

If there is no way to this, a solution that would launch the service after a full stop and restart would also be acceptable.

Thank you for your help!


Solution

  • I found a way to do precisely what I wanted: a BroadcastReceiver that listens to "USER_PRESENT". In order to be launched automatically, it has to be declared in the manifest, which is not allowed... except for system apps!

    By having the app built into the OS in the right partition, it will gain the permission to declare the receiver in the manifest and everything will work as intended.

    For now my problem is fixed, but I don't know how people that can't build their OS can fix the issue.