37

I am developing a Phonegap app that plays audio using the Phonegap Media plugin. When I press the home button or screen lock button on my android device (KitKat 4.4), the app goes into the background as it should but the audio does not shut off because the pause event is not getting called. Only when I resume the app does the pause event run, and my code to turn off the audio finally runs. The resume event also runs right after this.

Reading the Phonegap docs on the pause event, there is a note about iOS Quirks:

"In the pause handler, any calls to the Cordova API or to native plugins that go through Objective-C do not work, along with any interactive calls, such as alerts or console.log(). They are only processed when the app resumes, on the next run loop."

This is very similar to what I see on my Android device, though I am wondering if it is the same issue. I really need a fix or workaround as this is a showstopper to not be able to turn off audio when a user pauses the app.

Here is my code to add the pause event listener:

document.addEventListener('deviceready', on_device_ready, false);
function on_device_ready()
{
    document.addEventListener('pause', on_pause, false);
    document.addEventListener('resume', on_resume, false);
}

UPDATE: I think I've solved it, though I'm not too happy about the solution. I had set the Phonegap config.xml variable KeepRunning to false. I set to true and now it gets the pause event when it is supposed to. I feel like I should be able to stop my app from running in the background and also run some pause code beforehand as well.

Anyway, here is the config.xml line I am talking about:

<preference name="KeepRunning" value="true"/>
3
  • how about programmatically stopping the app after the pause? Jan 30, 2019 at 0:05
  • Interesting—it’s a big issue in Cordova generally. Wonder if that works in iOS.
    – user241244
    Feb 17, 2019 at 6:40
  • 3
    Oh, you should maybe put that solution down below as an answer. Totally allowed.
    – user241244
    Feb 17, 2019 at 6:40

1 Answer 1

1

When I was developing an mp3 player for my thesis, I was encountering the same issue in the first android version.
The issue was that I was not creating threads and so the stop function was not prioritary to be executed.

I know that my thesis was not in Cordova, but reading Cordova documentation it states

Threading. JavaScript in the WebView does not run on the UI thread. It runs on the 
WebCore thread

from Cordova Documentation

Looking also at Android Documentation, have you thought of implementing a class that handles multiple thread and task queue that fits with Cordova plugin ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.