当 AsyncTask 的 doInBackground 中发生 IOException 时,如何优雅地显示 Toast?
3 回答
您可以覆盖 onPostExecute 或 onProgressUpdate 以在 UI 线程上显示消息。
要在扩展 AsyncTask 时使用 onProgressDisplay 将第二种类型声明为 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;
}
像这样:
Toast.makeText(Context context, int resId, int duration).show();
它需要一个上下文,所以只需将它传递给 AsyncTask。更多信息。
A dirty way is to create a different result in your IOException, for example if there is no internet connection you can check the connectivity in your IOException and set your result if connection exists to result='connection_to_server_issue' . If there is no connection result='no_connection'.
And later on on your postExecution you can check first your result if equals on of these two strings, and if so just execute a toastmessage, or whatever you want do do if one of these errors occurs.