Step 1: In info. plist, add the "Required background Modes" key and the value is app plays audio.
Step 2:
- -(Bool) Application :( uiapplication *) Application didfinishlaunchingwitexceptions :( nsdictionary *) launchoptions
- {
- Self. Window = [[[uiwindow alloc] initwithframe: [[uiscreen mainscreen] bounds] autorelease];
- // Override point for customization after application launch.
- Nserror * setcategoryerr = nil;
- Nserror * activationerr = nil;
- [[Avaudiosession sharedinstance]
- Setcategory: avaudiosessioncategoryplayback
- Error: & setcategoryerr];
- [[Avaudiosession sharedinstance]
- Setactive: Yes
- Error: & activationerr];
- Self. Window. backgroundcolor = [uicolor whitecolor];
- [Self. Window makekeyandvisible];
- Return yes;
- }
Copy code
Step 3: Add the following code to the appdelegate file:-(void) applicationdidenterbackgrounduiapplication
*) The application function can also be added to the notification method after the application registered in a specific class enters the background.
- -(Void) applicationdidenterbackground :( uiapplication *) Application {
- Uiapplication * APP = [uiapplication sharedapplication];
- _ Block uibackgroundtaskidentifier bgtask;
- Bgtask = [App beginbackgroundtaskwithexpirationhandler: ^ {
- Dispatch_async (dispatch_get_main_queue (), ^ {
- If (bgtask! = Uibackgroundtaskinvalid)
- {
- Bgtask = uibackgroundtaskinvalid;
- }
- });
- }];
- Dispatch_async (dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^ {
- Dispatch_async (dispatch_get_main_queue (), ^ {
- If (bgtask! = Uibackgroundtaskinvalid)
- {
- Bgtask = uibackgroundtaskinvalid;
- }
- });
- });
- }
Copy code
After completing the above steps, you will find that the timer can still be run after the program enters the background!
Link: http://www.cnblogs.com/zzltjnh/archive/2013/05/15/3080058.html