android - 避免 android 绑定(bind)服务中的 ANR

标签 android multithreading service android-asynctask android-anr-dialog

我有绑定(bind)服务。例如,服务有一个方法calculate(),它会执行一些非常密集的计算,如果 Activity 关闭,这些计算应该继续执行(这就是选择服务而不是异步任务的原因)。该服务返回一些结果值,当再次打开 Activity 时,该结果值应该显示在 Activity 上。 问题如下,如果绑定(bind)服务必须返回某个值,如何优雅地避免 ANR 错误?

最佳答案

如果您使用Service,这并不意味着您不需要线程(或AsyncTask)。你实际上需要。

摘自Service引用:

Note that services, like other application objects, run in the main thread of their hosting process. This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work.

因此,我只需将 AsyncTask 放入 Service 中以避免 ANR。

更新:

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

您可以使用以下方式更新主线程:

onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.

关于android - 避免 android 绑定(bind)服务中的 ANR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19678242/

相关文章:

service - 在容器启动时启动服务

service - 无法将瘦 Web 服务器作为服务运行 - 瘦 : unrecognized service

android - setVisibility(View.GONE) 不会消失 View

c# - 读取 byte[] 最快(可能不安全)的方法是什么?

java - 设置 NetworkImageView 与 Volley 禁用图像的持有者

java - 从线程外部、线程运行内部设置 boolean 值

Java线程: Is using interrupt() within run() acceptable to stop a thread when it is finished completing its task?

javascript - 是否存在 Javascript Liferay 服务库的文档?如何处理错误情况?

android - onConnectionSuspended。如何测试?这段代码什么时候运行?

android - 如何通过用户应用程序将日期设置为设备日历并在android中获取提醒?