1

正如我们所知,在后台模式下运行的应用程序存在一些限制。例如,NSTimer 不起作用。我试着写一个像这样的“定时器”,它可以在后台模式下工作。

-(UIBackgroundTaskIdentifier)startTimerWithInterval:(NSTimeInterval)interval run:(void (^)())runBlock complete:(void (^)())completeBlock
{
    NSTimeInterval delay_in_seconds = interval;
    dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, delay_in_seconds * NSEC_PER_SEC);
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    // ensure the app stays awake long enough to complete the task when switching apps
    UIBackgroundTaskIdentifier taskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{

        completeBlock();

    }];

    NSLog(@"remain task time = %f,taskId = %d",[UIApplication sharedApplication].backgroundTimeRemaining,taskIdentifier);

    dispatch_after(delay, queue, ^{
        // perform your background tasks here. It's a block, so variables available in the calling method can be referenced here.
        runBlock();

        // now dispatch a new block on the main thread, to update our UI
        dispatch_async(dispatch_get_main_queue(), ^{

            completeBlock();
            [[UIApplication sharedApplication] endBackgroundTask:taskIdentifier];
        });
    });

    return taskIdentifier;

}

我这样调用这个函数:

-(void)fire
{
    self.taskIdentifier = [self startTimerWithInterval:10
                                                   run:^{
                                                           NSLog(@"timer!");
                                                           [self fire];
                                                   }
                                              complete:^{

                                                  NSLog(@"Finished");

                                              }];

}

除了有一个问题外,这个计时器完美无缺。后台任务最长周期为 10 分钟。(请参考 startTimerWithInterval 中的 NSLog)。

有什么办法可以让我的计时器工作超过 10 分钟?顺便说一句,我的应用程序是一个 BLE 应用程序,我已经将 UIBackgroundModes 设置为 bluetooth-central。

4

0 回答 0