IOS Background execution

Source: Internet
Author: User

Transferred from: http://blog.csdn.net/yujianxiang666/article/details/35996005

When the app enters the background, there's a time to do the work.

Or, for some services, you can run for long periods of time, such as playing music.

?

For long-running tasks, you need to add a row to Info.plist, the key is uibackgroundmodes, the value is an array, and you can include several strings as follows:

    • Audio
    • Location
    • Voip
    • Newsstand-content
    • External-accessory
    • Bluetooth-central

?

Then, you can do something in the background.


-(void) Applicationdidenterbackground: (uiapplication *) application {//Use this method to release shared resources, Save user data, invalidate timers, and store enough application state information to restore your application to its Curr       ENT state's it is terminated later. If your application supports background execution, this method is called instead of Applicationwillterminate:when the            User quits.      Uidevice *device = [Uidevicecurrentdevice];      BOOL backgroundsupported = NO;      if ([Device respondstoselector: @selector (ismultitaskingsupported)]) {backgroundsupported = YES;          } __blockuibackgroundtaskidentifier bgtaskid = [Application beginbackgroundtaskwithexpirationhandler:^{          [Application Endbackgroundtask:bgtaskid];      Bgtaskid = Uibackgroundtaskinvalid;            }];              if (backgroundsupported) {Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{    //      }); }  ?

}?

Steps:

1. Add the Uibackgroundmodes key to the Info.plist, and its value is an array, and one of the arrays is a VoIP string:

<key> Uibackgroundmodes</key><array><string>VoIP</string></array>

2. Call the-(void) Setupbackgroundhandler function when the program starts, and the function body is as follows:

?

#pragma mark-voip-(void) setupbackgroundhandler{if (uiudeviceisbackgroundsupported ()) {if ( [[UIApplication sharedapplication] setkeepalivetimeout:600 handler: ^ {[Self requestserverhowm            Anyunreadmessages];        }]) {Udlog (@ "Set Background handler successed!");}    else {//failed Udlog (@ "Set Background handler failed!");}} else {Udlog (@ "This deviece was not Background supported.");}}         -(void) requestserverhowmanyunreadmessages{uiapplication* app = [UIApplication sharedapplication]; if ([app applicationstate] = = uiapplicationstatebackground) {Nsarray * oldnotifications = [App Scheduledlocalnot        Ifications];        if ([oldnotifications count] > 0) [app Cancelalllocalnotifications];        uilocalnotification* alarm = [[[[Uilocalnotification alloc] init] autorelease]; if (alarm) {           Alarm.firedate = [NSDate datewithtimeintervalsincenow:15];            Alarm.timezone = [Nstimezone defaulttimezone];            Alarm.repeatinterval = 0;            Alarm.soundname = Uilocalnotificationdefaultsoundname;            Alarm.alertbody = @ "Time to request MOA2 server!";        [App Schedulelocalnotification:alarm];  }} else if ([app applicationstate] = = uiapplicationstateactive) {Uialertview *alertview = [[Uialertview]        ALLOC] init] autorelease];        [Alertview settitle:@ "alert"];        [Alertview setmessage:@ "time to request MOA2 server!"];        [Alertview addbuttonwithtitle:nslocalizedstring (@ "Cancel", nil)];        [Alertview Setdelegate:nil];    [Alertview show]; }}

?

Explanation:


-(BOOL) Setkeepalivetimeout: (nstimeinterval)timeout? Handler: (Void (^) (void))Keepalivehandler

function function: The app wakes up once every timeout.

0. To successfully invoke this function, you must set the Uibackgroundmodes key in Info.plist to one of the array values of the VoIP string.

1.timeout must be >=600

2. the time interval for waking up the app is not accurate.

3. Only 10 second execution time after wake-up. That is, the code in handler is executed in the 10-second class. The app is blocked again after 10 seconds.

(You can use the-backgroundtimeremaining property to return the remaining time )

4. After the function is successfully called, it is valid for the program life cycle.

The effect of this function is still valid when returning to the foreground. (so it can be used as a timer to make.)?

The 5.clearKeepAliveTimeout function is used to clear the handler.

IOS Background execution

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.