Amir Shadaab Mohammed Amir Shadaab Mohammed - 6 months ago 86
Android Question

How to stop media player sound when fragment not visible?

I have a slider fragments in my activity. I am trying to play a sound when the fragment is visible and stop the media player when the user slides to another fragment. Here's my code. I've tried implementing the method onHiddenChanged for the fragment but the sound keeps playing.

public class WorkoutBuddyViewFragment extends Fragment {


MediaPlayer mp;
public WorkoutBuddyViewFragment() {


}
ImageButton play;
TextView display;



// BPPVComment#7: For now, this is a placeholder screen.
// override to provide sensor assisted exercise session
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {


View pageView = null;

pageView = inflater.inflate(R.layout.workout_buddy_dummy, container, false);
play = (ImageButton) pageView.findViewById(R.id.playButton);
display = (TextView) pageView.findViewById(R.id.textForWOB);
mp = MediaPlayer.create(getActivity(), R.raw.welcome);
try
{
mp.start();
}
catch (NullPointerException e)
{
display.setText("Null Pointer Exception");
}


play.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent startExercise = new Intent("android.intent.action.exercise");
startActivity(startExercise);

}
});

return pageView;
}



@Override
public void onHiddenChanged(boolean hidden) {
// TODO Auto-generated method stub
super.onHiddenChanged(hidden);
try
{
mp.stop();
}
catch(NullPointerException e)
{
e.printStackTrace();
}
}

}

Answer

I would try this, setUserVisibleHint method.

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    // Make sure that we are currently visible
    if (this.isVisible()) {
        // If we are becoming invisible, then...
        if (!isVisibleToUser) {
            mp.stop();
        }
        else {
            // do what you like
        }
    }
}