开发者

Android - Right design to implement AsyncTask or Thread

I have a getViewBitmap() method that creates a Bitmap with a 3rd party library (which is proprietary) and goes like this:

public Bitmap getViewBitmap(int index) {
    Bitmap retBitmap = null;

    int width = 400;
    int height = 200;

    try {
        retBitmap = lib.createBitmap(width, height, index);
    } catch(BMException e) {
        e.printStacktrace();
    }

    return retBitmap;
}

This method is used for creating two page view bitmap in another method:

public Bitmap getTwoPageBitmap(int firstPageIndex, intSecondPageIndex) {
    Bitmap first = getViewBitmap(firstPageIndex);
    Bitmap second = getViewBitmap(secondPageIndex);

    Bitmap retBitmap = Bitmap.create(800, 400, first.getConfig());

    Canvas helperCanvas = new Canvas(splitViewBm);
    helperCanvas.drawBitmap(leftPageBitmap, 0, 0, null);
    helperCanvas.drawBitmap(rightPageBitmap, leftPageBitmap.getWidth(), 0, null);

    return retBitmap;
}

And then finally in initiated method, I have this:

public View createView() {
    MyView v = new MyView();
    if(pagePortratit) {
        v.setPageView(getViewBitmap(0));
    } else {
        // if page is landscape
        v.setPageView(getTwoPageBitmap(0, 1));
    }

    return v;
}

Now - I wanna make the getViewBitmap(int) method Asynchronous. Since the "lib.createBitmap(int, int, int)" is pretty slow and it blocks the UI, I want the creation of the bitmap (getViewBitmap(int)) to be in another thread, with possibilit开发者_JS百科y to interrupt it's work.

What is the correct design for such design so that the method that is actually heavy goes async?


You likely want to subclass AsyncTask (read here) and put your getBitmapView code in the doInBackground() method (@Override). When it's done, have the onPostExecute() method update the View/UI. The logic for determining landscape or portrait will want to be outside the AsyncTask and you'll just want to farm out to the task (using .execute()) which ever view is needed.

That might be one approach.


I think the best thing that you can do is to use AysncTask which allows u to update the UI Directly without special handling for UI Thread update.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