IOS4以上的多任务

一:了解multitasking

        background apps(可以在后台运行的任务):

             1:play audio 

             2:get location

             3:voip stream

             4:request time to finish

             5: create notifications

 

二:多任务生命周期

 

1:程序加载成功

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

 

2:程序将要失去活跃状态

- (void)applicationWillResignActive:(UIApplication *)application

 

3:程序已经进入后台运行

- (void)applicationDidEnterBackground:(UIApplication *)application

 

4:程序将要进入前台运行

- (void)applicationWillEnterForeground:(UIApplication *)application

 

5:程序进入活跃状态

- (void)applicationDidBecomeActive:(UIApplication *)application

 

6:程序退出

- (void)applicationWillTerminate:(UIApplication *)application

 

 

从启动到转入后台,从后台转入前台,退出,生命周期函数调用顺序

1->5->2->3->4->5->6

 

 

三:转入后台后请求一段时间完成操作

 

C代码  收藏代码
  1. UIBackgroundTaskIdentifier backgroundTask;  
  2.   
  3.    
  4.   
  5. - (void)applicationDidEnterBackground:(UIApplication *)application {  
  6.   
  7.    
  8.   
  9.   // tell the OS you're about to begin a background task that may need time to finish  
  10.   
  11.   
  12.     backgroundTask = [application beginBackgroundTaskWithExpirationHandler: ^{  
  13.         // 如果超时这个block将被调用  
  14.         dispatch_async(dispatch_get_main_queue(), ^{  
  15.             if (backgroundTask != UIBackgroundTaskInvalid)  
  16.             {  
  17.     // do whatever needs to be done  
  18.                 [application endBackgroundTask:backgroundTask];  
  19.                 backgroundTask = UIBackgroundTaskInvalid;  
  20.             }  
  21.         });  
  22.     }];  
  23.    
  24.     
  25.     // Start the long-running task  
  26.     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{  
  27.     
  28.         // Do the work!  
  29.   [NSThread sleepForTimeInterval:5];  
  30.   NSLog(@"Time remaining: %f",[application backgroundTimeRemaining]);  
  31.   [NSThread sleepForTimeInterval:5];  
  32.   NSLog(@"Time remaining: %f",[application backgroundTimeRemaining]);      
  33.   [NSThread sleepForTimeInterval:5];  
  34.   NSLog(@"Time remaining: %f",[application backgroundTimeRemaining]);  
  35.   // done!  
  36.       
  37.         // call endBackgroundTask - should be executed back on  
  38.   // main thread  
  39.         dispatch_async(dispatch_get_main_queue(), ^{  
  40.             if (backgroundTask != UIBackgroundTaskInvalid)  
  41.             {  
  42.     // if you don't call endBackgroundTask, the OS will exit your app.  
  43.                 [application endBackgroundTask:backgroundTask];  
  44.                 backgroundTask = UIBackgroundTaskInvalid;  
  45.             }  
  46.         });  
  47.     });  
  48.   
  49.  NSLog(@"Reached the end of ApplicationDidEnterBackground - I'm done!");  
  50.    
  51. }  

 

 

四:本地消息

 

1:创建一个本地消息

 

C代码  收藏代码
  1. -(IBAction) scheduleNotification {  
  2.     UILocalNotification *local = [[UILocalNotification alloc] init];  
  3.       
  4.  // create date/time information  
  5.  local.fireDate = [NSDate dateWithTimeIntervalSinceNow:15];  
  6.     local.timeZone = [NSTimeZone defaultTimeZone];  
  7.    
  8.  // set notification details  
  9.     local.alertBody = @"Missing you already!";  
  10.     local.alertAction = @"View";  
  11.    
  12.  // set the badge on the app icon  
  13.     local.applicationIconBadgeNumber = 1;  
  14.    
  15.  // Gather any custom data you need to save with the notification  
  16.     NSDictionary *customInfo =   
  17.  [NSDictionary dictionaryWithObject:@"ABCD1234" forKey:@"yourKey"];  
  18.     local.userInfo = customInfo;  
  19.    
  20.  // Schedule it!  
  21.     [[UIApplication sharedApplication] scheduleLocalNotification:local];  
  22.       
  23.  [local release];  
  24.   
  25. }  

 

 

2:delegate 处理方法

 

C代码  收藏代码
  1. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {      
  2.       
  3.     // Override point for customization after application launch.  
  4.   
  5.     // Add the view controller's view to the window and display.  
  6.     [window addSubview:viewController.view];  
  7.     [window makeKeyAndVisible];  
  8.    
  9.  //程序启动是检查是否有UILocalNotification,如果有跳出提示框  
  10. // reset badge   
  11.  application.applicationIconBadgeNumber = 0;  
  12.    
  13.     // If the app was closed, and we launched from the notification  
  14.     UILocalNotification *local =  
  15.     [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];  
  16.     if (local) {  
  17.         UIAlertView *alert = [[UIAlertView alloc]  
  18.          initWithTitle:@"You came back! (App was closed)"  
  19.        message:@"Nice to see you again!" delegate:nil  
  20.        cancelButtonTitle:@"Okay" otherButtonTitles:nil];  
  21.   [alert show];  
  22.   [alert release];  
  23.     }  
  24.   
  25.    
  26.  return YES;  
  27. }  

 

 

