I was following a tutorial to integrate SoundPool into my app, and this is the code which was given in the tutorial:
package com.example.soundpoolexample;
i
This is a bit tricky to solve correctly. I handle similar scenario in the following way. Structure-wise, it looks like this:
handler is instantiated on the main thread.handleMessage is implemented, which takes care of a custom notification message of all sound samples being loaded.SoundPool is instantiated on the main thread.New thread is started which:
4.1 Sets up SoundPool.OnLoadCompleteListener which sends the custom notification message using the instantiated handler from the main thread.
4.2 Uses instantiated soundPool to issue async loading of sound samples (load method of SoundPool class)
Then, there is a variable which holds a state of sound samples loading. It can have three states: not loading, loading, loaded.
The state of this variable is set to loading in the thread from the 4th step above.
The state of this variable is set to loaded in the handleMessage when the custom notification message arrives.
This state variable is checked before any sound is played. If no sound samples are loaded yet, a semi-fullscreen dialog is shown stating that the sound samples are being loaded and automatically disappears when the loading is done. The dialog can't be dismissed by a user. That is does programmatically from handleMessage method by calling the dismiss method of that dialog, if shown. The dialog has a nice progress bar animation. This is specific to my app and it can be done differently for other apps.
You might ask why it is done so complicated. The thing is that the whole Android GUI API is an event machine and by definition, your own code running on the main thread should not execute any time consuming procedure because that would render the whole GUI non-responsive. In fact, when Android detects such cases, it logs them into logcat. For example, if I had used a semaphore, there would be no progress bar animation because the main GUI thread would be blocked. Using a semaphore this way just exhibits the fact of not understanding Android GUI architecture and it can easily cause an app to hang if something goes wrong with a part which releases the semaphore.
Hope this helps.