Android : AsyncTask source code questions

on Friday, August 15, 2014


I was reading AsyncTask.java and there are few places that I can't understand.




  1. What does this code actually do? Judging by the comment it should create the handler, but I can't get how it can do this. The method getLooper() in the Handler class just returns the handler, so there is no way I can see it can initialize a new handler.



    /** @hide Used to force static handler to be created. */
    public static void init() {
    sHandler.getLooper();
    }



  2. Why putting postResultIfNotInvoked() in the overriden done() method? How can it be not invoked? If I understand this right, first the call() method of mWorker will be called and then mTaskInvoked is guaranteed to be true.



    mWorker = new WorkerRunnable<Params, Result>() {
    public Result call() throws Exception {
    mTaskInvoked.set(true);
    //...
    return postResult(doInBackground(mParams));
    }
    };

    mFuture = new FutureTask<Result>(mWorker) {
    @Override
    protected void done() {
    try {
    postResultIfNotInvoked(get());
    } catch (InterruptedException e) {
    android.util.Log.w(LOG_TAG, e);
    } catch (ExecutionException e) {
    throw new RuntimeException("An error occured while executing doInBackground()",
    e.getCause());
    } catch (CancellationException e) {
    postResultIfNotInvoked(null);
    }
    }
    };



0 comments:

Post a Comment