与前台服务android通信 [英] Communicate with foreground service android
问题描述
第一个问题,但是我已经有一段时间了.
First question here, but I've been around for a while.
我拥有什么:
我正在构建一个可播放音频流和在线播放列表的Android应用.现在一切正常,但是在与服务进行通信时遇到问题.
I'm building an Android app which plays audio streams and online playlists. Everything is working fine now, but I'm having issues in communicating with my service.
音乐是从startForeground开始在服务中播放的,因此它不会被杀死.
The music is playing in a Service, started with startForeground, so it doesn't gets killed.
我需要通过活动与服务进行通信,以获取曲目名称,图像以及更多其他信息.
I need to communicate from my activity with the service, for getting the track name, image, and a couple of things more.
我的问题是什么
我认为我需要使用bindService(而不是当前的startService)来启动我的服务,以便活动可以与其进行对话.
I think I need to start my service with bindService (instead of my current startService) so the activity can talk to it.
但是,当我这样做时,我的服务在关闭活动"后就被杀死了.
However, when I do that, my service gets killed after closing the Activity.
如何同时获得两者?绑定和前台服务?
How can I get both? Binding and foreground service?
谢谢!
推荐答案
否. bindService
将不会启动服务.它将仅使用service connection
绑定到Service
,因此您将具有服务的instance
来访问/控制它.
No. bindService
will not start a service . It will just bind to the Service
with a service connection
, so that you will have the instance
of the service to access/control it.
根据您的要求,我希望您可以使用MediaPlayer
的实例.您也可以从Activity
,然后从bind
启动该服务.如果service
已经在运行,将调用onStartCommand()
,并且您可以检查MediaPlayer
实例是否不为null,然后只需返回START_STICKY
.
As per your requirement I hope you will have the instance of MediaPlayer
in service . You can also start the service from Activity
and then bind
it. If the service
is already running onStartCommand()
will be called, and you can check if MediaPlayer
instance is not null then simply return 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
有类似的应用.让我知道这种方法是否对您没有帮助.
I have similar application with MediaPlayer
service
. let me know if this approach doesn't help you.
这篇关于与前台服务android通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!