在AsyncTask中优雅地处理IOException?

时间:2011-07-13 22:17:36

标签: android android-layout android-ui android-networking

如果在AsyncTask的doInBackground中发生IOException时如何正常显示Toast?

3 个答案:

答案 0 :(得分:2)

您可以覆盖onPostExecute或onProgressUpdate以在UI线程上显示消息。

使用onProgressDisplay在扩展AsyncTask时将第二个类型声明为String:

private class YourTask extends AsyncTask<ParamType, String, ReturnType> {

并覆盖onProgressUpdate:

protected void onProgressUpdate(String... progress) {
     String errMsg = progress[0];
     Toast.makeText(getApplicationContext(), errMsg, Toast.LENGTH_SHORT).show();
}

然后你可以在doInBackground中发生异常时调用“progress”函数:

protected ReturnType doInBackground(ParamType... params) {
     try {
         // do stuff
     } catch (IOException e) {
        publishProgress("My Error Msg goes here");
     }
     return result;
 }

答案 1 :(得分:1)

就像这样:

Toast.makeText(Context context, int resId, int duration).show();

它需要一个Context,所以只需将它传递给AsyncTask即可。 More information

答案 2 :(得分:0)

一种肮脏的方法是在IOException中创建不同的结果,例如,如果没有Internet连接,您可以检查IOException中的连接,并在结果存在连接时设置结果=&#39; connection_to_server_issue&#39; 。如果没有连接结果=&#39; no_connection&#39;。

稍后在你的postExecution上,如果等于这两个字符串,你可以先检查你的结果,如果是这样,只要执行一个toastmessage,或者如果出现其中一个错误,你可以做什么。