-->

iOS device On/Off notification

2020-07-30 00:31发布

问题:

I understand that this task requires Private API and the app is not designed for the AppStore.

So, is it possible to know when the system(iOS) is switching to off state and when it wakes up? Maybe it sends some system notifications about that?

回答1:

I assume you're talking about notifications when device is turned on/off.

I was having the same problem and notifications were my first choice. But I found much simpler and more robust solution. You see, usually notifications are sent just one time. For example, if you're building a daemon that will listen to those notifications then you need to be sure that it will be running at the moment when device turn on notification is sent. That's the problem - you can't be sure and probably will miss notification that might help you. It just doesn't look that robust to me.

So obvious solution is to look at system uptime. You can obtain it with this [NSProcessInfo processInfo].systemUptime. In my case I don't need to know right away when device is turned off. I periodically save [NSProcessInfo processInfo].systemUptime value and current date and time at some file in device file system. When device is turned on and my daemon is launched I compare value from the file with current uptime. If current uptime is smaller then device was turned off and turned on. And from the date and time in the file I know when device was turned off.



回答2:

First of all, look at these questions:

Is there a away to detect the event when iOS device goes to sleep mode (when the screen gets blackened)?

Is there a away to detect the event when iOS device goes to sleep mode (when the screen gets blackened)?

Here are couple of private API's which you can be interested in:

void SBGetScreenLockStatus (mach_port_t* port, bool *lockStatus, bool *passcodeEnabled);

Check whether device is locked and passcode protected.

Here you can find a usage: How to find the purple port for the front most application in IOS 5 and above?

Also, there was bunch of system wide notifications which are fired when device is turned on/off.

  • com.apple.mobile.keybagd.lock_status
  • com.apple.springboard.lockstate
  • com.apple.iokit.hid.displayStatus
  • com.apple.springboard.hasBlankedScreen
  • com.apple.springboard.lockcomplete

You can register to them using CFNotificationCenterAddObserver();