본문 바로가기
프로그래밍

(안드로이드) 테스트용 이미지 로딩 스레드

by hansoo.labs 한수댁 2015. 2. 26.
비동기식으로 이미지를 로딩할려고 했던 것. 지금은 오픈소스로 대체.

private class LoadThread extends Thread {

    public volatile boolean isActive = false;
    private ImageView imageView;
    private String path;

    public LoadThread(ImageView imageView, String path) {
        this.imageView = imageView;
        this.path = path;
    }

    @Override
    public synchronized void start() {
        isActive = true;
        super.start();
    }

    public void cancel() {
        isActive = false;
    }

    @Override
    public void run() {
        if(isActive) {
            if (path != null) {
                InputStream is;
                BufferedInputStream buf;

                try {
                    
                    is = mContext.getAssets().open(path);
                    buf = new BufferedInputStream(is);
                    final Bitmap bMap = BitmapFactory.decodeStream(buf);

                    if (isActive) {
                        imageView.post(new Runnable() {
                            @Override
                            public void run() {
                                imageView.setImageBitmap(bMap);
                                imageView.setVisibility(View.VISIBLE);
                                imageView.setAlpha(0f);
                                imageView.animate()
                                .setDuration(400)
                                .alpha(1f).start();
                            }
                        });
                    } else {
                        HLog.w(TAG, CLASS, "canceled");
                    }

                    is.close();
                    buf.close();

                } catch (Exception e) {
                    HLog.e(TAG, CLASS, e);
                }
            } else {
                if (isActive) {
                    imageView.post(new Runnable() {
                        @Override
                        public void run() {
                            imageView.setImageResource(0);
                        }
                    });
                }
                else {
                    HLog.w(TAG, CLASS, "canceled");
                }
            }
        }

        isActive = false;

        super.run();
    }
}

댓글2