在服务中播放音频时,片段中的Android MediaController [英] Android MediaController in Fragment while audio is playing in Service
问题描述
我有一个使用片段显示各种屏幕的活动.屏幕之一用于播放音频文件.当用户选择要播放的音频文件时,我启动了一项服务,并在该服务上播放音频,这样即使用户返回主屏幕,它也将继续在后台播放.
I have an Activity that uses Fragments to display various screens. One of the screens is used to play an Audio File. When the user selects the audio file to play, I start a Service and play the audio on that Service so that it will continue to play in the background even when the users returns to the home screen.
我的问题是这个.如何在片段中使用MediaController来反映服务中发生的情况,这样我就不必重新发明MediaController的所有控件了?
My question is this. How do I use the MediaController in the fragment to reflect what is happening in the Service, so that I don't have to re-invent all of the controls of the MediaController?
我可以在片段中创建MediaController并显示它,但是mMediaController.setMediaPlayer(this);将控制器设置为我的片段,对吗?如何将其设置为我的服务?
I can create the MediaController in my fragment and display it, however the mMediaController.setMediaPlayer(this); sets the controller to my fragment, correct? How do I get it to set to my service?
推荐答案
已将您的Service
工具实现为MediaPlayerControl
,例如...
Have your Service
implement MediaPlayerControl
, example...
public class MyMusicService extends Service
implements MediaPlayerControl {
...
// Override the various `MediaPLayerControl` methods
}
现在,为了使您的Fragment
使用MediaPlayerControl
,它必须绑定到Service
.将以下内容添加到Service
...
Now, in order for your Fragment
to use the MediaPlayerControl
it must bind to the Service
. Add the following to the Service
...
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
public MyMusicService getService() {
return MyMusicService.this;
}
}
@Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
现在,您需要在Fragment
代码中添加绑定到Service
的功能-注意,我只用Activity
完成了此操作,但是理论是相同的Fragment
.在您的Fragment
代码中添加ServiceConnection
...
Now you need to add the ability to bind to your Service
in your Fragment
code -NOTE, I've only done this with an Activity
but the theory is the same for a Fragment
. Add a ServiceConnection
to your Fragment
code...
MyMusicService mService = null;
boolean mBound;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
}
public void onServiceDisconnected(ComponentName className) {
mService = null;
mBound = false;
}
};
您可以在onResume()
的onResume()
中绑定到Service
,在Fragment
的onPause()
中解除绑定,如果将以下内容添加到Fragment
,则可以将MediaController
设置为
You can bind to your Service
in the onResume()
and unbind in onPause()
of your Fragment
and if you add the following to your Fragment
you can set the MediaController
to be the Service
...
public void showMediaControllerHere() {
if (mBound){
controller.setMediaPlayer(mService);
controller.setEnabled(true);
controller.show();
}
}
这篇关于在服务中播放音频时,片段中的Android MediaController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!