iOS 监测app 进入后台、活跃、杀死

Swift:

   //  - 添加通知的监听
   NotificationCenter.default.addObserver(self, selector: #selector(appBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
   NotificationCenter.default.addObserver(self, selector: #selector(appEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
   NotificationCenter.default.addObserver(self, selector: #selector(applicationWillTerminate), name: UIApplication.willTerminateNotification, object: nil)

   // - 事件处理
   /// 程序进入前台 开始活跃
   @objc func appBecomeActive() {
       print("appBecomeActive")
   }
   /// 程序进入后台
   @objc func appEnterBackground() {
       print("appEnterBackground")
       UIApplication.shared.beginBackgroundTask(expirationHandler: nil)
   }
   /// 程序被杀死
   @objc func applicationWillTerminate() {
       print("app 被杀死")
   }

OC:

//  - 添加通知的监听
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate) name:UIApplicationWillTerminateNotification object:nil];

// - 事件处理
/** 程序进入前台 开始活跃 */
- (void)appBecomeActive {
    NSLog(@"appBecomeActive");
}

/** 程序进入后台 */
- (void)appEnterBackground {
    NSLog(@"appEnterBackground");
    [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
}

/** 程序被杀死 */
- (void)applicationWillTerminate {
    NSLog(@"app 被杀死");
}

你可能感兴趣的:(iOS 监测app 进入后台、活跃、杀死)