What happens to an iPhone app when iPhone goes into stand-by mode? - iphone

My app uses NSTimer and it appears that NSTimer doesn't fire when the iPhone goes into the stand-by mode (either by pressing the hardware button or by the idle timer).
When I activate the iPhone again, my app is still in the foreground. What happens to third party apps when the iPhone is the stand-by mode?

Although it's not evident here, I believe the original poster did find an answer to his question by starting a thread (available here) in the iPhone Developer Forums (which I eventually had to find myself because the information wasn't shared here).
In case someone else has the same question and finds the page in the future, here's a helpful response that was posted by someone on the Apple forum called "eskimo1" (which I have edited slightly such that it is easier to read without having the context provided by the entire original thread):
Regarding iPhone app status terminology, "active" does not mean "awake", it means "attached to the GUI". Think of it being analogous to "frontmost" in Mac OS X. When you lock the device your app deactivates but the device may or may not go to sleep
iPhone OS rarely sleeps if the device is connected to main power (i.e., via USB). It can sleep if running on battery, however.
A short time after the screen is locked (20 seconds according to Oliver Drobnik), the device sleeps. This is like closing the lid on your laptop; all activity on the main CPU halts.
This does not happen if the device is playing audio in the right audio session. See DTS Q&A QA1626 "Audio Session - Ensuring audio playback continues when screen is locked" for details.
Note that the idleTimerDisabled property (which can be turned on to prevent the screen from turning off while the app is running) is about locking the screen after user inactivity. It's not directly related to system sleep (it's indirectly related in that the system may sleep shortly after it's locked).

See Application Interruptions in the iPhone OS Programming Guide, especially the applicationWillResignActive and applicationDidBecomeActive events. (The whole guide is certainly worth reading.) When You ignore the events, the timer seems to go on for a while and then stops. Sounds logical, the application could easily drain the battery if kept running. And what exactly happens to the application? I guess it simply does not get any CPU time – it freezes and only thaws when You turn the machine back “on.”

My first advice is do not disable the idle timer, that is just a hack. If you want to keep a timer alive during UI events run the timer on the current run loop using NSCommonModes:
// create timer and add it to the current run loop using common modes
self.timer = [NSTimer timerWithTimeInterval:.1 target:self selector:#selector(handleTimer) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];

I used the information on this post for a small sample that I was building. This is the code that I used when I initiated the playback to prevent the audio from stopping:
AudioSession.Category = AudioSessionCategory.MediaPlayback;
And when the application is done with the playback to reset to the original value:
AudioSession.Category = AudioSessionCategory.SoloAmbientSound;
The full sample is here:
http://github.com/migueldeicaza/monotouch-samples/tree/master/StreamingAudio/

I was faced with this issue recently in an app I am working on that uses several timers and plays some audio prompts and made two relatively simple changes:
In the AppDelegate I implemented the following methods and there mere presence allows the app to continue when the screen is locked
// this receives the notification when the device is locked
- (void)applicationWillResignActive:(UIApplication *)application
{
}
// this receives the notification that the application is about to become active again
- (void)applicationWillBecomeActive:(NSNotification *)aNotification
{
}
references: UIApplicationDelegate Protocol Reference & NSApplication Class Reference in the API doc (accessible via Xcode, just search for applicationWillBecomeActive).
Made the main viewcontroller class an AVAudioPlayerDelegate and used this code from Apple's "AddMusic" sample to make the audio alerts the app played mix nicely into the iPod audio etc...
I just dropped this code into a method that is called during viewDidLoad. If this interests you, you fall into the "who should read this doc" category for this: Audio Session Programming Guide
// Registers this class as the delegate of the audio session.
[[AVAudioSession sharedInstance] setDelegate: self];
// The AmbientSound category allows application audio to mix with Media Player
// audio. The category also indicates that application audio should stop playing
// if the Ring/Siilent switch is set to "silent" or the screen locks.
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: nil];
// Activates the audio session.
NSError *activationError = nil;
[[AVAudioSession sharedInstance] setActive: YES error: &activationError];

I believe your application should run normally when suspended. (think Pandora Radio)
Check to see if your timer is being deallocated due to your view being hidden or some other event occurring.

