Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

serviceconnection - Do I need to call both unbindService and stopService for Android services?

In my Android app, I call both startService and bindService:

Intent intent = new Intent(this, MyService.class);
ServiceConnection conn = new ServiceConnection() { ... }

startService(intent)
bindService(intent, conn, BIND_AUTO_CREATE);

Later, I attempt to both unbindService andstopService`:

unbindService(conn);
stopService(intent);

However, I get an exception on the call to unbindService. If I remove this call, the app seems to run properly through the stopService call.

Am I doing something wrong? I thought a bindService call had to be associated with an unbindService call, and a startService call had to be associated with a stopService call. This doesn't seem to be the case here, though.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

The Android documentation for stopService() states:

Note that if a stopped service still has ServiceConnection objects bound to it with the BIND_AUTO_CREATE set, it will not be destroyed until all of these bindings are removed. See the Service documentation for more details on a service's lifecycle.

So calling stopService() first followed by unbindService() should work (it's working for me).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...