0

我正在将音频流服务绑定到Fragment.

如何percent从服务中获取价值MediaPlayeronBufferingUpdateFragment

我正在考虑Broadcast从服务发送一个意图onBufferingUpdate,但这似乎有点矫枉过正。

有人可以帮忙吗?

服务

public class StreamService extends Service implements OnBufferingUpdateListener,
OnInfoListener, OnPreparedListener, OnErrorListener {

    private final IBinder mBinder = new StreamServiceBinder();


    MediaPlayer mMediaPlayer;   


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        initMediaPlayer();
        return START_STICKY;
    }

    @Override
    public void onBufferingUpdate(MediaPlayer player, int percent) {
        // how to send percent to my fragment?

    }

    public class StreamServiceBinder extends Binder {
        StreamService getService() {
            return StreamService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    /* ... */
}

分段

public class StreamPlayerFragment extends Fragment{

    private StreamService mService;
    private boolean mBound = false;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return inflater.inflate(R.layout.stream_player, container, false);
    }

    @Override
    public void onResume() {         
        super.onResume();

        Intent intent = new Intent(getActivity(), StreamService.class);
        getActivity().bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void onPause() {
        super.onPause();

        if (mBound) {
            getActivity().unbindService(mConnection);
            mBound = false;
        }
    }

    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {

            StreamServiceBinder binder = (StreamServiceBinder) service;
            mService = binder.getService();
            mBound = true;          
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };

}
4

1 回答 1

0

我会按照您的建议进行操作,并使用 aLocalBroadcastManager将内部更新发送回 Fragment。

http://developer.android.com/reference/android/support/v4/content/LocalBroadcastManager.html

如果没有在服务中存储对片段的引用,我不确定您还会怎么做。

于 2013-06-14T13:19:55.843 回答