«

android利用多线程加载图片【不使用第三方库】

时间:2024-3-2 20:03     作者:韩俊     分类: Android


前言

这是一份关于android利用线程池加载图片的demo。有部分参考意义。

代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="这是四种线程池的测试实验"/>

    <TableLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        <TableRow>
            <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="SingleThreadExecutor" android:id="@+id/btn_SingleThreadExecutor"/>
            <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="FixedThreadPool" android:id="@+id/btn_FixedThreadPool"/>

        </TableRow>
        <TableRow>
            <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="CachedThreadPool" android:id="@+id/btn_CachedThreadPool"/>
            <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ScheduledThreadPool" android:id="@+id/btn_ScheduledThreadPool"/>
        </TableRow>
        <TableRow>
            <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="实际环境中的图片加载" android:id="@+id/btn_production"/>
        </TableRow>
    </TableLayout>

    <ScrollView android:layout_width="fill_parent" android:layout_height="wrap_content">

        <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:id="@+id/panel_list">

        </LinearLayout>

    </ScrollView>
</LinearLayout>
package com.example.apppractise.app;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.Image;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.Volley;
import com.example.Sys.utils.ImgUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Administrator on 2015/7/3.
 */
public class ThreadPoolDemo extends Activity {

    private Button btn_singleThreadPool;
    private Button btn_fixedThreadPool;
    private Button btn_canchedThreadPool;
    private Button btn_scheduledThreadPool;

    private Button btn_production;

    private LinearLayout panelList;
    Handler handler=new Handler();

    ExecutorService pool_single;
    ExecutorService pool_fixed;
    ExecutorService pool_cached;
    ExecutorService pool_schedule;
    RequestQueue mQueue;

    class ImageURLInfo{
        public String url="";
        public String title="";
        public ImageURLInfo(){}
        public ImageURLInfo(String _url,String _title){
            url=_url;
            title=_title;
        }
    }

    //--这是图片数据列表。这个先随便在网上搜几幅图片来,然后再加载。
    protected ArrayList<ImageURLInfo> urlInfos=new ArrayList<ImageURLInfo>();

