开发者

How do you know if a task executes in the background when your app sleeps?

With Objective C memory management, we have the general rule that if you create an object with any of the following techniques, you need to release the object later.

  • alloc
  • new
  • copy
  • mutableCopy

This rule is simple to remember. I'm looking for a analogous simple rule for deciding whether something does background processing when the app sleeps. Does such a definitive list exist?

  • NSUrlRequest - if you send a request out then hit the home button right away, is it possible that my app still processes the server response?
  • Timer - you set off a timer to fire 1 minute from now, but you hit the home button before 1 minute elapse. Does the timer still run, does it get paused, or does it get canceled?
  • For loop - you write a for loop that does a million iterations. You close the app after it's done with 600,000 iterations. What happens to the rest of the 400,000 iterations when the app sleeps and when you re-open the app?
  • And so on...

There's a dozen other things I'm thinking about whenever the app sleeps. I'm worried because ever since I started developing this video camera app, my battery life has been horrible (dropping 50% overnight). Maybe it's 开发者_如何学Goa coincidence or maybe the camera is still recording while the app is sleeping.


It depends on the UIBackgroundModes flags in your bundle to some extent. You can use them to tell iOS that you want to continue running in the background. You can also dynamically request enough time to continue a download for a few minutes using beginBackgroundTaskWithExpirationHandler.

If you do nothing, the default is to suspend your app -- NSTimers will not fire until you return to the foreground. If you are in a loop on the main thread, your app will get a little bit of time to finish it, but the exact amount of time is not specified. If a loop on the main thread takes too long, your app will be terminated even if you are in the foreground.

I'm not 100% sure what happens with NSURLConnections, but I suspect they are canceled by default.

See:

iPhoneOS Programming Guide (PDF), p. 65

As for your battery issue, your app could definitely be responsible for that. The GPS is a notorious battery hog, for example, especially if you continue to run in the background to play audio or do other processing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