0

Is there a way to detect lock after the app has entered background? For example,

  1. I have my app (A) open at the foreground
  2. Then I bring another app (B) to the foreground
  3. Then lock the screen

Is it possible for (A) to detect the lock?

Grace Huang
  • 5,355
  • 5
  • 30
  • 52

2 Answers2

2

The answer is "In theory yes, but usually not."

Apps actually have more states than active and background.

The states are:

  1. Active
  2. Background (still running, but another app is in the foreground)
  3. Suspended (in memory, but not getting any CPU time)
  4. Not running. (no longer running or in memory.)

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.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • My use case is that, users can switch to another app for a little while (<= 1min) just for changing things , and switch back to our app. If I set a new timer, when the app is put on the background, do you think it is possible? Do you think Apple will allow? – Grace Huang Dec 21 '15 at 19:31
  • I believe they will as long as you only run in the background for a short time, and for a clearly defined reason. I don't claim to speak for Apple though. – Duncan C Dec 21 '15 at 21:01
0

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.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • 1
    As for your first statement, it **is** possible to detect that the screen has been locked. (You use `notify_register_dispatch`. See [**this thread**](http://stackoverflow.com/questions/14229955/is-there-a-way-to-check-if-the-ios-device-is-locked-unlocked).) However, your second reason still holds, making the lock notification not very useful unless your app is set up to run in the background. – Duncan C Dec 21 '15 at 19:16