简体   繁体   中英

Keep accelerometer running when for app to background IOS

I am using the accelerometer in IOS and I want it to run in background mode.

I tried to use CMMotionManager like this but it didn't work:

CMMotionManager*manager= [[CMMotionManager alloc] init];
if(!manager.accelerometerAvailable) {
    NSLog(@"Accelerometer not available");
} else {
    manager.accelerometerUpdateInterval = 0.1;
    NSOperationQueue *motionQueue = [[NSOperationQueue alloc] init];

    [manager startAccelerometerUpdatesToQueue: motionQueue withHandler:
     ^(CMAccelerometerData *data, NSError *error) {
         NSLog(@"Accelerometer data: %@", [data description]);
     }
     ];
}

How can I do this?

Not sure this solves your problem, but a glance at the docs ( http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html ) says:

"Implementing Long-Running Background Tasks

For tasks that require more execution time to implement, you must request specific permissions to run them in the background without their being suspended. In iOS, only specific app types are allowed to run in the background:

  1. Apps that play audible content to the user while in the background, such as a music player app

  2. Apps that keep users informed of their location at all times, such as a navigation app

  3. Apps that support Voice over Internet Protocol (VoIP)

  4. Newsstand apps that need to download and process new content

  5. Apps that receive regular updates from external accessories

Apps that implement these services must declare the services they support and use system frameworks to implement the relevant aspects of those services. Declaring the services lets the system know which services you use, but in some cases it is the system frameworks that actually prevent your application from being suspended."

Not sure if you're trying to use the accelerometer to do any of these things (communicate with a blue tooth device perhaps?), but if so, you'll need to declare the services you support in the app. To do that, you need to add the UIBackgroundModes key to your Info.plist and then add an array containing the relevant string(s) for the services you're trying to use. See the docs page linked above for the full list of the strings.

If you're not trying to use the accelerometer to do any of those things, it looks as if you may be out of luck. Though I'd love to be wrong there.. (anybody?)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM