从iOS服务检测屏幕开/关

Sun*_*kas 10 notifications objective-c broadcast jailbreak ios

我正在开发一个在后台作为服务运行的网络监视器应用程序.屏幕打开或关闭时是否可以收到通知/电话?

它通过使用以下代码存在于Android中:

private void registerScreenOnOffReceiver()
{
   IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
   filter.addAction(Intent.ACTION_SCREEN_OFF);
   registerReceiver(screenOnOffReceiver, filter);
}
Run Code Online (Sandbox Code Playgroud)

然后在打开/关闭屏幕时调用screenOnOffReceiver.iOS有类似的解决方案吗?

编辑: 到目前为止我发现的最好的是UIApplicationProtectedDataWillBecomeUnavailable(检测iPhone屏幕是否打开/关闭),但它要求用户在设备上启用数据保护(密码保护).

Nat*_*ate 15

您可以使用Darwin通知来侦听事件.我不是百分百肯定,但在我看来,在越狱的iOS 5.0.1 iPhone 4上运行,其中一个事件可能就是你所需要的:

com.apple.iokit.hid.displayStatus
com.apple.springboard.hasBlankedScreen
com.apple.springboard.lockstate
Run Code Online (Sandbox Code Playgroud)

更新:此外,手机锁定时会发布以下通知(但不会解锁时):

com.apple.springboard.lockcomplete
Run Code Online (Sandbox Code Playgroud)

要使用它,请注册这样的事件(这只注册一个事件,但如果这不适合你,请尝试其他事件):

CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), //center
                                NULL, // observer
                                displayStatusChanged, // callback
                                CFSTR("com.apple.iokit.hid.displayStatus"), // event name
                                NULL, // object
                                CFNotificationSuspensionBehaviorDeliverImmediately);
Run Code Online (Sandbox Code Playgroud)

displayStatusChanged你的事件回调在哪里:

static void displayStatusChanged(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo) {
    NSLog(@"event received!");
    // you might try inspecting the `userInfo` dictionary, to see 
    //  if it contains any useful info
    if (userInfo != nil) {
        CFShow(userInfo);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您真的希望此代码作为服务在后台运行,并且您已越狱,我建议您查看iOS Launch Daemons.与您只是在后台运行的应用程序相反,启动守护程序可以在重新启动后自动启动,您不必担心在后台运行任务的应用程序的iOS规则.

让我们知道这是如何工作的!