iOS AppDelegate方法梳理,监听进程在后台、被杀死事件 —— HERO博客

AppDelegate中一些常用方法:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSLog(@"启动程序,didFinishLaunchingWithOptions");
    
    return YES;
}

- (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:^(){
        // 程序在进入后台一定时间后(application.backgroundTimeRemaining,我测试是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,Objective-C技术分享)