我正在将音频流服务绑定到Fragment
.
如何percent
从服务中获取价值MediaPlayer
?onBufferingUpdate
Fragment
我正在考虑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;
}
};
}