I'm doing a radio app, with a MediaPlayer
in a Service
.
I start it with startService()
when a StreamPlayerFragment
is created because the audio stream must play as long as the app runs, and I bind it only in StreamPlayerFragment
, because only this Fragment
need to access the MediaPlayer
to play/pause/stop the audio stream.
Now I'm not sure when/how the Service
should be stopped? I need to know when it's stopped or destroyed to be able to release the MediaPlayer
.
Should I leave Android kill the Service
and release the MediaPlayer
in the Service
's onDestroy
? I can't see other options because I need it to run as long as the app runs...
public class StreamPlayerFragment extends Fragment{
@Override
@Override
public void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
// start service
Intent intent = new Intent(getActivity(), StreamService.class);
getActivity().startService(intent);
}
@Override
public void onResume() {
super.onResume();
// bind service
Intent intent = new Intent(getActivity(), StreamService.class);
getActivity().bindService(intent, mConnection, Context.BIND_AUTO_CREATE)
}
@Override
public void onPause() {
// unbind service
if (mBound) {
getActivity().unbindService(mConnection);
mBound = false;
}
super.onPause();
}
}