我有绑定(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/