Home Tutorials Hints & Tips

Getting Started in Android Development

Part 25 - The onPause Method

You may have noticed that if you quit the music activity from the last tutorial and were playing the music at the time, then the music carries on playing. This may be desirable in your app, but may not be if you need to quit the app to take a call or something similar. There is however, and override method we can use in the Android system that means we can force the music to stop or pause. The method is placed with the class outside of the onCreate method. It can be selected by pressing Ctrl+O in Android Studio. We can then place any code we wish in that method. The code will be executed if the Activity is paused or quit.

In our example we simply check to see if ‘mp’ is initialised the music is playing and then pause it. The code for the completed onPause method is shown below:

protected void onPause() {
   if (mp != null && mp.isPlaying()) {

After this tutorial you MusicActivity.java file should look similar to the one below:

Download Download tutorial set 1

Privacy and Cookies Disclaimer Copyright
© 2015 - 2018 North Border Tech Training All rights reserved