这里是第一个问题,但我已经有一段时间了。
我有什么:
我正在构建一个播放音频流和在线播放列表的 Android 应用。现在一切正常,但我在与我的服务通信时遇到问题。
音乐在服务中播放,从 startForeground 开始,所以它不会被杀死。
我需要通过我的 Activity 与服务进行通信,以获取轨道名称、图像和其他一些内容。
我的问题是什么:
我认为我需要使用 bindService(而不是我当前的 startService)启动我的服务,以便 Activity 可以与之对话。
但是,当我这样做时,我的服务会在关闭 Activity 后被终止。
我怎样才能两者兼得?绑定(bind)和前台服务?
谢谢!
最佳答案
没有。 bindService
不会启动服务。它只会通过 service connection
绑定(bind)到 Service
,因此您将拥有服务的 instance
来访问/控制它。
根据您的要求,我希望您将 MediaPlayer
的实例投入使用。您也可以从 Activity
启动服务,然后 bind
它。如果 service
已经在运行 onStartCommand()
将被调用,并且您可以检查 MediaPlayer
实例是否不为空,然后简单地返回 START_STICKY
。
像这样改变你的Activity
..
public class MainActivity extends ActionBarActivity {
CustomService customService = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// start the service, even if already running no problem.
startService(new Intent(this, CustomService.class));
// bind to the service.
bindService(new Intent(this,
CustomService.class), mConnection, Context.BIND_AUTO_CREATE);
}
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
customService = ((CustomService.LocalBinder) iBinder).getInstance();
// now you have the instance of service.
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
customService = null;
}
};
@Override
protected void onDestroy() {
super.onDestroy();
if (customService != null) {
// Detach the service connection.
unbindService(mConnection);
}
}
}
我有与 MediaPlayer
service
类似的应用程序。如果这种方法对您没有帮助,请告诉我。
关于android - 与前台服务android通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23017767/