Search code examples
androidservicebackgroundbroadcastreceiverandroid-manifest

Can a manifest-registered BroadcastReceiver + Service combo operate when its parent application is closed?


I have been trying to get an Android service to take pictures in the background using the action.USER_PRESENT trigger. Suprisingly enough, it works.

I am confused about the mechanisms involved however. Going to list some points below, please correct where I am wrong.

  1. When an intent filter is registered in the BroadCastRecevier via manifest, it will be triggerred even if the app is closed, correct?
  2. The created service runs its methods on a newly created thread, and will execute until end, no matter what.
  3. What are the mechanistic differences in how the service behaves when the app is open, in the background (or stopped in some devices), or destroyed?
  4. action.USER_PRESENT triggers when the user passes his lockscreen?

In addition, I would invite suggestions to alternative triggers to USER_PRESENT, when my condition is that the service be triggered whenever the user is using his device.


Solution

  • When an intent filter is registered in the BroadCastRecevier via manifest, it will be triggerred even if the app is closed, correct?

    Android developers do not use "app is closed", as that is not a specific description. Many things might qualify as "app is closed". In this particular case, your receiver will work even if your process is terminated, which is my guess for what you mean by "app is closed".

    The created service runs its methods on a newly created thread, and will execute until end, no matter what.

    No.

    First, in Java, objects do not run on threads. Methods run on threads.

    Second, there is no requirement that any work done by a service "will execute until end".

    All a service means is that you are telling the OS that you are doing work that is not tied to the foreground UI, and that will hint to the OS to try to keep your process around a little bit longer. How long "a little bit longer" is depends on Android OS version, system RAM, what the other apps on the device are doing, etc.

    What are the mechanistic differences in how the service behaves when the app is open, in the background (or stopped in some devices), or destroyed?

    Apps are not "destroyed". An app's process being terminated is the closest thing that I can think of to what you might mean.

    Once an app's process is terminated, all running code is gone, including any running service code.

    There is no difference in the behavior of the service itself whether the app has foreground UI or not. Having foreground UI means that the app's process is very unlikely to be terminated, assuming that your code does not crash.

    action.USER_PRESENT triggers when the user passes his lockscreen?

    Yes, IIRC.