Android HandlerThread 멀티 이미지 다운로드

7896 단어
최근 Handler Thread를 복습하던 중 예전의 한 항목에서 아리를 통해 권한을 부여받은 다음에 아리 서버의 여러 장의 사진을 다운로드하여 로컬에 캐시하고 표시하는 것이 생각났다.
구체적인 원리 따위는 더 이상 말하지 않겠으니 참고문을 참고하시오.
현재 모든 코드를 붙여서 기록합니다
HanlderThreadActivity.java
package com.hzy.exampledemo.ui.Thread;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;

import com.hzy.exampledemo.R;
import com.hzy.exampledemo.utils.DownloadHandlerThread;

import java.util.ArrayList;
import java.util.List;

/**
 * Description HanlderThreadActivity
 *
 * @author hzy
 * Create on 2019/6/15 11:58
 */
public class HanlderThreadActivity extends AppCompatActivity {

    private DownloadHandlerThread mDownloadHandlerThread;
    private ImageModel imageModel = null;

    private List listUrls=new ArrayList<>();

    private ImageView iv1, iv2, iv3, iv4;

    private Handler mUiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.d("mUiHandler", "  :" + msg.what);
            ImageModel model = (ImageModel) msg.obj;
            switch (msg.what) {
                case 0:
                    iv1.setImageBitmap(model.getBitmap());
                    break;
                case 1:
                    iv2.setImageBitmap(model.getBitmap());
                    break;
                case 2:
                    iv3.setImageBitmap(model.getBitmap());
                    break;
                case 3:
                    iv4.setImageBitmap(model.getBitmap());
                    break;
            }

        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler_thread);
        initData();
        initView();
        initHandlerThread();
    }

    /**
     *          
     */
    private void initData() {
        listUrls.add("http://img5.imgtn.bdimg.com/it/u=891209561,3636218284&fm=26&gp=0.jpg");
        listUrls.add("http://img4.imgtn.bdimg.com/it/u=3405377191,2814141235&fm=26&gp=0.jpg");
        listUrls.add("http://img4.imgtn.bdimg.com/it/u=3354006971,2210896407&fm=26&gp=0.jpg");
        listUrls.add("http://img0.imgtn.bdimg.com/it/u=3693563304,289022646&fm=26&gp=0.jpg");
    }

    /**
     *    View
     */
    private void initView() {
        iv1 = findViewById(R.id.iv1);
        iv2 = findViewById(R.id.iv2);
        iv3 = findViewById(R.id.iv3);
        iv4 = findViewById(R.id.iv4);
    }

    /**
     *    HandlerThread
     */
    private void initHandlerThread() {
        //    HandlerThread
        mDownloadHandlerThread = new DownloadHandlerThread("mHandlerThread");
        mDownloadHandlerThread.setUiHandler(mUiHandler, listUrls);
        //       
        mDownloadHandlerThread.start();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mDownloadHandlerThread.quit();
        for (int i = 0; i < listUrls.size(); i++) {
            mUiHandler.removeMessages(i, imageModel);
        }

    }
}

ImageModel.java
package com.hzy.exampledemo.ui.Thread;

import android.graphics.Bitmap;

public class ImageModel {

    private Bitmap bitmap;
    private String url;

    public Bitmap getBitmap() {
        return bitmap;
    }

    public void setBitmap(Bitmap bitmap) {
        this.bitmap = bitmap;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}


activity_handler_thread.xml




    

    

    

    




DownloadHandlerThread.java
package com.hzy.exampledemo.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;

import com.hzy.exampledemo.ui.Thread.ImageModel;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Description HandlerThread    
 *
 * @author hzy
 * Create on 2019/6/15 11:55
 */
public class DownloadHandlerThread extends HandlerThread {

    private Handler mDownloadHandler;//     Handler
    private Handler mUiHandler; //  UI   Handler
    private List listUrls = new ArrayList();

    public DownloadHandlerThread(String name) {
        super(name);
    }

    public DownloadHandlerThread(String name, int priority) {
        super(name, priority);
    }

    public void setUiHandler(Handler mUiHandler, List listUrls) {
        this.mUiHandler = mUiHandler;
        this.listUrls = listUrls;
    }


    @Override
    protected void onLooperPrepared() {
        super.onLooperPrepared();
        //   
        mDownloadHandler = new Handler(getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                //           
                Bitmap bitmap = downloadUrlBitmap(listUrls.get(msg.what));
                ImageModel imageModel = new ImageModel();
                imageModel.setBitmap(bitmap);
                imageModel.setUrl(listUrls.get(msg.what));
                Message msg1 = new Message();
                msg1.what = msg.what;
                msg1.obj = imageModel;
                //        UI
                mUiHandler.sendMessage(msg1);
            }
        };
        if (mUiHandler == null) {
            throw new NullPointerException("uiHandler is not null");
        }
        for (int i = 0; i < listUrls.size(); i++) {
            //  1      
            mDownloadHandler.sendEmptyMessage(i);
        }
    }

    private Bitmap downloadUrlBitmap(String urlString) {
        HttpURLConnection urlConnection = null;
        BufferedInputStream in = null;
        Bitmap bitmap = null;
        try {
            final URL url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            in = new BufferedInputStream(urlConnection.getInputStream(), 8 * 1024);
            bitmap = BitmapFactory.decodeStream(in);
        } catch (final IOException e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            try {
                if (in != null) {
                    in.close();
                }
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }

}

참고 자료:https://blog.csdn.net/javazejian/article/details/52426353 https://blog.csdn.net/lmj623565791/article/details/47079737 https://www.jianshu.com/p/2834a2cf894a https://www.jianshu.com/p/25e9aad4e608

좋은 웹페이지 즐겨찾기