Is there a way to detect lock after the app has entered background? For example,
- I have my app (A) open at the foreground
- Then I bring another app (B) to the foreground
- Then lock the screen
Is it possible for (A) to detect the lock?
Is there a way to detect lock after the app has entered background? For example,
Is it possible for (A) to detect the lock?
The answer is "In theory yes, but usually not."
Apps actually have more states than active and background.
The states are:
When the user swaps apps, presses the home button, or locks their device, your app gets notified that it is going into the background, but it actually only runs in the background for a VERY short time. It transitions to suspended almost immediately. Once you're suspended, you can be terminated at any time without further notice.
If you need more time to finish a task when you get notified that you are being moved to the background, you can ask for it using the beginBackgroundTaskWithExpirationHandler
call. However, as of this writing you get at most 3 minutes, and then your expiration handler fires and your app is suspended.
As a result of this, you don't actually get to run in the background for very long and it's likely that by the time the user locks the screen (or it locks automatically) you are already suspended and don't get notified.
Is it possible for (A) to detect the lock?
No, for two reasons:
You cannot detect, under any circumstances, that the screen has been locked. Even if your app is frontmost when the screen is locked, all you learn is that your app was backgrounded, without your being able to learn why.
In your scenario, by the time the screen is locked, your app isn't even running — it has been suspended. So it cannot "detect" anything.