1

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();

    }
}
4

1 回答 1

0

如果你开始它,startService()你将不得不停止它stopService()。解绑是不够的。

http://developer.android.com/reference/android/app/Service.html

如果有人调用 Context.startService() ,那么系统将检索服务(创建它并在需要时调用其 onCreate() 方法),然后使用客户端提供的参数调用其 onStartCommand(Intent, int, int) 方法。此时服务将继续运行,直到调用 Context.stopService() 或 stopSelf()。

如果它需要与您的活动一起运行,为什么不将其作为绑定服务启动呢?

http://developer.android.com/guide/components/bound-services.html

于 2013-06-30T06:06:51.657 回答