I slapped together a simple test application that has a button, and makes a noise when the user clicks on it. Here are it’s method:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button)findViewById(R.id.easy);
b.setOnClickListener(this);
}
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(this, R.raw.easy);
mp.start();
while(true) {
if (!mp.isPlaying()) {
mp.release();
break;
}
}
}
My question is, why is onCreate acting like it’s in a while loop? I can click on the button whenever, and it makes the sound. I might think it was just a property of listeners, but the Button object wasn’t a member variable. I thought that Android would just go through onCreate onse, and proceed onto the next lifecycle method.
Also, I know that my current way of seeing if the sound is playing is crap…I’ll get to that later. 🙂
Thank you.
You’re thinking of the button instance in terms of the code you’ve written as opposed to an instance that lives in a view that the framework has constructed. Your Button variable (b) is simply a reference to that. Your reference is no longer alive once the onCreate method goes out of scope, but the button still exists in your UI. Your reference was around long enough to attach a listener method to it, so for the lifetime of the button (that you still see in the UI after the onCreate has come and gone, obviously) is more associated with when you can see it and not the scope of the variable you created.
Btw…I know you’re just getting started and your MediaPlayer code was just thrown together, but for future reference, you don’t need a while loop. MediaPlayer gives you an onCompletionListener callback:
OnCompletionListener