Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
656 views
in Technique[技术] by (71.8m points)

binding - Android Service: onBind(Intent) and onUnbind(Intent) is called just once

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() returns true, mService.onBind() is called, and ServiceConnection.onServiceConnected() is called too. All works.

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

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.

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.

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().

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.

question from:https://stackoverflow.com/questions/8788103/android-service-onbindintent-and-onunbindintent-is-called-just-once

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...