Search code examples
androidmedia-playeropengl-es-2.0glsurfaceview

How to stop music from starting if app is in background?


OK, I've spent 2 days on this almost and getting nowhere, so posting here in hope that someone can come up with a solution of sorts!

In my app, I kick my music off in my onSurfaceChanged method. Seems a pretty good place to do it, as it will start after all of my resources have loaded.

Everything works perfectly, except..... if the user presses the home key before everything has finished loading, then the app (as one would expect) happily goes into the background, but onSurfaceCreated, onSurfaceChanged, and an initial call to onDrawFrame are still initiated... therefore, my music starts playing even though the app is in a 'paused' state and the user can't see it.

I understand that this (calling of the 3 callbacks listed above) is normal behaviour and the GLSurfaceView won't actually pause until it hits onDrawFrame - in a way this is good because even if the user presses home, things can continue loading in the background, but it's not good for my music problem!

I've tried starting my music from within onResume but the first time the app runs, everything isn't yet setup. So I've had to put a check in place for null - therefore it only works on subsequent launches, (ie, from a paused state).

Any ideas very welcome!!


Solution

  • Use a boolean value to ensure that the app is user-facing before starting to play your music.

    In onSurfaceChanged :

    if(canPlay) //Do what you need to play the music
    

    In onResume:

    canPlay = true;
    

    In onPause :

    canPlay = false;
    

    EDIT - Or use this mechanism in other forms if necessary. If you are playing your sound through GL, you might want to set a boolean value somewhere else. The key is turning the mechanism off in onPause, and on in onResume.