简体   繁体   中英

What does “UIBackgroundTaskInvalid” mean?

I'm developing iPhone app which runs in the background(iOS4), and refer "Completing a Finite Length Task in the Background" written by Apple at the following url

http://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html#//apple_ref/doc/uid/TP40007072-CH5

Then I've been able to implement background tasks. (Of course, I see that application has 10min time limitaiton.) However, I still can't understand what " bgTask = UIBackgroundTaskInvalid; "(Line7,16 of Listing 4-2) means.

In my opinion, the line shown above has never been reached. Because there is " endBackgroundTask: " before that and the background task will be ended. In fact, when I checked with xcode debugger, this thought may be true and not reach at Line7, 16.

If so, is this line redundant? Or is there any reason to have to be written?

I would appreciate any help about this. Thanks in advance.

The code in the block is called if the 10 minutes runs out before the application has completed its background task.

The code in this block must call endBackground: to indicate the situation is acknowledged and accepted by the application - if it doesn't the application will be terminated. Note that calling the method doesn't terminate the application - it simply indicates to the OS that the background task execution has completed.

The second line is simply to reset bgTask to a neutral value, rather than leaving it set id of a task that no longer exists. It's a tidiness thing rather than being essential.

(I wouldn't be surprised if the second line isn't executed until the application is next foregrounded, since once background execution ends the app doesn't get any CPU time to run. Haven't tested this, though)

Key to understanding it is that instead of having a completion Handler you have an expiration Handler. It only executes that line as a 'clean up' of your code taking toooo long.

To clean up it has nuke/kill/end your background task. So first it has to stop it with:

[application endBackgroundTask:bgTask];

Then it also sets a flag on the task so it won't be executed again.

bgTask = UIBackgroundTaskInvalid; 

The reason you see it twice in the code is because either:

  • It successfully runs in the background and gets finished in the dispatch block...so you need to inform the app that hey I'm done.
  • You don't finish in the background but the app is like times up! You gotta go...clean up after yourself by doing a [application endBackgroundTask:bgTask]; + bgTask = UIBackgroundTaskInvalid;

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