SoundPool and Loopers
Discipline of IT
James Cook University
1
Threads/async are good, but Loopers & Handlers are better!
• Looper and Handler offer a more useful abstraction
• And Android uses Loopers and Handlers a lot
– That’s how it implements things like
Activity.runOnUiThread() and View.post()
The main GUI thread already has a Looper running inside it
• If you create a new Handler object within an activity
– Then it will automatically attach itself to the
Looper running on the UI thread!
• This handler object can then be used to safely run
GUI update code via a Runnable
• Note: it’s an example of a COMMAND pattern!
Example - HandlerDemo
Note: it is possible to use this handler inside a background
thread!
So now, what about your own custom Looper Thread…
The custom looper thread has its own looper and handler
• Its handler is attached to its looper
• The handler is used to post new Runnables that run
on the looper – inside Looper.loop()
• So, in a sense, Looper.loop() saves you writing your
own infinite while loop inside Thread.run()
• Note: looper API also has Looper.quit() to stop
Looper.loop() running
SoundPool API – what is it?
• A collection of audio samples loaded into memory
• Offers low-latency playback
• Can playback multiple samples simultaneously
• Sounds can be one-shot or looped
• Playback rate can be adjusted (0.5 – 2.0)
SoundPool API – how does it work?
• Samples are loaded from app resource
– These can be compressed / encoded (e.g. mp3)
• Once loaded, audio samples are decoded /
uncompressed into memory
• SoundPool defines a max numbers of samples
– This limits CPU overhead – preventing audio
playback reducing UI performance
Summary