【问题标题】:Is there a way, in background, to get my app notified when the CMMotionActivity changes?有没有办法在后台让我的应用在 CMMotionActivity 更改时得到通知?
【发布时间】:2015-01-03 08:34:19
【问题描述】:

我想知道如果 CMMotionActivity 发生变化,系统是否可以在后台唤醒应用程序,例如,如果用户在坐下后开始走路/跑步,我想能够执行一些代码和计划本地通知。

有没有办法让系统为此在后台唤醒我的应用?

编辑:通过查看reference,这似乎是不可能的(“[...] 并且在您的应用暂停时不会提供更新。”),但也许还有其他方法?

【问题讨论】:

  • 您发现了另一种方法吗?
  • @ChristopherMarkieta 不,也许唯一的方法是让应用程序在后台持续运行,但这需要它做一些非常具体的事情,比如播放音乐、进行 VoIP 或 GPS。
  • @ChristopherMarkieta (当然,它可能对电池造成不必要的伤害……)
  • 有一种方法总是在后台使用位置,通过询问位置更新,您可以在后台获取动态更新。

标签: ios swift background-process core-motion


【解决方案1】:

我解决了这个问题,创建了一个后台计时器并在选择器调用方法中检查活动类型。只需查看代码,以防它对您有用。我接受对此的建议、更正和建议。

#define k_timer_time 10.0f
@property NSTimer *timer;

- (void) createBackGroundTimerToCheckMotion{
// create new uiBackgroundTask
__block UIBackgroundTaskIdentifier bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
    [[UIApplication sharedApplication]  endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
}];

__weak __typeof(self) weakSelf = self;

// and create new timer with async call:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    weakSelf.timer = [NSTimer scheduledTimerWithTimeInterval:k_timer_time target:self selector:@selector(onTick:) userInfo:nil repeats:YES];
    weakSelf.timer.tolerance = 5;
    [[NSRunLoop currentRunLoop] addTimer:weakSelf.timer forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
});

}

- (void) onTick:(NStimer*)timer{
if([CMMotionActivityManager isActivityAvailable])
{
    __weak __typeof(self) weakSelf = self;

    CMMotionActivityManager *cm = [[CMMotionActivityManager alloc] init];

    CMPedometer *sc = [[CMPedometer alloc] init];

    NSDate *now = [NSDate date];

    NSDate *last30Sec = [now dateByAddingTimeInterval:-30];

    [cm queryActivityStartingFromDate:last30Sec toDate:now toQueue:[NSOperationQueue mainQueue] withHandler:^(NSArray *activities, NSError *error)
     {
         [activities enumerateObjectsUsingBlock:^(CMMotionActivity *a, NSUInteger idx, BOOL * _Nonnull stop) {
              //Your stuff here

         }];
     }];
}
else
{
    NSLog(@"Error accessing Motion data");
}

}

【讨论】:

    猜你喜欢
    • 2016-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多