Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phonegap / Cordova pause event triggered on resume for android; can not turn off audio as a result

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"/>
like image 968
learnworkplay Avatar asked Oct 06 '14 22:10

learnworkplay


1 Answers

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 ?

like image 165
Fedeco Avatar answered Oct 08 '22 10:10

Fedeco