当屏幕被锁定时,我们如何允许我们的应用程序运行

时间:2012-08-27 12:03:26

标签: iphone objective-c ios

我遇到设备锁定问题。如果我的应用程序正在运行且设备被锁定,那么我的应用程序也无法运行我希望我的应用程序即使我的设备被锁定也能正常工作 我的代码如下:

- (void)applicationDidEnterBackground:(UIApplication *)application
{
 [[UIApplication sharedApplication] setIdleTimerDisabled:NO];

 background = YES;

 UIApplication  *app = [UIApplication sharedApplication];

 bgTask  = [app beginBackgroundTaskWithExpirationHandler:^{
  [app endBackgroundTask:bgTask];
  bgTask = UIBackgroundTaskInvalid;
 }];

 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  if (background) {
   StressFreeAlarmViewController *alarmController=[[StressFreeAlarmViewController alloc] initWithNibName:@"StressFreeAlarmViewController" bundle:nil];

   [alarmController setTimer:[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updatingApp) userInfo:nil repeats:YES]];

   background=NO;
  }
 });

}


- (void)applicationDidBecomeActive:(UIApplication *)application
{
 // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
 background = NO;
}

3 个答案:

答案 0 :(得分:1)

评论此行

 [app endBackgroundTask:bgTask];
 bgTask = UIBackgroundTaskInvalid;


here


 UIApplication  *app = [UIApplication sharedApplication];

 bgTask  = [app beginBackgroundTaskWithExpirationHandler:^{
  //[app endBackgroundTask:bgTask];
  //bgTask = UIBackgroundTaskInvalid;
 }];

答案 1 :(得分:1)

设备锁定后,您无法安装应用。但是当应用程序已经在设备中时,您可以阻止通过preventSleepTimer框架锁定,如上面的帖子

当设备被锁定时,错误消息将是:错误:无法启动'/Users/venkateswarlun/Library/Developer/Xcode/DerivedData/XXXXXX-celefkdlufzfpexcvbngfwhpwosr/Build/Products/Debug-iphoneos/XXXXXX.app/XXXXXX' - 设备已锁定

答案 2 :(得分:0)

为此,您需要阻止屏幕锁定以下代码使用

- (void)startPreventSleep {
    // We need to play a sound at least every 10 seconds to keep the iPhone awake.
    // We create a new repeating timer, that begins firing now and then every ten seconds.
    // Every time it fires, it calls -playPreventSleepSound
    self.preventSleepTimer = [[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:0]
                                                  interval:10.0
                                                target:self
                                                  selector:@selector(playPreventSleepSound)
                                                  userInfo:nil
                                                   repeats:YES];
    // We add this timer to the current run loop
    NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
    [runLoop addTimer:self.preventSleepTimer forMode:NSDefaultRunLoopMode];
}

stopPreventSleep可以阻止睡眠。

- (void)stopPreventSleep {
    [self.preventSleepTimer invalidate];
    self.preventSleepTimer = nil;
}

For More detail You can refer the Link Here.