后台运行

在xx-info.plist 里的 "Required background modes" 里加入"App provides Voice over IP services"

然后在delegate里加入以下代码,原理是进入后台时程序会在600秒那样结束任务,我做的就是在结束任务前新开一个任务,再结束旧任务,这样就一直的在后台运行,原链接:http://www.devdiv.com/forum.php?mod=viewthread&tid=200491

#import "AppDelegate.h"

#import "ViewController.h"

@interface AppDelegate ()

{

UIBackgroundTaskIdentifier backgroundTaskIdentifier;

UIBackgroundTaskIdentifier oldBackgroundTaskIdentifier;

NSInteger count;

}

@property (nonatomic,strong) NSTimer *timer;

@end

@implementation AppDelegate

//-(NSTimer *)timer{

//    if (_timer==nil) {

//        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];

//

//        [_timer fire];

//    }

//    return _timer;

//}

- (BOOL) isMultitaskingSupported{

BOOL result = NO;

if ([[UIDevice currentDevice]

respondsToSelector:@selector(isMultitaskingSupported)]){ result = [[UIDevice currentDevice] isMultitaskingSupported];

}

return result;

}

- (void) timerMethod:(NSTimer *)paramSender{

count++;

if (count % 500 == 0) {

UIApplication *application = [UIApplication sharedApplication];

//开启一个新的后台

backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{

}];

//结束旧的后台任务

[application endBackgroundTask:backgroundTaskIdentifier];

oldBackgroundTaskIdentifier = backgroundTaskIdentifier;

}

NSLog(@"%ld",count);

}

- (void)applicationDidEnterBackground:(UIApplication *)application

{

if ([self isMultitaskingSupported] == NO){

return; }

//开启一个后台任务

backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{

}];

oldBackgroundTaskIdentifier = backgroundTaskIdentifier;

if ([self.timer isValid]) {

[self.timer invalidate];

}

self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerMethod:) userInfo:nil repeats:YES];

}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

// Override point for customization after application launch.

//    ViewController *vc = [[ViewController alloc] init];

//    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];

//    self.window.rootViewController = vc;

self.window.backgroundColor = [UIColor whiteColor];

[self.window makeKeyAndVisible];

[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

//    [[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];

//    [self timer];

//    [[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:10000];

return YES;

}

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

// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.

// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.

}

-(void)backgroundHandler{

[self timer];

}

-(void)timerFired{

NSLog(@"%s %@",__func__,_timer);

}

- (void)applicationWillEnterForeground:(UIApplication *)application

{

if (backgroundTaskIdentifier != UIBackgroundTaskInvalid){

[application endBackgroundTask:backgroundTaskIdentifier];

if ([self.timer isValid]) {

[self.timer invalidate];

}

}

}

- (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.

}

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

// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.

}

@end








首先需要配置Info-Plist文件,在里面新建一个Required background modes。这个是一个数组,在下面添加如下内容:

App provides Voice over IP services(VOIP)

App plays audio or streams audio/video using AirPlay(audio)

App processes Newsstand Kit downloads(newsstand-content)

App communicates using CoreBluetooth(bluetooth-central

App shares data using CoreBluetooth(bluetooth-peripheral

App registers for location updates(location)

添加完成后,在- (void)applicationDidEnterBackground:(UIApplication *)application里面添加如下代码

 

  1. __block UIBackgroundTaskIdentifier background_task;
  2. background_task = [application beginBackgroundTaskWithExpirationHandler:^ { [application endBackgroundTask: background_task];
  3. background_task = UIBackgroundTaskInvalid; }];
  4. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  5. while(TRUE) {
  6. [NSThread sleepForTimeInterval:1];
  7. //编写执行任务代码
  8. }
  9. [application endBackgroundTask: background_task]; background_task = UIBackgroundTaskInvalid;
  10. });
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值