美文网首页移动开发码农的世界IOS 开发
iOS AppDelegate方法,监听进程在后台、被杀死事件

iOS AppDelegate方法,监听进程在后台、被杀死事件

作者: honey缘木鱼 | 来源:发表于2018-07-17 19:04 被阅读5次

AppDelegate中一些常用方法:


- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions{

NSLog(@"启动程序,didFinishLaunchingWithOptions");

returnYES;

}

- (void)applicationWillResignActive:(UIApplication*)application

{

NSLog(@"将变为非活跃状态,applicationWillResignActive");

}

- (void)applicationDidEnterBackground:(UIApplication*)application

{

NSLog(@"进入后台,applicationDidEnterBackground");

}

- (void)applicationWillEnterForeground:(UIApplication*)application

{

NSLog(@"由后台进入前台,applicationWillEnterForeground");

}

- (void)applicationDidBecomeActive:(UIApplication*)application

{

NSLog(@"变为活跃状态,applicationDidBecomeActive");

}

- (void)applicationWillTerminate:(UIApplication*)application

{

NSLog(@"程序被杀死,applicationWillTerminate");

}

- (void)application:(UIApplication*)application handleEventsForBackgroundURLSession:(NSString*)identifier completionHandler:(void(^)(void))completionHandler

{

NSLog(@" 应用处于后台,所有下载任务完成调用,handleEventsForBackgroundURLSession");

}

当进入后台,想继续进行操作,如果没有注册后台任务,可实现如下代码:

先定义一个后台任务标识:UIBackgroundTaskIdentifier backgroundTaskIdentifier;
 
- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // 若不实现该代码,进入后台,不会响应定时器事件
    backgroundTaskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^(){
        // 程序在进入后台一定时间后,我测试是180秒左右,若还未结束后台任务,则会响应该回调,若已结束,则不会进入该回调
        NSLog(@"beginBackgroundTaskWithExpirationHandler");
    }];
    
    // 这里进行需要的操作,可在操作完成调用endBackgroundTask结束后台任务
    [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
}
 
- (void)timerAction
{
    static int a = 0;
    if (a == 100) [self endBackgroundTask];
    NSLog(@"a : %d", a++);
}
 
- (void)endBackgroundTask
{
    [[UIApplication sharedApplication] endBackgroundTask:backgroundTaskIdentifier];
    backgroundTaskIdentifier = UIBackgroundTaskInvalid;
}

监听进程被杀死时,会发现, 程序处于前台被杀死时会调用applicationWillTerminate:方法,程序处于后台时,并不会调用,需要实现如下代码:

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // 实现如下代码,才能使程序处于后台时被杀死,调用applicationWillTerminate:方法
    [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^(){}];
}
 
- (void)applicationWillTerminate:(UIApplication *)application
{
    NSLog(@"程序被杀死,applicationWillTerminate");
}

相关文章

网友评论

    本文标题:iOS AppDelegate方法,监听进程在后台、被杀死事件

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