    @Override
    public void onCreate(Bundle savedInstanceState){

        super.onCreate(savedInstanceState);
        setContentView(R.layout.thread_pool_demo);
        mQueue= Volley.newRequestQueue(this);
        initData();
        initUI();
        initEvents();
    }
    private void initUI(){
        panelList=(LinearLayout)findViewById(R.id.panel_list);
        btn_singleThreadPool=(Button)findViewById(R.id.btn_SingleThreadExecutor);
        btn_fixedThreadPool=(Button)findViewById(R.id.btn_FixedThreadPool);
        btn_canchedThreadPool=(Button)findViewById(R.id.btn_CachedThreadPool);
        btn_scheduledThreadPool=(Button)findViewById(R.id.btn_ScheduledThreadPool);
        btn_production=(Button)findViewById(R.id.btn_production);

    }
    private void initEvents(){
        btn_singleThreadPool.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clearList();

                //--将相关图片获取出来。
                for(int i=0;i<urlInfos.size();i++){
                    final ImageURLInfo iinfo=urlInfos.get(i);
                    pool_single.execute(new Runnable() {
                        @Override
                        public void run() {
                            appendImage(iinfo);
                            try{
                            Thread.sleep(2000);}
                            catch (Exception ed){
                                ed.printStackTrace();
                            }
                        }
                    });
                }

            }
        });
        btn_fixedThreadPool.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clearList();

                //--将相关图片获取出来。
                for(int i=0;i<urlInfos.size();i++){
                    final ImageURLInfo iinfo=urlInfos.get(i);
                    pool_fixed.execute(new Runnable() {
                        @Override
                        public void run() {
                            appendImage(iinfo);
                            try{
                                Thread.sleep(2000);}
                            catch (Exception ed){
                                ed.printStackTrace();
                            }
                        }
                    });
                }
            }
        });

        btn_canchedThreadPool.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clearList();

                //--将相关图片获取出来。
                for(int i=0;i<urlInfos.size();i++){
                    final ImageURLInfo iinfo=urlInfos.get(i);
                    pool_cached.execute(new Runnable() {
                        @Override
                        public void run() {
                            appendImage(iinfo);
                            try{
                                Thread.sleep(2000);}
                            catch (Exception ed){
                                ed.printStackTrace();
                            }
                        }
                    });
                }
            }
        });
        btn_scheduledThreadPool.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clearList();

                //--将相关图片获取出来。

                for(int i=0;i<urlInfos.size();i++){
                    final ImageURLInfo iinfo=urlInfos.get(i);
                    pool_schedule.execute(new Runnable() {
                        @Override
                        public void run() {
                            appendImage(iinfo);
                            try{
                               // Thread.sleep(2000);
                               }
                            catch (Exception ed){
                                ed.printStackTrace();
                            }
                        }
                    });
                }
            }
        });
        btn_production.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clearList();
                loadImagesInProduction();
            }
        });
    }
    private void initData(){

        pool_single = Executors. newSingleThreadExecutor();
        pool_fixed=Executors.newFixedThreadPool(2);
        pool_schedule=Executors.newScheduledThreadPool(5);
        pool_cached=Executors.newCachedThreadPool();

        urlInfos.add(new ImageURLInfo("http://att2.citysbs.com/guangzhou/sns01/forum/2011/05/23-17/20110523_5fbe97609ec6dcbcf8390UKPwPXpNu8v.jpg","我们的婚礼"));
        urlInfos.add(new ImageURLInfo("http://imgst-dl.meilishuo.net/pic/_o/85/fb/e4b47e2b627c0b426936848c027d_1944_2592.jpeg","飞机上某个女孩自拍照"));
        urlInfos.add(new ImageURLInfo("http://cdn.duitang.com/uploads/item/201405/16/20140516134733_L5zhQ.jpeg","浓妆艳抹女孩的红唇"));
        urlInfos.add(new ImageURLInfo("http://photo.sohu.com/20041013/Img222475331.jpg","清爽女孩自拍【鱼泡眼还是卧蚕?】"));
        urlInfos.add(new ImageURLInfo("http://img1d.xgo-img.com.cn/pics/401/400109.jpg","一个车模【工作辛苦,汗如雨下啊】"));
        urlInfos.add(new ImageURLInfo("http://pic.cnhubei.com/attachment/201203/1/2781_13305689234Uuh.jpg","有山有水有女人【请忽略女人吧,1m多的图片,可以测试加载速度】"));
        urlInfos.add(new ImageURLInfo("http://ff.topit.me/f/be/ff/1141477403584ffbefo.jpg","韩国洗剪吹【我真分不出韩国男明星,感觉都一样 囧】"));
        urlInfos.add(new ImageURLInfo("http://img1.ph.126.net/dMMszRbV4BKyzzy3Jo9PaQ==/2680486203232537044.jpg","范晓萱广告封面【范晓萱是谁】"));
        urlInfos.add(new ImageURLInfo("http://photo.sohu.com/20041013/Img222475337.jpg","凳子上的女孩【主角感觉是那张黄凳子,太显眼了】"));
        urlInfos.add(new ImageURLInfo("http://cms.gdzjdaily.com.cn/2011bb/upload/2010-12/1293267071.jpg","爱尔美广告封面【我没打广告,用用图片而已】"));

    }
    private void clearList(){
        panelList.removeAllViews();
    }

    private void appendImage(ImageURLInfo imageURLInfo){
        DefaultHttpClient httpclient = new DefaultHttpClient();

        HttpGet httpget = new HttpGet(imageURLInfo.url);

        try {
            HttpResponse resp = httpclient.execute(httpget);
            //判断是否正确执行
            if (HttpStatus.SC_OK == resp.getStatusLine().getStatusCode()) {
                //将返回内容转换为bitmap
                HttpEntity entity = resp.getEntity();
                InputStream in = entity.getContent();
                BitmapFactory.Options boptions=new BitmapFactory.Options();
                boptions.inJustDecodeBounds=true;
                try {
                    byte[] imgdata=readStream(in);

                    //BitmapFactory.decodeStream(in,null,boptions);
                    BitmapFactory.decodeByteArray(imgdata,0,imgdata.length,boptions);
                    int imageHeight=boptions.outHeight;
                    int imageWidth=boptions.outWidth;
                    boptions.inJustDecodeBounds=false;
                    int inSampleSize=ImgUtil.calculateInSampleSize(imageWidth,imageHeight,200,200);
                    boptions.inSampleSize=inSampleSize;
                    //final Bitmap resizeBitmap=BitmapFactory.decodeStream(in,null,boptions);
                    final Bitmap resizeBitmap=BitmapFactory.decodeByteArray(imgdata, 0, imgdata.length, boptions);
                    //final Bitmap resizeBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(),new Matrix(), false);

                    //向handler发送消息,执行显示图片操作

                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            ImageView imageView=new ImageView(ThreadPoolDemo.this);
                            imageView.setImageBitmap(resizeBitmap);
                            panelList.addView(imageView);
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
                in.close();

            }

        } catch (Exception e) {
            e.printStackTrace();
            setTitle(e.getMessage());
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    }
    /*
         * 得到图片字节流 数组大小
         * */
    public static byte[] readStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len=inStream.read(buffer)) != -1){
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        inStream.close();
        return outStream.toByteArray();
    }

    private void loadImagesInProduction(){
        for(int i=0;i<urlInfos.size();i++){
            ImageURLInfo info=urlInfos.get(i);
            ImageRequest imageRequest=new ImageRequest(info.url, new Response.Listener<Bitmap>() {
                @Override
                public void onResponse(Bitmap response) {
                    ImageView imageView=new ImageView(ThreadPoolDemo.this);
                    imageView.setImageBitmap(response);
                    panelList.addView(imageView);
                    Log.e("log", "抓取成功");
                }
            }, 400, 400, Bitmap.Config.ARGB_4444, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    ImageView imageView=new ImageView(ThreadPoolDemo.this);

                    error.printStackTrace();
                    imageView.setImageResource(R.drawable.ui_imgselect_albums_bg);
                    panelList.addView(imageView);
                    Log.e("log","抓取失败");
                }
            });
            mQueue.add(imageRequest);
        }

    }
    @Override
    protected void onStop(){
        super.onStop();
        pool_single.shutdown();
        pool_fixed.shutdown();
        pool_cached.shutdown();
        pool_schedule.shutdown();

    }
}

        <p>版权声明:本文为博主原创文章,未经博主允许不得转载。</p>

标签: android

热门推荐