iOS应用推到后台继续执行

@interface AppDelegate : UIResponder <UIApplicationDelegate> {


    __block UIBackgroundTaskIdentifier _bgTask;


}

@property (nonatomic, strong) NSTimer * pushTimer;


@end



在AppDelegate.m中实现


- (void)timerMethod:(NSTimer *)paramSender

{

    

    

}

- (void)applicationDidEnterBackground:(UIApplication *)application {    

    UIDevice * device = [UIDevice currentDevice];

    if([device respondsToSelector:@selector(isMultitaskingSupported)] && [device isMultitaskingSupported])

    {

        self.pushTimer =  [NSTimer scheduledTimerWithTimeInterval:30.0f target:self selector:@selector(timerMethod:) userInfo:nil repeats:YES];

        

        //iOS系统,借用10分钟(默认就是10分钟)时间。当调用beginBackgroundTaskWithExpirationHandler: 记得必须调用endBackgroundTask:方法,否则iOS会终止你的程序.

        _bgTask = [application beginBackgroundTaskWithExpirationHandler:^

                   {

                    

                       if(_bgTask != UIBackgroundTaskInvalid){

                           [application endBackgroundTask:_bgTask];

                           _bgTask = UIBackgroundTaskInvalid;

                       }

                   }];

        

        

        //如果想提前结束10分钟的后台运行,可在下面加逻辑,目前是空转.

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

            NSInteger remaining = [application backgroundTimeRemaining];

            while (remaining > 30 && _bgTask != UIBackgroundTaskInvalid) {

                sleep(15);

                remaining = [application backgroundTimeRemaining];

                DLog(@"remain %d S", remaining);//iOS 7就只有180秒,但是超过这个时间程序依然可以运行

               

            }

        });

    }

    

}


- (void)applicationWillEnterForeground:(UIApplication *)application {

    DLog(@"程序即将进入【前台】");

    if(_bgTask != UIBackgroundTaskInvalid){

        if(_pushTimer!=nil){

            [_pushTimer invalidate];

        }

        [application endBackgroundTask:_bgTask];

        _bgTask = UIBackgroundTaskInvalid;

    }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值