【发布时间】:2018-03-16 13:35:42
【问题描述】:
正如标题所说,我在 AsyncTask 中的“doInBackground”中有代码。 该代码从互联网上读取文本;但是,如果出现问题(例如,连接不可用),它应该发出这种情况的信号。可变变量用于(并且正在工作)将状态标记到另一个线程,运行计时器。
现在,问题:在调用“urlConnection.connect()”时,函数结束(在调试器中可见)。应用程序报告字符串“Fase 3”,但变量“lendoInternet”或“contador”(易失性变量)保持不变 - 没有发现异常(!)。另一方面,如果我使用字符串“abracadabra”作为(错误的)URL,则会引发异常。
我的理论:调用“urlConnection.connect();”将 AsyncTask 发送到 Jupiter;我的意思是,它崩溃得如此之大,以至于连异常处理都没有得到尊重(但是:Timer 线程继续更新 UI)。是的,愚蠢的理论,但我需要一些亮光,拜托。
这个东西在模拟器中运行,从 Android Studio 启动。顺便说一句,在 finally 块中,葡萄牙语字符串的意思是“Hey Java,你妈妈过得好吗?”,以显示我对这种可爱的编程语言的所有温柔(将所有内容替换为您喜欢的德语诅咒)。
谢谢大家。
lendoInternet = true;
erroInternet = false;
try {
URL url = new URL("https://www-eng-x.llnl.gov/documents/a_document.txt"); result = "-Fase-2-";
//URL url = new URL("abracadabra"); result = "-Fase-2-";
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); result = "-Fase-3-";
urlConnection.connect(); result = "-Fase-4-";
InputStream is = new BufferedInputStream(urlConnection.getInputStream()); result = "-Fase-5-";
BufferedReader r = new BufferedReader(new InputStreamReader(is)); result = "-Fase-6-";
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line).append('\n');
}
result = total.toString();
} catch (IOException t) {
contador = 1;
lendoInternet = false;
erroInternet = true;
} catch (Throwable t) {
contador = 1;
lendoInternet = false;
erroInternet = true;
}
finally {
result = "Sua maezinha vai bem, Java?";
}
【问题讨论】:
-
调试你的代码到底是哪里抛出异常。如果它在我认为不可能的
try块内,请指出这条线。 -
尝试在
catch上放一些日志,看看它是否通过它。你能把logcat贴出来吗?
标签: android exception networking android-asynctask