我有两个 AsyncTask 类。 第一:
private class NotationChanger extends AsyncTask <Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
synchronized(mutex) {
try {
this.infixToPostNotation();
} catch(ParseErrorException e) {
Log.i("Parse Error Exception", e.getMessage());
changedNotationError = true;
}
finally {
mutex.notify(); //Calculator waits while notation is being changed
} //So we should wake it
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
changedNotation = false;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
changedNotation = true;
}
...
}
第二:
private class Calculator extends AsyncTask <Void, Void, Void> {
@Override
protected Void doInBackground(Void... arg0) {
synchronized(mutex) {
while(!changedNotation) {
try {
mutex.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Log.i("Calculation", "waked");
if(!changedNotationError) {
try {
this.calculatePoints();
} catch (CalculateException e) {
Log.i("Calculate exception", e.getMessage());
}
}
else {
changedNotationError = false;
}
return null;
}
...
}
正如您所看到的,当 NotationChanger 完成其工作时,它会唤醒 Calculator 类。它工作正常,没有异常(exception)。当我在 NotationChanger 类中收到 ParseErrorException 时,不会调用 onPostExecute 方法。
如果我搬家
changedNotation = true;
从onPostExecute函数到finally block 每次都运行良好。这是否意味着 doInBackground 中的异常中断了 onPostExecute 方法的调用,或者我什么都不明白?
最佳答案
如果计算器先运行,并在 doInBackground() 中等待。 我认为你的NotationChanger无法进入doInBackground()。 根据我的经验,所有 AsyncTask 都只使用一个线程来工作。
关于java - Android AsyncTask异常和onPostExecute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25431743/