问题描述
我需要在 applicationDidEnterBackground
中做一些事情.但我需要区分哪些用户操作会导致进入背景":屏幕锁定或主页按钮按下.
I need to do something in applicationDidEnterBackground
. But I need to differentiate which user action causes the "enter background": screen lock or home button press.
我正在使用此代码,该代码来自此帖子 - 如何区分 iOS5 上的屏幕锁定和主页按钮按下?:
I was using this code, which is from this post - How to differentiate between screen lock and home button press on iOS5?:
UIApplicationState state = [application applicationState];
if (state == UIApplicationStateInactive) {
NSLog(@"Sent to background by locking screen");
} else if (state == UIApplicationStateBackground) {
NSLog(@"Sent to background by home button/switching to other app");
}
它在 iOS6 上运行良好.但是在 iOS7(设备和模拟器)上,我总是得到 UIApplicationStateBackground
,无论用户点击主页还是锁定按钮.
It works fine on iOS6. but on iOS7 (both device and simulator), I always get UIApplicationStateBackground
, whether the user clicks the home or the lock button.
有人知道是什么导致了这种情况吗?iOS 7 更新多任务后台处理?或者我的应用程序的某些设置(我的应用程序的后台模式已关闭)?
Does someone have an idea about what could cause this? iOS 7 updates to multi-task background handling? Or some setting of my app (my app's background mode is off)?
还有其他解决方案吗?
推荐答案
这可以帮助你在 iOS6 和iOS7 :).
This can help you both on iOS6 & iOS7 :).
当用户按下锁定按钮时,您将收到 com.apple.springboard.lockcomplete
通知.
When user press lock button you will get a com.apple.springboard.lockcomplete
notification.
//new way
//put this in - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
NULL,
displayStatusChanged,
CFSTR("com.apple.springboard.lockcomplete"),
NULL,
CFNotificationSuspensionBehaviorDeliverImmediately);
//put this function in AppDelegate
static void displayStatusChanged(CFNotificationCenterRef center,
void *observer,
CFStringRef name,
const void *object,
CFDictionaryRef userInfo) {
if (name == CFSTR("com.apple.springboard.lockcomplete")) {
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"kDisplayStatusLocked"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
//put this in onAppEnterBackground
UIApplicationState state = [[UIApplication sharedApplication] applicationState];
if (state == UIApplicationStateInactive) {
NSLog(@"Sent to background by locking screen");
} else if (state == UIApplicationStateBackground) {
if (![[NSUserDefaults standardUserDefaults] boolForKey:@"kDisplayStatusLocked"]) {
NSLog(@"Sent to background by home button/switching to other app");
} else {
NSLog(@"Sent to background by locking screen");
}
}
//put this in - (void)applicationWillEnterForeground:(UIApplication *)application
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"kDisplayStatusLocked"];
[[NSUserDefaults standardUserDefaults] synchronize];
这篇关于区分iOS7上的屏幕锁定和主页按钮按下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!