Reputation: 558
I am using this setOnClickListener() inside an one of the method in my Android App.Here I have used A mediaPlayer, which is declared locally. Like this I also have two more methods which all uses mediaplayer. Also I have declared a global Mediaplayer & used it in various places of my onCreate().
public void setOnClickListenerWithMedia(ImageView iv,final int drawable,final int sound) {
iv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopAllSoundsAndClearMemory();
switchCases();
iv_gone();
fullscreenImage.setVisibility(View.VISIBLE);
fullscreenImage.setImageResource(drawable);
MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), sound);
mediaPlayer.start();
}
});
}
My problem is if I click on any other method, I have to stop the MediaPlayer. For Globally declared MediaPlayer Object(mp.). I can directly use,
if(mp!=null&&mp.isPlaying()){
mp.stop();
}
and I can stop it. But I also want to stop the sound from all the methods. How is it possible?
P.S: -> If I use mp in all the methods , it is not playing the sound & saying to create static mediaPlayer.
Thank you.
Upvotes: 0
Views: 1968
Reputation: 722
try to design your mediaplayer as a singleton mode, and then your mediaplayer will be created only one instance object through the whole app.
Upvotes: 2
Reputation: 20155
Every time when you are creating new player assign it to Global MediaPlayer
instance.
i.e
declare mediaPlayer like this
MediaPlayer mp;
And then in your onClick
or in other other methods use like this
And check whether MediaPlayer
already exist or not
f(mp!=null&&mp.isPlaying()){
mp.stop();
mp.release();
}
mp=MediaPlayer.create(getApplicationContext(), sound);
mp.start();
Upvotes: 2