如何在iphone处于加速模式或空闲模式时启动和停止CMMotionManager startAccelerating和stopAccelerating?

时间:2013-03-25 10:22:45

标签: iphone ios accelerometer core-motion cmmotionmanager

我正在开发与加速相关的应用程序。我正在使用CMMtionManager对象。但是当我调用startaccelerating方法时它会工作并且在空闲模式下连续调用该方法甚至iphone。 如何在iphone加速和闲置时停止并开始加速。

- (void)viewDidLoad
{
    [super viewDidLoad];
    motionManager=[[CMMotionManager alloc]init];
    motionManager.accelerometerUpdateInterval=2;



- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

     [self startMyMotionDetect];     
}



- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [motionManager stopAccelerometerUpdates];   
 // Request to stop receiving accelerometer events and turn off accelerometer

}


- (CMMotionManager *)motionManager
{
   motionManager = nil;

    id appDelegate = [UIApplication sharedApplication].delegate;

    if ([appDelegate respondsToSelector:@selector(motionManager)]) {
        motionManager = [appDelegate motionManager];
    }

    return motionManager;
}
- (void)startMyMotionDetect
{    NSLog(@"active %d",motionManager.accelerometerActive);

     NSLog(@"availabilty %d",motionManager.accelerometerAvailable);



    [motionManager 
     startAccelerometerUpdatesToQueue:[[NSOperationQueue alloc] init]
     withHandler:^(CMAccelerometerData *data, NSError *error)
     {

         dispatch_async(dispatch_get_main_queue(),
                        ^{
                        NSLog(@"hello");
                            [motionManager stopAccelerometerUpdates];
                        });   

     }];
}

请帮助我。

1 个答案:

答案 0 :(得分:1)

你尝试添加这个吗?:

[[NSNotificationCenter defaultCenter] addObserver:self
                                      selector:@selector(stopAccelerometer)
                                          name:UIApplicationDidEnterBackgroundNotification 
                                        object:nil];