首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在锁定屏幕的情况下在后台运行代码几个小时--可以做到吗?

在锁定屏幕的情况下在后台运行代码几个小时--可以做到吗?
EN

Stack Overflow用户
提问于 2014-12-10 10:35:39
回答 1查看 534关注 0票数 0

当我的应用程序在后台运行,屏幕被锁定时,我缺乏确切发生了什么的信息。一些设置。

我已经创建了一个CLLocationManager并启动了它,我还注册了一个来自高度计更新的处理程序。当然,后台模式是打开的,选定的后台抓取和位置更新,在Plist中添加了所需的键。我最关心的是获取位置更新,并在高度计更新处理程序中做一些工作。在处理程序中,我有一些逻辑,然后我使用NSURLSession将值发布到REST HTTP服务器中。

从我的测试中我注意到,由于用户启动了应用程序,允许位置更新,而我启动了位置管理器和高度计更新,我的高度计处理程序每秒都会被调用大约20-25秒,所以我在服务器中获得了我的读数。

我还注意到,如果我打开应用程序,但没有在ViewController中启动整个过程,而是模拟后台获取,它似乎不会调用高度计处理程序。为什么我不能在模拟后台抓取的时候启动位置管理器,而且到目前为止还没有开始?

当屏幕在10-15分钟后被锁定时有什么限制,当应用程序挂起时Apple后台模式不工作吗?

它没有被系统终止,因为一旦我解锁它,它就会向服务器发送一些消息,就像它在内存中保持暂停一样,处理程序将再次开始更新。另外,我在这里找到了这篇文章,http://mobileoop.com/background-locatio ... - for -ios-7,声称这个方法可以工作3个小时,我不喜欢这个解决方案,但我打算尝试一下,尽管它似乎并不适用于每个人,所以我有疑问。他使用的是我在RW文章中见过的UIBackgroundTaskIdentifier,http://www.raywenderlich.com/29948/back ...ng-for-ios,但还没有嵌入,因为我不确定当屏幕被“永远”锁定时,你是否能够发送POST请求和更新,如果系统不允许这样做,时间可能是足够的。

如果应用程序停止响应,意味着处理程序没有被调用,如果我模拟后台获取处理程序2-3次,但不会启动NSURLSession POST请求。

代码。

代码语言:javascript
复制
// WEELog is just a wrapper function, you could change it to NSLog removing the log level 

- (void) commonInitialization
    {
    self.readingsModel = [WEEReadingsModel new];
    self.locationManager = [CLLocationManager new];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
    self.locationManager.distanceFilter = 500;
    if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
        {
        WEELog(DebugLogLevel, @"I should request location now");
        [self.locationManager requestAlwaysAuthorization];
        }
    self.altimeter = [CMAltimeter new];
    self.isAltimeterAvailable = [CMAltimeter isRelativeAltitudeAvailable];
    }

- (void) start:(void (^)(UIBackgroundFetchResult))completionHandler
    {
    UIBackgroundFetchResult fetchResult = UIBackgroundFetchResultNoData;
    if (self.altimeter == nil ||
        self.locationManager == nil)
        {
        [self commonInitialization]; 
        [self.locationManager startUpdatingLocation]; 
        if (self.isAltimeterAvailable)
            {
            [self.altimeter startRelativeAltitudeUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAltitudeData *altitudeData, NSError *error)
                {
                UIBackgroundFetchResult fetchResult = error == nil ? UIBackgroundFetchResultNoData : UIBackgroundFetchResultFailed;
                if (error == nil)
                    {
                    double previousPressureInInchesOfMercury = self.readingsModel.pressureInInchesOfMercury ? self.readingsModel.pressureInInchesOfMercury.doubleValue : 0.0;
                    [self.readingsModel appendWithAltitudeData:altitudeData];
                    if (self.readingsModel.pressureInInchesOfMercury.doubleValue != previousPressureInInchesOfMercury)
                        {
                        fetchResult = UIBackgroundFetchResultNewData;
                        WEELog(DebugLogLevel, @"New readings to save %@", self.readingsModel.toJSONString);
                        [[WEEServiceRepository sharedInstance] sendReadings:self.readingsModel withCompletionHandler:^(NSError *error, NSURLResponse *response)
                            {
                            NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
                            WEELog(DebugLogLevel, @"Called my completion handler: %@", [NSString stringWithFormat:@"%li - %@", (long)httpResponse.statusCode, [NSHTTPURLResponse localizedStringForStatusCode:httpResponse.statusCode]]);
                            }];
                        }
                    }
                else
                    {
                    WEELog(ErrorLogLevel, @"Error in altimeter handler: %@", error);
                    fetchResult = UIBackgroundFetchResultFailed;
                    }
                }];
        }
   }

- (void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
    {
    CLLocation* location = [locations lastObject];
    if (location != nil)
        {
        WEELog(DebugLogLevel, @"Location update");
        [self.readingsModel appendWithLocation:location];
        }
    }

// Web service call

- (void) sendReadings:(WEEReadingsModel*)readingsModel withCompletionHandler:(WebServiceCompletion)completionHandler
    {
    WEEReachability* reachability = [WEEReachability reachabilityForInternetConnection];
    if (reachability.isReachable &&
        readingsModel)
        {
        NSMutableURLRequest* urlRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:ServerUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
        [urlRequest setHTTPMethod:@"POST"];
        [urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        NSData* originalData = [[NSString stringWithFormat:@"data=%@", readingsModel.toJSONString] dataUsingEncoding:NSUTF8StringEncoding];
        [urlRequest setHTTPBody:originalData];

        if (!self.defaultSessionConfiguration)
            {
            self.defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
            self.urlSession = [NSURLSession sessionWithConfiguration:self.defaultSessionConfiguration delegate:nil delegateQueue:[NSOperationQueue mainQueue]];
            }

        NSURLSessionDataTask* dataTask = [self.urlSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
            {
            WEELog(DebugLogLevel, @"DataTask completion handler is invoked!");
            if (completionHandler)
                {
                completionHandler(error, response);
                }
            }];
        [dataTask resume];
        }
    }

我还没有尝试使用静默推送通知,你认为这是一个合适的解决方案来唤醒我的应用程序,即使应用程序是锁定的,正如我所知,即使应用程序关闭,它也会运行一些代码?

所以我想我最怀念的信息是,当我试图使用in位置更新,高度计后台更新和屏幕锁定时,系统允许我使用这些API的时间?它是具体的,还是系统会决定多久?有没有什么办法让我的应用程序执行这段代码~几个小时?

EN

回答 1

Stack Overflow用户

发布于 2014-12-10 13:13:15

在后台启动音乐/音频(可能是静音)。这将使您的应用程序保持清醒,以便您可以实现您想要的任何功能。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27392446

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档