C代码  收藏代码
  1. //如果程序完全退出,此方法不会被调用,而是先调用didFinishLaunchingWithOptions把程序启动起来。如果该程序在后台运行收到消息时直接调用该方法  
  2. - (void)application:(UIApplication *)application   
  3. didReceiveLocalNotification:(UILocalNotification *)local {  
  4.   
  5.  // reset badge number  
  6.  application.applicationIconBadgeNumber = 0;   
  7.    
  8.  if (local) {  
  9.   // get custom info from dictionary  
  10.   NSString *customInfo = [local.userInfo objectForKey:@"yourKey"];  
  11.   //   
  12.         UIAlertView *alert = [[UIAlertView alloc]  
  13.          initWithTitle:@"You came back! (App was running)"  
  14.          message:customInfo delegate:nil  
  15.          cancelButtonTitle:@"Okay" otherButtonTitles:nil];  
  16.   [alert show];  
  17.   [alert release];  
  18.     }  
  19. }  

 

 

 

五:后台播放音乐

 

 

1:读取文件

 

C代码  收藏代码
  1. - (void)viewDidLoad {  
  2.     [super viewDidLoad];  
  3.    
  4.  self.playPauseButton.titleLabel.text == @"play";  
  5.    
  6.  // grab the path to the caf file  
  7.  NSString *soundFilePath =  
  8.  [[NSBundle mainBundle] pathForResource: @"Rainstorm"  
  9.          ofType: @"mp3"];  
  10.    
  11.  NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];  
  12.    
  13.  // create a new AVAudioPlayer initialized with the URL to the file  
  14.  AVAudioPlayer *newPlayer =  
  15.  [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL  
  16.              error: nil];  
  17.  [fileURL release];  
  18.    
  19.  // set our ivar equal to the new player  
  20.  self.player = newPlayer;  
  21.  [newPlayer release];  
  22.    
  23.  // preloads buffers, gets ready to play  
  24.  [player prepareToPlay];  
  25.    
  26.  // set delegate so we can get called back when the sound has finished playing  
  27.  [player setDelegate: self];  
  28.    
  29.   
  30.   //重要的两行  
  31.   // set category of audio  
  32.  [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];  
  33.  // announce that we want to hook up to remote UI events  
  34.  [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];  
  35.   
  36.    
  37. }  

 

 

2:重写canBecomeFirstResponder 方法,使改view 可以成为第一响应者

C代码  收藏代码
  1. -(BOOL) canBecomeFirstResponder {  
  2.        return YES;  
  3. }  

 

 3:显示view时,设置为第一响应者

C代码  收藏代码
  1. -(void) viewDidAppear:(BOOL)animated {  
  2.        [self becomeFirstResponder];  
  3. }  

 

 

4:实现remoteControlReceivedWithEvent方法使程序接收 iphone 自动音乐控制事件

 

C代码  收藏代码
  1. -(void) remoteControlReceivedWithEvent:(UIEvent *)event {  
  2.  switch (event.subtype) {  
  3.        case UIEventSubtypeRemoteControlTogglePlayPause:  
  4.                 [self playPause];  
  5.        default:  
  6.        break;  
  7.      }  
  8. }  

 

 5:info.plist 设置,可以设置多种形式

 

C代码  收藏代码
  1. <key>UIBackgroundModes</key>  
  2. <array>  
  3.  <string>audio</string>  
  4. </array>  

 

 

 六:NSUserDefaults  问题

 

如果程序在后台挂起,在转入到前台后不会调用viewDidLoad 方法,所以要在viewDidLoad 方法里面注册UIApplicationWillEnterForegroundNotification ,调用loadSettings

 

C代码  收藏代码
  1. -(void) loadSettings: (NSNotification *) notification {  
  2.          NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];  
  3.          [defaults synchronize];  
  4.   }  

 

C代码  收藏代码
  1. // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.  
  2. - (void)viewDidLoad {  
  3.    
  4.  [self loadSettings:nil];  
  5.    
  6.  NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];  
  7.  [notificationCenter addObserver:self   
  8.       selector:@selector(loadSettings:)   
  9.       name:UIApplicationWillEnterForegroundNotification   
  10.         object:nil];  
  11.    
  12.     [super viewDidLoad];  
  13. }  

 

 

 

七:去除后台运行inof.list

 

application dose not run in background   设置为  true

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值