AsyncTask的和错误处理在Android [英] AsyncTask and error handling on Android

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

问题描述

我将我的code使用处理程序的AsyncTask 。后者是伟大的它做什么 - 异步更新和处理结果在主UI线程的。什么是我不清楚是如何处理异常,如果出现失控的的AsyncTask#doInBackground

我做的方式是有一个错误处理和发送信息给它。它工作正常,但它是正确的方法还是有更好的选择?

另外我明白,如果我定义的错误处理程序为活动现场,就应该在UI线程中执行。但是,有时(非常联合国predictably)我会得到一个异常说,code从处理程序#的handleMessage 在执行了错误的线程上触发。我应该初始化活动#的onCreate ,而不是错误处理?配售 runOnUiThread 处理程序#的handleMessage 似乎是多余的,但执行非常可靠的。

解决方案
  

它工作正常,但它是正确的   的做法,是有更好的   另类?

我守住了的AsyncTask 的Throwable 异常 C>实例本身,然后用它做什么的 onPostExecute(),所以我的错误处理对屏幕显示一个对话框中的选项。

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?

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.

解决方案

It works fine but is it the "right" approach and is there better alternative?

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