从 runnable 调用 asynctask
是否可以从 Runnable 执行 AsyncTask?根据我的经验,这是可以做到的,但不安全。当我的应用程序第一次运行时,我的 AsyncTask 从 Runnable 运行良好。但是,当应用程序移至后台,然后向前返回时,我得到“无法在未调用 Looper.prepare() 的线程内创建处理程序”。
这就是我想做的: 我正在使用 MapView 并在 onCreate 中调用 runOnFirstFix(Runnable) 。我的 Runnable 调用 AsyncTask 来执行 Web 服务调用,该调用根据位置返回一些数据。 我将应用程序移动到后台(通过点击主页按钮),一段时间后,我再次将应用程序向前推进,并且在我对 AsyncTask 调用execute() 时遇到异常。
首先,为什么runOnFirstFix又被执行了?其次,为什么第二次会引发异常? 我猜生命周期的某些部分我不理解。
谢谢。
Is it possible to execute an AsyncTask from Runnable? in my experience it can be done, but not safely. When my app first runs my AsyncTask runs fine from the Runnable. But when the app is moved to the background, then brought back forward I get "Can't create handler inside thread that has not called Looper.prepare()".
Here's what I'm trying to do:
I'm using MapView and invoking runOnFirstFix(Runnable) within onCreate. My Runnable calls an AsyncTask to perform a web service call which returns some data based on the location.
I move the app to the background (by tapping the home button), after some time I bring my app forward again and I'm getting the exception at the point where I'm invoking execute() on my AsyncTask.
First of all, why is runOnFirstFix being executed again? Secondly, why is it causing the exception the second time around?
I'm guessing that there is some part of the lifecycle that I don't understand.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最初对我来说,AsyncTask 需要从 UI 线程调用并不明显。因此,当 runOnFirstFix 第二次运行时,它是来自不在 UI 线程上的 Runnable。为了解决这个问题,我简单地在第一个 Runnable 中创建了另一个 Runnable 来运行 AsynchTask。
我的 runOnFirstFix 似乎被调用两次的原因很简单,因为我正在创建它的一个新实例。
It wasn't initially obvious to me that the AsyncTask needed to be called from the UI thread. So when runOnFirstFix ran the second time it was from withing a Runnable which wasn't on the UI thread. To solve the problem I simple created another Runnable inside the first to run the AsynchTask.
And the reason my runOnFirstFix seemed to be called twice was simply because I was creating a new instance of it.