服务,重新绑定还是根本不绑定? [英] Service, Rebind or not bound at all?

查看:42
本文介绍了服务,重新绑定还是根本不绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我有这个问题.我有一个播放 mp3 文件的服务.我还可以通过 AIDL 功能暂停和停止 mp3.这工作完美.我可以按主页按钮然后重新启动活动,我仍然可以控制服务.

Ok, so I have this problem. I have a service that plays a mp3 file. I can also pause and stop the mp3 by AIDL functions. That works perfect. I can press the homebutton an then restart the activity and I have still control over the service.

但是,如果我按返回键然后打开活动,我将无法再控制该服务.

However, if I press the back key and then opens the activity I can't control the service anymore.

我认为重新启动活动时应该可以重新绑定到控件.但是发生的事情是服务的新实例已启动,我无法停止正在播放的 mp3.但是,我可以播放新的 mp3.我做错了什么?

I think it should be possible to rebind to the control when restarting the activiy. But what's happening is that new instance of the service is started and I can't stop the mp3 that is playing. I can play a new mp3 however. What am I doing wrong?

推荐答案

我想我明白你想做什么.启动活动并开始 mp3 播放后,您退出活动.然后下次打开它时,您希望绑定到现有服务,而不是启动该服务的另一个实例.

I think I understand what you want to do. After starting the activity and starting the mp3 playback, you exit from the activity. Then next time you open it you want to bind to the existing service and not start another instance of the service.

要实现这一点,您必须使用已启动的活动,然后绑定到它.也就是说,在按下按钮时使用 startActivity(Intent),然后在下一行执行 bindService(Intent, connection, Context.FLAG_AUTO_CREATE);.这绑定了服务,然后您可以在 onDestroy(推荐)或 onPause 中取消绑定.此外,由于这是一个已启动的服务,因此在解除绑定时不会被破坏.您必须明确调用 stopService(Intent)stopSelf() 来停止此服务.

To achieve this, you have to use a started activity, and then bind to it. That is, use startActivity(Intent) on press of button, then in the next line, do bindService(Intent, connection, Context.FLAG_AUTO_CREATE);. This binds the service, then you can unbind in onDestroy (recommended) or onPause. Also, as this is a started service, it does not get destroyed when unbind. You have to explicitly call stopService(Intent) or stopSelf() to stop this service.

在您的 Activity 的 onResume 中,您应该检查服务是否正在运行,然后使用以下代码再次绑定到它:bindService(Intent, connection, 0);

In the onResume of your activity, you should check if service is running, and then bind to it again using the code: bindService(Intent, connection, 0);

connection 对象是注册的 ServiceConnection,每次绑定或取消绑定到服务时都会触发该对象.

The connection object is a registered ServiceConnection that is fired everytime you bind or unbind to the service.

private ServiceConnection connection = new ServiceConnection() {

public void onServiceConnected(ComponentName className,
        IBinder service) {
}

public void onServiceDisconnected(ComponentName className) {
}

};

此外,您还可以使用 Messenger 服务从活动中发送和接收消息,例如播放 mp3 歌曲的时间.

Also, you can send and receive messages from the activity, in your case the time of mp3 song play, using Messenger Service.

请参阅此链接以了解有关使用 Messenger 的更多信息.

Refer to this link to learn more about using Messenger.

希望这会有所帮助.

这篇关于服务,重新绑定还是根本不绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