本文介绍了Android 上的 AsyncTask 和错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将我的代码从使用 Handler 转换为 AsyncTask.后者非常擅长它的工作 - 在主 UI 线程中异步更新和处理结果.我不清楚的是,如果 AsyncTask#doInBackground 出现问题,如何处理异常.

I'm converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the main UI thread. What's unclear to me is how to handle exceptions if something goes haywire in AsyncTask#doInBackground.

我这样做的方法是有一个错误处理程序并向它发送消息.它工作正常,但它是正确"的方法还是有更好的选择?

The way I do it is to have an error Handler and send messages to it. It works fine, but is it the "right" approach or is there better alternative?

我也明白,如果我将错误处理程序定义为 Activity 字段,它应该在 UI 线程中执行.但是,有时(非常不可预测)我会收到一个异常,说从 Handler#handleMessage 触发的代码在错误的线程上执行.我应该在 Activity#onCreate 中初始化错误处理程序吗?将 runOnUiThread 放入 Handler#handleMessage 似乎是多余的,但它执行起来非常可靠.

Also I understand that if I define the error Handler as an Activity field, it should execute in the UI thread. However, sometimes (very unpredictably) I will get an Exception saying that code triggered from Handler#handleMessage is executing on the wrong thread. Should I initialize error Handler in Activity#onCreate instead? Placing runOnUiThread into Handler#handleMessage seems redundant but it executes very reliably.

推荐答案

我保留 AsyncTask 实例本身中的 ThrowableException,然后在 onPostExecute(),所以我的错误处理可以选择在屏幕上显示一个对话框.

I hold onto the Throwable or Exception in the AsyncTask instance itself and then do something with it in onPostExecute(), so my error handling has the option of displaying a dialog on-screen.

这篇关于Android 上的 AsyncTask 和错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 02:26
查看更多