0

我想在一段时间后触发动作(在生产中将是 30 分钟),现在我正在使用NSTimers scheduledTimerWithTimeInterval。在测试期间(超时为 20 秒,而不是 1800 秒),一切似乎都很好。在调试模式下(从 XCode 运行)一切似乎都很好,因为设备不会自动锁定。但在现实生活中,当应用程序在设备上运行时,自动锁定(准确地说是自动锁定,触发锁定按钮不会)“冻结”计时器(或至少将计时器触发器以某种方式移动到未来)。

我能处理那种情况吗?当然我可以禁用 idleTimerUIApplication sharedApplication但是当应用程序进入后台模式时 ipad 仍然可以自动锁定。

4

2 回答 2

2

其实你可以

首先,为“startTimeOfMyExoticTimer”创建一个默认值到 NSUserDefaults:

[[[NSUserDefaults] standardDefaults] setObject:[NSDate date] forKey:@"startTimeOfMyExoticTimer"];

然后启动计时器以检查有效时间范围是否结束:

[NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(checkIfTimeIsOver) userInfo:nil repeats:YES];

然后实现您的检查器方法:

-(void)checkIfTimeIsOver{
     NSDate * now = [NSDate date];
     NSDate * startTime = [[NSUserDefaults standardDefaults] objectForKey:@"startTimeOfMyExoticTimer"];

     // Here compare your now and startTime objects. (subsract them) and see the difference between them. If your time range is to be set on 30 seconds. Then you should check if the time difference between those objects are bigger than 30 seconds.

}

即使设备被锁定,应用程序在后台等,这也将起作用。

这种方法对我有用,希望它也对你有用

于 2013-08-23T10:28:20.383 回答
0
//Implement this block help your application run background about 10 minutes    

@interface AppDeledate(){
     UIBackgroundTaskIdentifier backgroundTaskId;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // if missing interval exist > start timer again and set missing interval to 0
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
        NSLog(@"Did Enter Background");

        backgroundTaskId = [application beginBackgroundTaskWithExpirationHandler:^{
            NSLog(@"Background Task Expired !!!\n");

            [application endBackgroundTask:backgroundTaskId];
            backgroundTaskId = UIBackgroundTaskInvalid;
                    //save missing interval to NSUserDefault
        }];
    }

    - (void)applicationWillEnterForeground:(UIApplication *)application
    {
        NSLog(@"Will Enter Foreground");

        if (backgroundTaskId && backgroundTaskId != UIBackgroundTaskInvalid) {
            [application endBackgroundTask:backgroundTaskId];



    backgroundTaskId = UIBackgroundTaskInvalid;
        }

    }
于 2013-08-23T16:18:08.463 回答