如何在AsyncTask中举杯,提示我使用Looper
我有 AsyncTask 在后台完成的任务。在某些时候,我需要发出一个 Toast 来表示某件事已完成。
我尝试过但失败了因为 引起:java.lang.RuntimeException:无法在未调用 Looper.prepare() 的线程内创建处理程序
我该怎么做?
I have tasks completed by AsyncTask in background. At some point I need to issue a Toast that something is completed.
I've tried and I failed becauseCaused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
How can I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
onPostExecute - 在 UI 线程上执行
或者
publishProgress()
;在你的 doinbackground 和http://developer.android.com/reference/android/os /AsyncTask.html
onPostExecute - executes on UI thread
or
publishProgress()
; in your doinbackground andhttp://developer.android.com/reference/android/os/AsyncTask.html
你可以在Toast里面doInBackground
添加这段代码在你想要Toast出现的地方
you can Toast inside doInBackground
add this code where you want to Toast appear
您还可以使用 runOnUiThread 方法从后台线程操作您的 UI。
You can also use runOnUiThread method to manipulate your UI from background threads.
如果你想使用吐司
你应该使用这个方法:onProgressUpdate()
If you want to use Toast
You should use this method : onProgressUpdate()
如果要从后台线程显示 Toast,则必须从 doInBackground 调用 runOnUiThread。我不相信还有其他方法。
编辑:我收回那句话。我认为您可以实现 onProgressUpdate(它在 UI 线程上运行)来显示 Toast 并从 doInBackground 调用publishProgress。
If you want to display the Toast from the background thread you'll have to call runOnUiThread from doInBackground. I don't believe there's another way.
Edit: I take that back. I think you can implement onProgressUpdate, which runs on the UI thread, to show the Toast and make calls to publishProgress from doInBackground.
如果想在doInBackground中显示Toast,可以在AsyncTask的OnPostExecute方法中使用。
If you want to display the Toast in doInBackground, you can use it in the OnPostExecute method of AsyncTask.