Android 服务:onBind(Intent) 和 onUnbind(Intent) 只调用一次 [英] Android Service: onBind(Intent) and onUnbind(Intent) is called just once

查看:149
本文介绍了Android 服务:onBind(Intent) 和 onUnbind(Intent) 只调用一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有活动和服务.当Activity启动时,它会调用startService()使这个Service即使在Activity被销毁时也能存活,并调用bindService()与这个Service进行通信.

I have the Activity and the Service. When Activity is started, it calls startService() to make this Service be alive even when Activity is destroyed, and bindService(), to communicate with this Service.

bindService() 返回真,mService.onBind() 被调用,ServiceConnection.onServiceConnected() 也被调用.所有的作品.

bindService() returns true, mService.onBind() is called, and ServiceConnection.onServiceConnected() is called too. All works.

当我按返回键销毁我的 Activity 时,它调用 unbindService(),并调用我的 mService.onUnbind().(我在这个 onUnbind() 中返回 false.)

When i destroy my Activity by pressing Back key, it calls unbindService(), and my mService.onUnbind() is called. (i return false in this onUnbind().)

然后我再次启动这个 Activity,bindService() 返回 true,然后 mService.onBind()NOT 调用!但是 ServiceConnection.onServiceConnected() 也被调用了,一切又恢复了.

Then i start this Activity again, bindService() returns true, and then mService.onBind() is NOT called! But ServiceConnection.onServiceConnected() is called too, and all works again.

看起来 Dalvik 记得我的 onBind() 上次返回的内容,只是没有再次调用 onBind().当我再次销毁我的活动时,onUnbind() 也被NOT 调用.

It looks like Dalvik remembers what my onBind() returned last time, and just does not call onBind() again. When i destroy my Activity again, onUnbind() is NOT called too.

我可以多次将此 Service 绑定和取消绑定到我的 Activity,但是在我通过取消绑定和调用 stopService() 销毁 Service 之前,不会再调用这些方法.

I can bind and unbind this Service to my Activity any number of times, but these methods will not be called anymore until I destroy Service by unbinding and calling stopService().

在文档中,我找不到对这种行为的任何解释.相反,这个图表明onBind()onUnbind() 应该在客户端每次绑定和解绑 Service 时调用.此图可以在本开发指南的底部找到.

In docs i can't find any explanation of this behavior. Conversely, this figure shows that onBind() and onUnbind() should be called every time clients bind and unbind Service. This figure can be found on the bottom of this Dev Guide.

推荐答案

我认为 this(参考官方开发指南)可以解释你所有的疑问:

I think this (referenced from official dev guide) can explain all your queries:

多个客户端可以同时连接到服务.但是,只有在第一个客户端绑定时,系统才会调用您的服务的 onBind() 方法来检索 IBinder.然后,系统将相同的 IBinder 传递给绑定的任何其他客户端,而无需再次调用 onBind().

Multiple clients can connect to the service at once. However, the system calls your service's onBind() method to retrieve the IBinder only when the first client binds. The system then delivers the same IBinder to any additional clients that bind, without calling onBind() again.

这篇关于Android 服务:onBind(Intent) 和 onUnbind(Intent) 只调用一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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