Related

Alarm clock with answer-to-disable on iOS

Apple resources contain a lot of informations but there's one thing which I can't clearly understand reading about audio and notification.
Is it possible to make an app, running in background which produce sound (even if phone is locked and/or silenced) and when it's happend user must solve eg. equation to turn it off?
p.s. For now I mostly use Cordova framework but Obj-C tip will also be nice.
Yes it is posssible.
You can use UILocalNotification for this.
Also apple allows apps that are playing music in background.
Please check these links for the background task feature:
ManagingYourApplicationsFlow
ios multitasking background tasks
How to handle background audio playing while ios device is locked or on another
You can change Local Notifications for NSTimers (keeping them alive in inactive mode with https://github.com/mruegenberg/MMPDeepSleepPreventer) and calculate the time interval for each alarm. That way you can then play an audio even with the screen locked and the sound off pasting this in your - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions:
// Let the sound run with the screen blocked
NSError *setCategoryErr = nil;
NSError *activationErr = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&setCategoryErr];
[[AVAudioSession sharedInstance] setActive:YES error:&activationErr];
But you will have some problems:
The app must be playing an audio file each 10 seconds so it doesn´t deep sleep and kills all NSTimers.
Apple could reject your app for doing so.
You can´t close the app with the home button, otherwise, it won´t work.
You must open the app every time you need to use the alarm (you can´t schedule and forget).
When the alarm fires, you only have the lock screen of the iPhone and need to unlock it first and then stop the alarm from inside the app.
In Apple they don´t want competitors for their alarm clock app, that's for sure! Almost all the alarm clock apps you see in the App Store use this poor approach.

iOS 5 Audio Alarms Don't Sound Without kAudioSessionProperty_OverrideCategoryMixWithOthers On

I have an audio app that is having some problems with the way iOS 5 has changed audio behaviors. When my app's audio is playing (AVAudioSessionCategoryPlayback), and a Clock.app alarm or timer is fired from the OS, the UIAlertView notification pops up, but without the audio alert. My application sound ducks fine to get out of the way of the audio alert, but the alarm app's audio alert does not sound.
Naturally, tons of support requests poured in over the iOS 5 change. I have solved this temporarily by setting kAudioSessionProperty_OverrideCategoryMixWithOthers which lets the alarm audio come through, but there are a few very undesirable side-effects when doing this:
Other app's audio can play with/over mine.
The remote control events are not routed to my app, but to iPod.app.
None of the above drawbacks are acceptable for my app's requirements. I have been hacking away at this for some time now but haven't been able to crack it. How can I setup my audio such that:
My app's audio still uses the AVAudioSessionCategoryPlayback category for background audio.
The Clock.app alarms still have their audio alerts make sound
The app still responds to remote control notifications
After writing this question I went to file a bug report on this. I created a small sample project that I thought would replicate the issue, but I could not replicate it! This caused me to dig in deep once again and try to figure out what was up here…
I fired up an iOS alarm, then I placed a break point in audioPlayerBeginInterruption: and traced through my code line by line in the debugger. I noticed that before my code ran (while I was paused in the debugger), the iOS 5 alarm was sounding! Luckily it still sounded even as I was stepping through my app, so I was able to figure out which pieces of code specifically caused it to stop sounding.
Part of my interruptionHandler is to (obviously) stop the internal audio of my app to let the interruption come through. I never thought to inspect this method before, but turns out the problem existed in there. My stop method would call prepareToPlay immediately after stopping to make resuming faster the next time.
[self.player stop];
[self.player prepareToPlay]; // <- iOS 5 alarm sound stopped here.
The docs state the prepareToPlay method
preloads buffers and acquires the audio hardware needed for playback, which minimizes the lag between calling the play method and the start of sound output.
Sounds reasonable, and this worked for lesser iOS versions. My hypothesis is that  must have made a change to the Clock.app alarm system such that the new alarm sounds use the hardware, whereas before it used the software. This is what I think is causing the iOS 5 alarms to be silent in some apps.
Removing the prepareToPlay lines caused the alarm to sound without using kAudioSessionProperty_OverrideCategoryMixWithOthers, thus solving all my issues laid out in this question.
TL;DR
Remove the prepareToPlay calls from your stop sound code logic. It will take a microsecond longer to start later, but will allow interruptions to sound.

