美文网首页
iOS 监测app 进入后台、活跃、杀死

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

作者: 目染江夏 | 来源:发表于2021-04-13 10:04 被阅读0次

    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 进入后台、活跃、杀死

          本文链接:https://www.haomeiwen.com/subject/ozeqlltx.html