zoukankan      html  css  js  c++  java
  • iOS后台运行

    让程序在后台长久运行的示例代码如下:

    后台运行

    使用block的另一个用处是可以让程序在后台较长久的运行。在以前,当app被按home键退出后,app仅有最多5秒钟的时候做一些保存或清理资源的工作。但是应用可以调用UIApplication的beginBackgroundTaskWithExpirationHandler方法,让app最多有10分钟的时间在后台长久运行。这个时间可以用来做清理本地缓存,发送统计数据等工作。

    // AppDelegate.h文件
    @property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundUpdateTask;
    
    // AppDelegate.m文件
    - (void)applicationDidEnterBackground:(UIApplication *)application
    {
        [self beingBackgroundUpdateTask];
        // 在这里加上你需要长久运行的代码
        [self endBackgroundUpdateTask];
    }
    
    - (void)beingBackgroundUpdateTask
    {
        self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
            [self endBackgroundUpdateTask];
        }];
    }
    
    - (void)endBackgroundUpdateTask
    {
        [[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];
        self.backgroundUpdateTask = UIBackgroundTaskInvalid;
    }

    安排Local Notification的传递

    UILocalNotification类提供了一种方法来传递local notifications。和push notifications需要设置remote server不同,local notifications 在程序中安排并在当前的设备上执行。满足如下条件可以使用该能力:

    1、一个基于时间的程序,可以在将来特定的时间让程序post 一个alert,比如闹钟

    2、一个在后台运行的程序,post 一个local notification去引起用户的注意

    为了安排local notification 的传递,需要创建一个UILocalNotification的实例,并设置它,使用UIApplication类方法来安排它。Local notification对象包含了所要传递的类型(sound,alert,或者badge)和时间何时呈现) 。UIApplication类方法提供选项去确定是立即传递还是在指定的时间传递。

    - (void)scheduleAlarmForDate:(NSDate*)theDate  
    {  
        UIApplication* app = [UIApplication sharedApplication];  
        NSArray* oldNotifications = [app scheduledLocalNotifications];  
        // Clear out the old notification before scheduling a new one.  
        if ([oldNotifications count] > 0)  
            [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 = @"alarmsound.caf";  
            alarm.alertBody = @"Time to wake up!";  
            [app scheduleLocalNotification:alarm];  
        }  
    } 

    (可以最多包含128个 local notifications active at any given time, any of which can be configured to repeat at a specified interval.)如果在调用该notification的时候,程序已经处于前台,那么application:didReceiveLocalNotification:方法将取而代之。

  • 相关阅读:
    Web Client Software Factory 开发路线图
    Castle ActiveRecord Hands On Lab(1):基本数据访问
    古代武侠武功与现代软件开发
    微软Code Snippet Designer Alpha版发布了
    MSDN WebCast网站全新改版
    AJAX,只是一种过渡技术吗?
    中文网站排行榜:博客园位居博客类16名
    ASP.NET AJAX JavaScript 类浏览器
    .NET开源项目介绍及资源推荐:序
    微软发布WF教程及大量示例
  • 原文地址:https://www.cnblogs.com/tomblogblog/p/4503944.html
Copyright © 2011-2022 走看看