Allow application continue running when iPhone gets locked

I have developed an iPhone app which gets the microphone recorder inputs every second using NSTimer, calculate the amplitude of sound, and take appropriate action if required. I have noticed that when my iPhone gets locked, my application stops running(it doesn't fire the timer callback function). When I unlock iPhone, it start automatically. Could anyone please tell me how can I allow application responding when iPhone gets locked? Is there any other way around such that iPhone shouldn't get locked when my application is running? What should be Apple's recomendation on this?
I found this article but not sure it is correct way to do.
Thanks.
You cannot prevent timer from being stopped when application goes into idle state. Only one possible way is to disable idleTimer of the application.
application.idleTimerDisabled = TRUE;
//or
//Disable screen dimming if no user input occur on device.
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];

Receiving Notifications with App in background mode

I have an app, that will keep track of everything the user do in the iPod app. To do this, I added few observers to NSNotificationCenter, like MPMusicPlayerControllerNowPlayingItemDidChangeNotification. But my problem is, I only get those notifications when my app is in the foreground, if its in the background, the system add the notification to a queue, and then the next time my app becomes active it delivers it to me. I have no interest in this queue, since I want to receive real-time notifications.
Is there any way for me to get those notifications even if my app is in suspended state? I want to run just 3 lines of code everytime I get this NowPlayingItemDidChange notifications for example.
Here is where I add the observer.
MPMusicPlayerController *iPodMediaPlayer = [MPMusicPlayerController iPodMusicPlayer];
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver: self selector: #selector(handle_NowPlayingItemChanged:) name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification
object:iPodMediaPlayer];
[iPodMediaPlayer beginGeneratingPlaybackNotifications];
Also, if I add another kind of object to the observer instead of iPodMediaPlayer, the observer won't call the method.
Thanks a lot,
Abras
iOS applications are suspended when they are not in the foreground. There are three exceptions to this rule. You can have code execute in the background if your application is
a) Playing audio. This means the application itself is actually generating audio. My understanding is that the MPMediaPlayerController iPodMusicPlayer object only controls the playback of the external iPod process, rather than playing audio from the app itself. Perhaps you could have some success if you called applicationMusicPlayer instead of iPodMusicPlayer and set the appropriate background flags in your applications Info.plist. This seems like the most legitimate way to get your application to work, but you wouldn't be able to control iPod playback from the iPod app, only your app and the system audio controls.
b) Get your app to monitor the location. If the app is using the GPS it can continue to execute in the background. Downside to this is that the GPS will drain battery, and users might be creeped out that you're requesting their location.
c) Ask UIApplication for extra time. If you use UIApplication's beginBackgroundTask method, your application will continue to run for a finite amount of time in the background. If your users are going to come into your application once every ten minutes or so, this could work as well.
Hope that helps.
Multitasking in iOS is currently a very restricted one. You may start a background task using beginBackgroundTaskWithExpirationHandler: method (of an UIApplication object), but it is intended to finish a finite-length task before going suspended. All background tasks may expire (and get terminated) before it finishes its job. You can check how much longer your application can run by checking backgroundTimeRemaining property of the application object.
As I explained here iOS receive Media Player Notifications when app is in background, there seems no way to get notifications from iPodMusicPlayer.
About Omar Raul Qazi answer:
a) i tried and I had no success. The music kept going down when pressing home button. I think this background flag only works for normal AudioSessions and not for MPMusicPlayer...
b) I am not sure this would work and I don't think Apple would like it when looking for approval
c) You can run in background only synchronous task. You cannot wait there for a notification. Am I wrong?

Trying to identify problem with core audio vs iPhone background execution

