从iOS服务中检测屏幕的开启/closures

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

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

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

screenOnOffReceiver然后在屏幕打开/closures时被调用。 有没有类似的iOS解决scheme?

编辑:迄今为止我find的最好的是UIApplicationProtectedDataWillBecomeUnavailable( 检测如果iPhone屏幕开/关 ),但它需要用户启用设备上的数据保护(密码保护)。

您可以使用达尔文通知来监听事件。 我不是100%确定的,但从我在越狱的iOS 5.0.1 iPhone 4上运行,看起来,这些事件之一可能是你所需要的:

 com.apple.iokit.hid.displayStatus com.apple.springboard.hasBlankedScreen com.apple.springboard.lockstate 

更新:另外,当手机locking(但不是解锁时)时,会发布以下通知:

 com.apple.springboard.lockcomplete 

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

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

displayStatusChanged是您的事件callback:

 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); } } 

如果您确实希望此代码作为服务在后台运行,并且已经越狱,那么我build议您查看iOS启动后台进程 。 与简单地在后台运行的应用程序相反,启动守护进程可以在重新启动后自动启动,并且不必担心在后台运行任务的应用程序的iOS规则。

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

使用较低级别的通知API,您可以在收到通知时查询锁状态:

 #import <notify.h> int notify_token; notify_register_dispatch("com.apple.springboard.lockstate", &notify_token, dispatch_get_main_queue(), ^(int token) { uint64_t state = UINT64_MAX; notify_get_state(token, &state); NSLog(@"com.apple.springboard.lockstate = %llu", state); }); 

当然,你的应用程序将不得不启动一个UIBackgroundTask来获取通知,这限制了这种技术的有用性,因为iOS允许的运行时间有限。

虽然iPhone屏幕被lockingappdelegate方法“ – (void)applicationWillResignActive:(UIApplication *)应用程序”将被调用,你可以检查。 希望它可以帮助你。