iOS 4后台多任务
今天调查了下IOS 4.0 支持的多任务的事宜,系统是4.2, 初步结果如下:
Ios 4.0 多任务不是传统意义上的多任务。只是把程序的状态保存起来,程序挂起。因为Apple还没准备好多任务同时运行,
主要是因为battery和memory这两个问题还没有解决。
现在IOS 4多任务支持的类型(官网):
§ Background audio
§ Voice over IP
§ Background location
§ Push notifications
§ Local notifications
§ Task finishing - If your app is in mid-task when your customer leaves it, the app can now keep running to finish the task.
§ Fast app switching - All developers should take advantage of fast app switching, which allows users to leave your app and come right back to where they were when they left - no more having to reload the app.
我使用的是Task finishing, 既当用户挂起程序时,如果还有task没完成,可以把改task完成。
但这个是有限制的,时间的限制,就是说你的后台程序不能执行超过某个时间。
我刚才打log看了,系统返回500s,既是8分钟,8分钟如果还没执行完,就会自动把我们程序结束。
代码如下
#pragma mark -
#pragma mark Background Task Handle
- (void)applicationDidEnterBackground:(UIApplication *)application {
// Request permission to run in the background. Provide an
// expiration handler in case the task runs long.
NSAssert(self->bgTask == UIBackgroundTaskInvalid, nil);
self->bgTask = [application beginBackgroundTaskWithExpirationHandler: ^{
// Synchronize the cleanup call on the main thread in case
// the task catully finished at around the same time.
dispatch_async(dispatch_get_main_queue(), ^{
if (UIBackgroundTaskInvalid != self->bgTask) {
[application endBackgroundTask:self->bgTask];
self->bgTask = UIBackgroundTaskInvalid;
}
});
}];
// Start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
^{
// Do the work assoicated with the task.
for(int i = 0; i < 1000; i++) {
//request network.
NSLog(@"hahah %d, Time Remain = %f", i, [application backgroundTimeRemaining]);
}
// Synchronize the cleanup all on the main thread in case
// the task catully finished at around the same time.
dispatch_async(dispatch_get_main_queue(), ^{
if (UIBackgroundTaskInvalid != self->bgTask) {
[application endBackgroundTask:self->bgTask];
self->bgTask = UIBackgroundTaskInvalid;
}
});
});
}
#pragma mark -
#pragma mark Local Notifications
- (void)scheduleAlarmForDate:(NSDate *)theDate {
UIApplication *app = [UIApplication sharedApplication];
NSArray *oldNotifications = [app scheduledLocalNotifications];
// Clear out the old notification before scheduling a new one.
if (0 < [oldNotifications count]) {
[app cancelAllLocalNotifications];
}
// Create a new notification
UILocalNotification *alarm = [[UILocalNotification alloc] init];
if (alarm) {
alarm.fireDate = theDate;
alarm.timeZone = [NSTimeZone defaultTimeZone];
alarm.repeatInterval = 0;
alarm.soundName = @"ping.caf";//@"default";
alarm.alertBody = [NSString stringWithFormat:@"Time to wake up!Now is\n[%@]",
[NSDate dateWithTimeIntervalSinceNow:10]];
[app scheduleLocalNotification:alarm];
[alarm release];
}
}
有问题留言,或者微博:http://t.sina.com.cn/passionuranus