前言

这是一份关于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>();@Overridepublic 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() {@Overridepublic void onClick(View view) {clearList();//--将相关图片获取出来。for(int i=0;i<urlInfos.size();i++){final ImageURLInfo iinfo=urlInfos.get(i);pool_single.execute(new Runnable() {@Overridepublic void run() {appendImage(iinfo);try{Thread.sleep(2000);}catch (Exception ed){ed.printStackTrace();}}});}}});btn_fixedThreadPool.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {clearList();//--将相关图片获取出来。for(int i=0;i<urlInfos.size();i++){final ImageURLInfo iinfo=urlInfos.get(i);pool_fixed.execute(new Runnable() {@Overridepublic void run() {appendImage(iinfo);try{Thread.sleep(2000);}catch (Exception ed){ed.printStackTrace();}}});}}});btn_canchedThreadPool.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {clearList();//--将相关图片获取出来。for(int i=0;i<urlInfos.size();i++){final ImageURLInfo iinfo=urlInfos.get(i);pool_cached.execute(new Runnable() {@Overridepublic void run() {appendImage(iinfo);try{Thread.sleep(2000);}catch (Exception ed){ed.printStackTrace();}}});}}});btn_scheduledThreadPool.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {clearList();//--将相关图片获取出来。for(int i=0;i<urlInfos.size();i++){final ImageURLInfo iinfo=urlInfos.get(i);pool_schedule.execute(new Runnable() {@Overridepublic void run() {appendImage(iinfo);try{// Thread.sleep(2000);}catch (Exception ed){ed.printStackTrace();}}});}}});btn_production.setOnClickListener(new View.OnClickListener() {@Overridepublic 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()) {//将返回内容转换为bitmapHttpEntity 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() {@Overridepublic 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>() {@Overridepublic 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() {@Overridepublic 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);}}@Overrideprotected void onStop(){super.onStop();pool_single.shutdown();pool_fixed.shutdown();pool_cached.shutdown();pool_schedule.shutdown();}
}

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

  1. 又优化了一下 Android ListView 异步加载图片

    写这篇文章并不是教大家怎么样用listview异步加载图片,因为这样的文章在网上已经有很多了,比如这位仁兄写的就很好: http://www.iteye.com/topic/685986 我也是因为看 ...

  2. 【项目技术点总结之一】vue集成d3.js利用svg加载图片实现缩放拖拽功能

    [项目技术点总结之一]vue集成d3.js利用svg加载图片实现缩放拖拽功能 前言 概述 技术介绍 实现过程 插件安装 引用组件 初始化组件 实现效果 简单理解 使用d3创建一个svg 在svg中提添 ...

  3. Android ListView异步加载图片乱序问题,原因分析及解决方案

    转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/45586553 在Android所有系统自带的控件当中,ListView这个控件算是 ...

  4. Android开发解决加载图片OOM问题(非常全面 兼顾4 0以下系统)(by 星空武哥)

    转载请标明:http://blog.csdn.net/lsyz0021/article/details/51295402 我们项目中经常会加载图片,有时候如果加载图片过多的话,小则导致程序很卡,重则O ...

  5. android viewpager动态加载图片,Android使用ViewPager加载图片和轮播视频

    作为Android基础组件之一,大家对viewpager已经很熟悉了,网上也有很多使用viewpager来加载图片的案例.但是像微信那样点击图片,可以轮播显示图片和视频的例子却没找到.正巧项目中有需求 ...

  6. Android之glide加载图片圆角效果

    1 问题 Android加载图片需要圆角化,有什么简单粗暴的方法吗?当然有,用我们的神器glide 2 解决办法 1)简单办法 ImageView imageView = (ImageView)hel ...

  7. Android 自定义ImageView加载图片

    自定义imageview功能: 可以实现设置图片显示的时候,依据本身的比例进行图片的缩放 加载图片效果: 使用ImageLoader来加载 图片: 首先将ImageLoader的jar包关联到项目中 ...

  8. android自定义图片加载,Android自定义ProgressDialog加载图片

    为了提高用户体验,我们肯定希望该Dialog能更加炫酷,让用户看着更舒服.那如何做呢,当然是我们自己定义一个ProgressDialog了. 一.使用系统加载框 mDialog = new Progr ...

  9. android 实现异步加载图片,Android中ImageView异步加载图片类

    本源码是从网络找到经修改以方便直接调用感觉用着还可以 首先在项目中添加一个专门加载图片的类AsyncImageLoaderpackage com.demo.core; import java.io.I ...

最新文章

  1. 火遍全国的网络热梗“yyds”,创造者被判刑3年
  2. python中的format什么意思中文-python的format什么意思
  3. 这 9 个 Java 开源项目 yyds,你知道几个?
  4. numpy.random.normal
  5. In English or Chinese?
  6. php is_null(,PHP empty() isset() is_null() 区别与性能比较
  7. 过年前谈个恋爱很过分吗?
  8. pipenv相关指令
  9. 董明珠宣布开启抖音直播卖货首秀,对刚“半价”直播罗永浩?
  10. 基于HTML5的iPad电子杂志横竖屏自适应方案
  11. js radio 获值
  12. vue学习笔记-1-初步认识
  13. sql注入攻击与防御第二章
  14. Apollo OpenDRIVE和ASAM OpenDRIVE的区别
  15. 2020-10-04
  16. 用c语言编程求字符的反码,编程达人 《汇编、C语言基础教程》第一章 进制1.5原码、反码与补码(连载)...
  17. 计算机语言属于人类意识的客观内容,《2008年考研政治800题精解》世界的物质性和人的实践活动(5)...
  18. PHPJavaJavascript通用RSA加密
  19. pyecharts-map世界地图国家中英文对照表
  20. 翻译视频字幕的软件叫什么?安利这几个软件给你

热门文章

  1. python爬虫-京东登录
  2. 乐高JAVA编程_编程和乐高机器人,是一样的吗?学习这些有用吗?
  3. python中随机生成数字方法
  4. ​基于光通信的6G水下信道建模综述
  5. 打台球百发百中?油管博主球杆上“做手脚”
  6. OSPF你懂多少之经典问题50个
  7. BZOJ 1127 [POI2008]KUP 最大子矩阵
  8. 计算机房颁奖词,网络达人奖颁奖词.doc
  9. 明港镇计算机培训班,平桥区建筑工匠培训班在明港新集村开班
  10. 2年乘坐南航2次,却攒了48000里程,我是怎样做到的?(2)