I have an audio app in the store. It works fine with versions of the iPhone OS before iOS 4.0. I am working on a new version, starting by bringing the app into compliance with the new iOS multitasking capabilities. (I have iOS 4.0 on my iPhone, and have upgraded to the latest xCode and SDK.)
The result has been a show-stopper.
o When I install the app on the iPhone and run in the debugger, or start the app after the iPhone was powered down, the app acts just fine - playing audio as I push buttons, or restarting audio from "state" that was saved the previous time the app was run.
o If I try to push the Home button and then restart the app from the background, the audio - a and mix of 1-n audio streams - comes out with a stuttering sound that only I could recognize.
o If - while the audio is cleanly - I call the iPhone, I can either answer or decline the call. In both cases the app comes back cleanly, playing as it should.
Note that I am not trying to play anything while in background mode. I simply want to shut things off and bring them back when asked.
Technology: All of the audio logic uses RemoteIO. (I have plans for someday doing some fairly sophisticated signal processing.)
Please excuse the pseudo code narrative - some of the real code is pretty extensive.
MainViewController:
o viewDidLoad - nothing special
o didBecomeActive
set self as audio session delegate;
set the AudioSessionCategory to MediaPlayback;
set the AudioSessionActive;
create a Player (see below);
restart any sounds that were previously playing;
o willResignActive
save the state of what was playing;
stopAllSounds;
stop the player;
set the audio session inactive;
o didEnterBackground - nothing (method is registered, but no content.)
o willEnterForeground - nothing (method is registered, but no content.)
Overview of Player - my class:
The Player is a singleton. I make sure that the singleton instance is destroyed, and a new one created, in didBecomeActive. Instantiating the singleton actually starts the AudioUnit.
constructor
setupRemoteIO;
start
AudioOutputUnitStart;
stop
AudioOutputUnitStop;
player callback
the usual stuff;
>
Here are some methods from my MainViewController:
(void)willResignActive:(NSNotification *)note {
[ self saveState ];
[ [ NaturePlayer getInstance ] stopAllSounds ];
[ [ NaturePlayer getInstance ] stop ];
NSError *activationError = nil;
[[AVAudioSession sharedInstance] setActive: NO error: &activationError];
[NaturePlayer destroy];
}
- (void)didBecomeActive:(NSNotification *)note {
[ self setupAudioSession ];
NSError *activationError = nil;
[[AVAudioSession sharedInstance] setActive: YES error: &activationError];
[ self restartSounds ];
[ self setViewState ];
}
- (void)didEnterBackground:(NSNotification *)note {
int xxx = 1;
}
- (void)willEnterForeground:(NSNotification *)note {
int xxx = 1;
}
- (void) applicationWillTerminate: (NSNotification*) notification {
int xxx = 1;
}
Here is a method from the NaturePlayer:
/**
* Stop the playback process.
*/
void NaturePlayerDelegate::stop() {
if (isPlaying_) {
AudioOutputUnitStop(outputUnit_);
isPlaying_ = FALSE ;
}
}
I checked: stop() is being called, and in turn calls AudioOutputUnitStop();
Also checked: The doc on AudioOutputUnitStop says it blocks until all activity has completed.
Hard to say without more details on the audio code. But I suggest you might want to examine your Player object teardown code to make sure the audio unit and the audio session are completely stopped (buffer callback thread drained) before releasing stuff.
Are you initializing and un-initializing AudioUnits within your code? I have recently found an issue that AudioUnits being created and destroyed then leaving and returning to your App will cause stuttering.
I was able to fix this in my application by never uninitializing the AudioUnits.
More info on my problem and my AudioUnit code.
I had the same problem in a project of mine. I found that if I called AudioOutputUnitStop() from a button click before suspending the app, then called AudioOutputUnitStart() when the app resumed, I had no problems. But if I called AudioOutputUnitStop() automatically from the viewDidUnload handler or as a response to the UIApplicationWillResignActiveNotification, I had the stuttering, feedback-like sound described above.
I also noticed that if I stopped the audio unit manually, then suspended the app, the interruption listener was called. But if I suspended the app while the audio unit was still running, the interruption listener was not called. The interruption listener is supposed to stop the audio unit, so that's not doing me much good.
After several hours of tracing this, I found a way to finish my task without audio units, and took them out of my app. So I'm afraid I don't have a complete answer. But hopefully these clues will help someone. I may need to do this again in the future, so I'll check back here to see if someone else has figured it out.