有没有办法知道我的应用程序是在后台模式还是前台模式下运行。谢谢。
有没有办法了解Android应用程序是否在前台或后台运行?
[UIApplication sharedApplication].applicationState
将返回应用程序的当前状态,例如:
如果您想通过通知访问,请查看UIApplicationDidBecomeActiveNotification。
Swift 3+
let state = UIApplication.shared.applicationState
if state == .background || state == .inactive {
// background
} else if state == .active {
// foreground
}
switch UIApplication.shared.applicationState {
case .background, .inactive:
// background
case .active:
// foreground
default:
break
}
Objective C
UIApplicationState state = [[UIApplication sharedApplication] applicationState];
if (state == UIApplicationStateBackground || state == UIApplicationStateInactive) {
// background
} else if (state == UIApplicationStateActive) {
// foreground
}
Swift 3
let state: UIApplicationState = UIApplication.shared.applicationState
if state == .background {
// background
}
else if state == .active {
// foreground
}
UIViewController
的viewDidload
中使用这些观察器:let nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
nc.addObserver(self, selector: #selector(appMovedToForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
方法:
@objc func appMovedToBackground() {
}
@objc func appMovedToForeground() {
}
Swift 4
let state = UIApplication.shared.applicationState
if state == .background {
print("App in Background")
}else if state == .active {
print("App in Foreground or Active")
}
如果有人需要使用Swift 3.0
switch application.applicationState {
case .active:
//app is currently active, can update badges count here
break
case .inactive:
//app is transitioning from background to foreground (user taps notification), do what you need when user taps here
break
case .background:
//app is in background, if content-available key of your notification is set to 1, poll to your backend to retrieve data and update your interface here
break
default:
break
}
适用于Swift 4
switch UIApplication.shared.applicationState {
case .active:
//app is currently active, can update badges count here
break
case .inactive:
//app is transitioning from background to foreground (user taps notification), do what you need when user taps here
break
case .background:
//app is in background, if content-available key of your notification is set to 1, poll to your backend to retrieve data and update your interface here
break
default:
break
}
func applicationDidEnterBackground(application: UIApplication) { }
你会接到调用。 - Sanchit Kumar Singh