Android Activity and Service relationship - after

2019-06-27 04:53发布

Let's say Activity A is created and then A starts a Service S and binds itself to S. S notifies A of updates which will cause the state of A to change. What happens to A and S after Android pauses or stops A?

For instance:

  • Does pausing A automatically unbind it from S (thus stopping S if A is the last thing bound to it?)
  • Do updates from S cause A to be resumed?
  • Do updates from S never get passed to A and no error occurs?
  • Can S become aware that A is paused or stopped? (for instance by a call to something like A.isAsleep())

Also, How do I handle the situation so that the "right thing" happens? Do I unbind services in onPause() and re-bind upon onResume()?

1条回答
甜甜的少女心
2楼-- · 2019-06-27 04:57

(A) will be unbound from (S) onPause, but if you didn't call an unbind method, I think you will get a memory leak.

Unless you rebind (A) to (S) onResume(), (A) will note be aware of (S) unless the activity is recreated.

Depends on how you are sending updates. NPE's can happen for sure if you at all reference (A) and it happens to be destroyed while paused.

(S) will only be aware that (A) was paused if you have a method of communicating this to (S) as you have done.

And yes, you have it just right. You should bind and unbind onResume and onPause.

查看更多
登录 后发表回答