iOS程序进入后台后仍运行定时器NSTimer

步骤一:在Info.plist中,添加"Required background modes"键,value为:App plays audio

步骤二:

  1. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  2. {
  3. self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
  4. // Override point for customization after application launch.
  5. NSError *setCategoryErr = nil;
  6. NSError *activationErr = nil;
  7. [[AVAudioSession sharedInstance]
  8. setCategory: AVAudioSessionCategoryPlayback
  9. error: &setCategoryErr];
  10. [[AVAudioSession sharedInstance]
  11. setActive: YES
  12. error: &activationErr];
  13. self.window.backgroundColor = [UIColor whiteColor];
  14. [self.window makeKeyAndVisible];
  15. return YES;
  16. }
复制代码


步骤三:将以下代码添加到appDelegate文件中的- (void)applicationDidEnterBackgroundUIApplication *)application函数,也可添加到在具体类中注册的应用进入后台后的通知方法

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

  2. UIApplication* app = [UIApplication sharedApplication];
  3. __block UIBackgroundTaskIdentifier bgTask;
  4. bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
  5. dispatch_async(dispatch_get_main_queue(), ^{
  6. if (bgTask != UIBackgroundTaskInvalid)
  7. {
  8. bgTask = UIBackgroundTaskInvalid;
  9. }
  10. });
  11. }];
  12. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  13. dispatch_async(dispatch_get_main_queue(), ^{
  14. if (bgTask != UIBackgroundTaskInvalid)
  15. {
  16. bgTask = UIBackgroundTaskInvalid;
  17. }
  18. });
  19. });
  20. }
复制代码


完成以上步骤你会发现,程序进入后台后仍可运行定时器!

原文链接: http://www.cnblogs.com/zzltjnh/archive/2013/05/15/3080058.html

你可能感兴趣的:(IOS)