0

In my app I use a mediaplayer service. When I call a replace fragment I want to kill that service. Looking at the answers on Stackoverflow and Androids site I have not seen a straight answer. What parts of the fragment lifecycle are called once a replace fragment has been called.

I tried onDestroy and onDetach and these are not being called. Where is the appropriate place to put it?

Thanks

Nicholas Muir
  • 2,897
  • 8
  • 39
  • 89

1 Answers1

1

I would put it to onStop() callback.

Stopped
The fragment is not visible. Either the host activity has been stopped or the fragment has been removed from the activity but added to the back stack. A stopped fragment is still alive (all state and member information is retained by the system). However, it is no longer visible to the user and will be killed if the activity is killed.

onDestroy() and onDetach() callback might not be called.
You can see Fragments lifecycle. It may be helpful.

What is important:
.replace removes the existing fragment and adds a new fragment.

Replace an existing fragment that was added to a container. This is essentially the same as calling remove(Fragment) for all currently added fragments that were added with the same containerViewId and then add(int, Fragment, String) with the same arguments given here.

So that means, onCreate, onCreateView, onActivityCreated, onResume and now you Fragment is visible.

I think these are good related topics to that question:
What is the lifecycle of a fragment when replace() is called?
Replacing a fragment with another fragment inside activity group
Fragment Replacing Existing Fragment
Difference between add() & replace() with Fragment's lifecycle

Community
  • 1
  • 1
mmBs
  • 8,421
  • 6
  • 38
  • 46