Android Activity 和 Service 关系 - 暂停后、停止后

发布于 2024-11-19 16:14:31 字数 422 浏览 5 评论 0原文

假设创建了 Activity A,然后 A 启动了一个 Service S 并将其自身绑定到 S。S 通知 A 更新,这将导致 A 的状态发生变化。 后,A 和 S 会发生什么?

例如:

  • 暂停 A 是否会自动取消与 S 的绑定(如果 A 是最后绑定到它的东西,则停止 S?)
  • Android 暂停或停止A 导致A恢复?
  • S 的更新是否永远不会传递到 A 并且不会发生错误?
  • S 能否意识到 A 已暂停或停止? (例如通过调用诸如 A.isAsleep() 之类的东西)

此外,我如何处理这种情况以便发生“正确的事情”?我是否取消绑定服务在 onPause() 中并在 onResume() 上重新绑定?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时光匆匆的小流年 2024-11-26 16:14:31

(A) 将从 (S) onPause 解除绑定,但如果你没有调用解除绑定方法,我认为你会遇到内存泄漏。

除非您在 onResume() 上将 (A) 重新绑定到 (S),否则 (A) 将注意到 (S),除非重新创建活动。

取决于您发送更新的方式。如果您完全引用 (A) 并且它恰好在暂停时被破坏,那么 NPE 肯定会发生。

只有当您有办法像您所做的那样与 (S) 沟通时,(S) 才会知道 (A) 已暂停。

是的,你做对了。您应该绑定和取消绑定 onResume 和 onPause。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文