1

I am running an audio file in a fragment using the following code:

public class AudioFragment extends Fragment implements View.OnClickListener {

    private Runnable runnable;
    private Handler handler;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view= inflater.inflate(R.layout.fragment_audio,container,false);
        btnBwd=view.findViewById(R.id.btnBwd);
        btnPlay=view.findViewById(R.id.btnPlay);
        seekBar=view.findViewById(R.id.seekBar);
        handler=new Handler();

        btnBwd.setOnClickListener(this);
        btnPlay.setOnClickListener(this);

        mediaPlayer = MediaPlayer.create(view.getContext(),R.raw.play);
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){
           @Override
           public void onPrepared(MediaPlayer mediaPlayer){
               seekBar.setMax(mediaPlayer.getDuration());
               mediaPlayer.start();
               changeSeekBar();
           }
        });            
        return view;
    }

    private  void changeSeekBar() {
        seekBar.setProgress(mediaPlayer.getCurrentPosition());
        if(mediaPlayer.isPlaying()){
            runnable = new Runnable() {
                @Override
                public void run() {
                    changeSeekBar();
                }
            };
            handler.postDelayed(runnable,1000);
        }
    }
}

This fragment is created in another activity and when this fragment is replaced using fragmentTransaction.replace(), the music still keeps playing for some reason. Is it because there was a Runnable object involved. Can I send some signal to the process?

What is a good way to handle this either from my activity or the fragment itself?

fireball.1
  • 1,413
  • 2
  • 17
  • 42

3 Answers3

3

fragments and activities have a life cycle and in each state of the lifecycle there are methods that notify you about the current life cycle

onAttach() The fragment instance is associated with an activity instance.The fragment and the activity is not fully initialized. Typically you get in this method a reference to the activity which uses the fragment for further initialization work.

onCreate() The system calls this method when creating the fragment. You should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed.

onCreateView() The system calls this callback when it's time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View component from this method that is the root of your fragment's layout. You can return null if the fragment does not provide a UI.

onActivityCreated() The onActivityCreated() is called after the onCreateView() method when the host activity is created. Activity and fragment instance have been created as well as the view hierarchy of the activity. At this point, view can be accessed with the findViewById() method. example. In this method you can instantiate objects which require a Context object

onStart() The onStart() method is called once the fragment gets visible.

onResume() Fragment becomes active.

onPause() The system calls this method as the first indication that the user is leaving the fragment. This is usually where you should commit any changes that should be persisted beyond the current user session.

onStop() Fragment going to be stopped by calling onStop()

onDestroyView() Fragment view will destroy after call this method

onDestroy() onDestroy called to do final clean up of the fragment's state but Not guaranteed to be called by the Android platform.

for more information take a look here: https://www.tutorialspoint.com/android/android_fragments.htm

you could get notify by overriding these methods and react to them for example in your case when you are replacing or removing the fragment onPause and onStop method gets invoked (it is different between these two methods ) and there you should release the MediaPlayer.

Amir Hossein Mirzaei
  • 2,325
  • 1
  • 9
  • 17
1

Run your background task like music playing in a service. from anywhere of your application you can start or destroy the service as well.

check this topic for get more detail: Android background music service

javadroid
  • 1,421
  • 2
  • 19
  • 43
1

One of solutions could be Override Fragment's onPause() and calling mediaPlayer.pause():

@Override
public void onPause() {
  super.onPause();
  mediaPlayer.pause();
}


Also I suggest you checking this thread

ॐ Rakesh Kumar
  • 1,318
  • 1
  • 14
  • 24
Emin Guliev
  • 188
  • 2
  • 11