0

我正在使用 Android AsyncTask从网络上获取一些数据。它是一个从 random.org 获取字节并显示字节的简单程序(“破解我”)。该程序还固定 random.org 的公钥来检测拦截代理。

我已经实现onPreExecute,doInBackgroundonPostExecute. 当“一切顺利”时,需要这些方法。当出现问题时doInBackground,我无法显示,AlertDialog因为它不是 UI 线程。该接口还缺少onError在 UI 线程上执行的或类似的方法。

使用此类时如何传达错误?

4

4 回答 4

2

My suggestion is create field in your AsyncTask class. If something gonna wrong put there some exception throwed:

class SomeAsyncTask<..> extends AsyncTask<..> {
    Exception exception = null;
    public doInBackground(...) {
        try {
            . . . 
        } catch (Exception ex) {
            exception = ex;
        }
    }

    public onPostExecute(...) {
        if (exception != null) {
            // process exception on UI thread
        }
    }

} 
于 2012-08-27T20:41:04.107 回答
2

I catch the error in the doInBackground, save the Exception in a field variable and check in onPostExecute if an error occurred:

private Exception exception = null;

protected Void doInBackground(Void... params){
    try{
        doStuff();
    } catch (Exception ex){
        exception = ex;
    }

    return null;
}

protected void onPostExecute(Void result){
    if(exception != null){
        showException(exception);
    }
}

You could easily create your own interface using this code, and then implement the doStuff and showException methods when using it.

于 2012-08-27T20:41:39.223 回答
1

You should return any information needed to onPostExecute() and show your dialog there. Or you can store it locally as a member of an AsyncTask subclass.

于 2012-08-27T20:41:20.633 回答
0

不,只需在 AsyncTask 中发出广播并在您喜欢的任何地方处理广播。AsyncTask 只需要一个 Context 来发出它,您可以将它传递给它。可能希望作为粘性广播发布,以便您可以恢复它。

于 2012-08-27T21:55:45.833 回答