Android重复异步任务从不调用onPostExecute

时间:2014-07-22 19:42:04

标签: java android asynchronous android-asynctask locking

我有一个异步任务重复自己,直到一个语句为真。因此我使用此代码(简化):

public class AnalyzingTask extends AsyncTask<String, JSONObject, Void>
{
private final ReentrantLock lock = new ReentrantLock();
private final Condition tryAgain = lock.newCondition();
private volatile boolean finished = false;

@Override
protected Void doInBackground(String... params)
{
    try
    {
        lock.lockInterruptibly();

        do {

    ...somecode...
    publishProgress(result)

            tryAgain.await();
        }
        while (!finished);

        lock.unlock();
    }
    catch(Exception e){
        publishProgress(null);
    }

    return null;
}

@Override
protected void onProgressUpdate(JSONObject... result)
{
    ..someCode...

    if(state.equals("Available"))
                {

                    terminateTask();

                }
                else
                {
                    runAgain();
                }

}

public void runAgain() {
    // Call this to request data from the server again
    tryAgain.signal();
}

public void terminateTask() {
    // The task will only finish when we call this method
    finished = true;
    if(lock.isLocked())
    {
        lock.unlock();
    }
}

@Override
protected void onCancelled() {
    // Make sure we clean up if the task is killed
    terminateTask();
}


@Override
protected void onPostExecute(Void result)
{
   return;
}

}

我调试了这段代码,在&#34; state&#34;之后,terminateTask()被调用正常。有合适的价值。 然而,onPostExecuted永远不会被调用。这不会是一个问题,但只要这个任务正在运行,我就无法启动另一个任务。

为什么这个任务没有正常完成?

在评论中添加signal()时的Stacktrace:

8008-8008/com.michi.undroid E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.michi.undroid, PID: 8008
java.lang.IllegalMonitorStateException
        at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.signal(AbstractQueuedSynchronizer.java:1917)
        at com.michi.undroid.AnalyzingTask.terminateTask(AnalyzingTask.java:166)
        at com.michi.undroid.AnalyzingTask$1.run(AnalyzingTask.java:127)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5017)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
        at dalvik.system.NativeStart.main(Native Method)

0 个答案:

没有答案