`

ios 4 新特性 多任务

 
阅读更多

一:了解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

 

 

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

 

UIBackgroundTaskIdentifier backgroundTask;

 

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

 

  // tell the OS you're about to begin a background task that may need time to finish


    backgroundTask = [application beginBackgroundTaskWithExpirationHandler: ^{
        // 如果超时这个block将被调用
        dispatch_async(dispatch_get_main_queue(), ^{
            if (backgroundTask != UIBackgroundTaskInvalid)
            {
    // do whatever needs to be done
                [application endBackgroundTask:backgroundTask];
                backgroundTask = UIBackgroundTaskInvalid;
            }
        });
    }];
 
  
    // Start the long-running task
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  
        // Do the work!
  [NSThread sleepForTimeInterval:5];
  NSLog(@"Time remaining: %f",[application backgroundTimeRemaining]);
  [NSThread sleepForTimeInterval:5];
  NSLog(@"Time remaining: %f",[application backgroundTimeRemaining]);    
  [NSThread sleepForTimeInterval:5];
  NSLog(@"Time remaining: %f",[application backgroundTimeRemaining]);
  // done!
    
        // call endBackgroundTask - should be executed back on
  // main thread
        dispatch_async(dispatch_get_main_queue(), ^{
            if (backgroundTask != UIBackgroundTaskInvalid)
            {
    // if you don't call endBackgroundTask, the OS will exit your app.
                [application endBackgroundTask:backgroundTask];
                backgroundTask = UIBackgroundTaskInvalid;
            }
        });
    });

 NSLog(@"Reached the end of ApplicationDidEnterBackground - I'm done!");
 
}

 

 

四:本地消息

 

1:创建一个本地消息

 

-(IBAction) scheduleNotification {
    UILocalNotification *local = [[UILocalNotification alloc] init];
    
 // create date/time information
 local.fireDate = [NSDate dateWithTimeIntervalSinceNow:15];
    local.timeZone = [NSTimeZone defaultTimeZone];
 
 // set notification details
    local.alertBody = @"Missing you already!";
    local.alertAction = @"View";
 
 // set the badge on the app icon
    local.applicationIconBadgeNumber = 1;
 
 // Gather any custom data you need to save with the notification
    NSDictionary *customInfo = 
 [NSDictionary dictionaryWithObject:@"ABCD1234" forKey:@"yourKey"];
    local.userInfo = customInfo;
 
 // Schedule it!
    [[UIApplication sharedApplication] scheduleLocalNotification:local];
    
 [local release];

}

 

 

2:delegate 处理方法

 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    
    // Override point for customization after application launch.

    // Add the view controller's view to the window and display.
    [window addSubview:viewController.view];
    [window makeKeyAndVisible];
 
 //程序启动是检查是否有UILocalNotification,如果有跳出提示框
// reset badge 
 application.applicationIconBadgeNumber = 0;
 
    // If the app was closed, and we launched from the notification
    UILocalNotification *local =
    [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
    if (local) {
        UIAlertView *alert = [[UIAlertView alloc]
         initWithTitle:@"You came back! (App was closed)"
       message:@"Nice to see you again!" delegate:nil
       cancelButtonTitle:@"Okay" otherButtonTitles:nil];
  [alert show];
  [alert release];
    }

 
 return YES;
}

 

 

//如果程序完全退出,此方法不会被调用,而是先调用didFinishLaunchingWithOptions把程序启动起来。如果该程序在后台运行收到消息时直接调用该方法
- (void)application:(UIApplication *)application 
didReceiveLocalNotification:(UILocalNotification *)local {

 // reset badge number
 application.applicationIconBadgeNumber = 0; 
 
 if (local) {
  // get custom info from dictionary
  NSString *customInfo = [local.userInfo objectForKey:@"yourKey"];
  // 
        UIAlertView *alert = [[UIAlertView alloc]
         initWithTitle:@"You came back! (App was running)"
         message:customInfo delegate:nil
         cancelButtonTitle:@"Okay" otherButtonTitles:nil];
  [alert show];
  [alert release];
    }
}

 

 

 

五:后台播放音乐

 

 

1:读取文件

 

- (void)viewDidLoad {
    [super viewDidLoad];
 
 self.playPauseButton.titleLabel.text == @"play";
 
 // grab the path to the caf file
 NSString *soundFilePath =
 [[NSBundle mainBundle] pathForResource: @"Rainstorm"
         ofType: @"mp3"];
 
 NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
 
 // create a new AVAudioPlayer initialized with the URL to the file
 AVAudioPlayer *newPlayer =
 [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL
             error: nil];
 [fileURL release];
 
 // set our ivar equal to the new player
 self.player = newPlayer;
 [newPlayer release];
 
 // preloads buffers, gets ready to play
 [player prepareToPlay];
 
 // set delegate so we can get called back when the sound has finished playing
 [player setDelegate: self];
 

  //重要的两行
  // set category of audio
 [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
 // announce that we want to hook up to remote UI events
 [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

 
}

 

 

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

-(BOOL) canBecomeFirstResponder {
       return YES;
}

 

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

-(void) viewDidAppear:(BOOL)animated {
       [self becomeFirstResponder];
}

 

 

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

 

-(void) remoteControlReceivedWithEvent:(UIEvent *)event {
 switch (event.subtype) {
       case UIEventSubtypeRemoteControlTogglePlayPause:
                [self playPause];
       default:
       break;
     }
}

 

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

 

 <key>UIBackgroundModes</key>
 <array>
  <string>audio</string>
 </array>

 

 

 六:NSUserDefaults  问题

 

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

 

-(void) loadSettings: (NSNotification *) notification {
         NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
         [defaults synchronize];
  }

 

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
 
 [self loadSettings:nil];
 
 NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
 [notificationCenter addObserver:self 
      selector:@selector(loadSettings:) 
      name:UIApplicationWillEnterForegroundNotification 
        object:nil];
 
    [super viewDidLoad];
}

 

 

 

七:去除后台运行inof.list

 

application dose not run in background   设置为  true

 

 

 

分享到:
评论

相关推荐

    iOS技术概述

    多任务 12 数据保护 13 苹果推送通知服务 13 本地通知 14 手势识别器 14 文件共享支持 14 点对点服务 15 标准系统视图控制器 15 外部设备支持 16 Cocoa Touch 层包含的框架 16 Address Book UI 框架 16 Event Kit UI...

    ios问答题-这份文档总结了100个iOS开发/设计面试中可能会问到的问题,涵盖了非常全面的内容.md

    针对iOS系统的一些核心技术和新特性,如Handoff、iCloud、iOS扩展、HealthKit、HomeKit、Apple Pay、应用沙盒、辅助功能、多任务处理、游戏中心、iBeacons等,考察面试者对这些技术的理解程度。 3. 编程相关 围绕...

    iOS 6 Programming Cookbook.pdf

     创建多任务感知的应用  使用event kit来管理日程表、日期和事件  运用加速计和陀螺仪  使用icloud服务来增强你的应用  vandad nahavandipoor从事软件开发工作多年,使用过cocoa,cocoa touch,assembly,...

    iOS9-day-by-day, 从iOS9系列开始选择日的项目.zip

    iOS9-day-by-day, 从iOS9系列开始选择日的项目 iOS9-day-by-day苹果在发布到 public的开发者世界中... iOS为用户带来了一些重大的改变,比如iPad的多任务和搜索和Siri增强。 大多数新特性都集中在优化和性能增强方面。

    leetcode答案-iOS-:在网上找的一些iOS面试资料

    iOS面试题-----进程、线程、多进程、多线程、任务、队列、NSThread、GCD、NSOprationQueue... 8、2019 iOS面试题-----多线程相关之GCD、死锁、dispatch_barrier_async、dispatch_group_async、Dispatch Semaphore 9...

    LSTTimer 性能和精度兼得的iOS计时器组件

    LSTTimer 性能和精度兼得的iOS计时器组件github: https://github.com/LoSenTrad/LSTTimer简书: https://www.jianshu.com/p/4f05c7e26bb11.特性提供丰富的api,简单入手使用单例设计,安全且占用内存少,统一管理app所有...

    Cisco路由器配置PPPoE.doc

    当然,还需要有适当的IOS软 件,同时支持PPPoE Client和NAT两个特性、需求最低的IOS是"REMOTE ACCESS SERVER"特性集。以2621为例,运行该IOS只需32M内存、8M Flash,文件名为:c2600-c- mz.122-4.T1.bin ,这就是下面...

    LSTTimer:LSTTimer 性能和精度兼得的iOS计时器组件(QQ群

    在项目开发中,计时器任务的需求很多, LSTTimer的出现就是为了更好统一管理项目中的计时器任务. 欢迎coder们发现问题或者提供更好的idea,一起努力完善 博客地址 github: 简书: 实现思路 LSTTimer单例设计, 内部持有一...

    小白必看的Swift资料

    3. **互动学习**:提供练习题和项目任务,鼓励读者在学习过程中动手实践,加深对Swift语言特性和开发流程的理解。 4. **资源共享**:分享有用的外部资源,如在线课程、书籍、论坛和工具,帮助读者在学习Swift编程时...

    用python实现摄像头来人脸识别的源程序

    Python 3.6版本引入了多项新功能和改进,包括语言特性、库和工具等方面的改进。Python 3.6引入了一种新的字符串格式化语法,称为格式化字面量。它可以方便地在字符串中插入变量值,并支持各种数据类型

    java开源包4

    Java Remote Desktop 是一个Java 的远程桌面软件,支持很多特性例如文件传输、数据压缩、颜色转换、键盘鼠标事件转换等等。 最短路径算法实现 k-shortest-paths 这是一个实现了 Yen 的排名算法的无环路径的项目 ...

    强大的 FTP 服务器软件 Wing FTP Server Corporate 6.4.0.rar

    我们在新版本中添加了Android/iOS的App, 便于手机用户传输文件. 可编程的事件管理器 事件触发时, 可执行Lua脚本, 发送电子邮件 或 执行第三方的应用程序. 负载均衡 & 高可用 可以使用Wing Gateway对WingFTP进行...

    chrome.exe

    另有手机版的Chrome浏览器,于2012年发布了Chrome浏览器移动版,提供IOS系统、安卓系统以及Windows Phone系统的Chrome浏览器,在保持浏览器原有特点的情况下,实现了多终端使用浏览器,具有共享收藏历史信息等功能,...

    runner:Runner-具有Sudo和代理支持的简单多线程SSH

    Runner是一个简单的多线程命令行SSH实用程序,用于快速的即席管理任务和自动化。 Runner已经过测试,可以通过SSH进入Ubuntu,Redhat,Solaris,F5 Bigip和Cisco IOS设备。 特性与功能 提供可调的多线程SSH功能(-t...

    工程硕士学位论文 基于Android+HTML5的移动Web项目高效开发探究

    Activity Activity是一个应用程序组件,提供一个屏幕,用户可以用来交互为了完成某项任务,是一个负责与用户交互的组件 SSH 为 Struts+Spring+Hibernate的一个集成框架,是目前较流行的一种Web应用程序开源框架。...

    Tiercel:简单易用,功能丰富的纯Swift下载框架

    每个下载任务都可以单独操作和管理支持创建多个下载模块,每个模块互不影响每个下载模块拥有单独的管理者,可以对总任务进行操作和管理支持批量操作内置了下载速度,剩余时间等常见的下载信息支持自定义日志支持下载...

    PlanPal:适用于iOS和Android的个人护理应用程序,旨在使用经过心理验证的技术来有效地管理学习计划

    推送通知以提醒您休息,开始下一个任务,补水等(当前未实现)目录特性与功能短期学习时间表短期学习时间表选项使您可以在1小时的多个时间间隔内学习10分钟。 该日程安排的用户输入包括用户当天要处理的任务,用户要...

    java开源包2

    Java Remote Desktop 是一个Java 的远程桌面软件,支持很多特性例如文件传输、数据压缩、颜色转换、键盘鼠标事件转换等等。 最短路径算法实现 k-shortest-paths 这是一个实现了 Yen 的排名算法的无环路径的项目 ...

    iAsyncLite:考虑到函数式编程的更好的 dispatch_async()

    This library is a fork of iAsync.iAsync 存储库增长太多,并且包含许多大多数开发人员不需要的实用功能。 这个 fork 是尝试创建一个轻量级的、模块化的和有据可查的库。 该项目的主要目标: 完全支持原始库中的...

Global site tag (gtag.js) - Google Analytics