I'm learning how to use threads in Android, and to do that I've made a small application that plays a series of notes. The idea is that there is a start button and an end button and that (obviously) if you press the start button it starts playing music, and if you press the end button, it stops. The start button works just fine, but the problem is that the end button doesn't. I'm having trouble figuring out why, so maybe some of you can help me out. This is the code:
public class PressAndPlay extends Activity {
private volatile Thread initBkgdThread;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button startButton = (Button) findViewById(R.id.trigger);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// create thread
initBkgdThread = new Thread(new Runnable() {
public void run() {
play_music();
}
});
initBkgdThread.start();
}
});
Button endButton = (Button) findViewById(R.id.end);
endButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
end_music();
}
});
}
int[] notes = {R.raw.c5, R.raw.b4, R.raw.a4, R.raw.g4};
int NOTE_DURATION = 400;
MediaPlayer m_mediaPlayer;
private void play_music() {
for(int ii=0; ii<12; ii++) {
//check to ensure main activity is not paused
if(!paused) {
if (m_mediaPlayer != null) {m_mediaPlayer.release();}
m_mediaPlayer = MediaPlayer.create(this, notes[ii%4]);
m_mediaPlayer.start();
try {
Thread.sleep(NOTE_DURATION);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private void end_music() {
if(initBkgdThread != null) {
initBkgdThread.interrupt();
initBkgdThread = null;
}
}
boolean paused = false;
@Override
protected void onPause() {
paused = true;
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
paused = false;
}
}