Android 利用 AsyncTask 异步读取网络图片
2017-09-06 11:16
441 查看
1.新建Android工程AsyncLoadPicture
新建布局文件activity_main.xml主界面为一个ListView
2.功能主界面MainActivity.java,主代码如下
下面来写一下 ImageLoader的原理
package com.bwie.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import java.lang.ref.SoftReference;
import java.util.HashMap;
/**
* Created by Administrator on 2017/9/5.
*/
public class LoadImageUtil {
private Context context;
private HashMap<String,SoftReference<Bitmap>> bitMaps;
public LoadImageUtil(Context context) {
this.context = context;
this.bitMaps = new HashMap<String,SoftReference<Bitmap>>();//实例化缓存容器
}
//回调的接口
public interface CallBack{
public void callBack(String imgUrl,Bitmap bitmap);
}
//加载图片,进行缓存
public Bitmap loadBitmapByImgUrl(final String imgUrl, final CallBack callBack){
//先判断缓存中有没有图片,得到图片
SoftReference<Bitmap> soft = bitMaps.get(imgUrl);
if(soft != null){
Bitmap bitmap = soft.get();//从软引用中获得bitmap
if(bitmap != null){//缓存中有次图片,直接用
return bitmap;
}else{
bitMaps.remove(imgUrl);//key(图片的url)对应的bitmap消耗了,key也没有意义
}
}
//代码走到此处,说明缓存中没有图片,需要到第三级缓存:网络缓存去取
//通过handler实现子线程和ui主线程的通信
final Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bitmap bitmap = (Bitmap) msg.obj;
callBack.callBack(imgUrl,bitmap);
}
};
//启动线程访问图片
new Thread(){
@Override
public void run() {
super.run();
//加载图片
Bitmap bitmap = new NetWorkUtils().getBitmapByHttpUrlConnectionGet(imgUrl);
//压缩图片
//把bitmap缓存到缓存中,通过软引用
bitMaps.put(imgUrl,new SoftReference<Bitmap>(bitmap));
handler.sendMessage(handler.obtainMessage(1,bitmap));//发给handler
}
}.start();
// //内存中没有图片,通过次线程去加载,然后放在缓存中
// bitMaps.put(imgUrl,bitmap);
return null;
}
}
3、网络请求的工具类
package com.bwie.utils;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* 网络请求的工具类
* Created by Administrator on 2017/9/1.
*/
public class NetWorkUtils {
//获得json串的方法,通过HttpClient get
public String getJsonByHttpClientGet(String url){
return "";
}
//获得json串的方法,通过HttpClient get
public String getJsonByHttpUrlConnectionGet(String jsonUrl){
URL url = null;
HttpURLConnection httpURLConnection = null;
String strJson = "";
InputStream inputStream = null;
try {
url = new URL(jsonUrl);
httpURLConnection = (HttpURLConnection) url.openConnection();
int responseCode = httpURLConnection.getResponseCode();
if(responseCode == 200){
inputStream = httpURLConnection.getInputStream();
byte[] b = new byte[1024];
int length = 0;
while((length = inputStream.read(b)) != -1){//循环读取json串,拼装
strJson += new String(b,0,length);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return strJson;//返回最终的json数据
}
//获得json串的方法,通过HttpClient get
public Bitmap getBitmapByHttpUrlConnectionGet(String imageUrl){
URL url = null;
HttpURLConnection httpURLConnection = null;
Bitmap bitmap = null;
InputStream inputStream = null;
try {
url = new URL(imageUrl);
httpURLConnection = (HttpURLConnection) url.openConnection();
int responseCode = httpURLConnection.getResponseCode();
if(responseCode == 200){
inputStream = httpURLConnection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);//把图片信息(输入流)
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bitmap;//返回最终的json数据
}
}
4、一定要记得加网络权限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.bwie.httpclienthomework1">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
今天写的网络请求图片,是ImageLoader的原理,所以用的不多,但是原理一定要懂,不然在工作中遇到实际的问题,会让你懵逼,对,懵逼!!
新建布局文件activity_main.xml主界面为一个ListView
2.功能主界面MainActivity.java,主代码如下
package com.bwie.httpclienthomework1; import android.graphics.Bitmap; import android.os.AsyncTask; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.bwie.com.bwie.beans.Book; import com.bwie.com.bwie.beans.Data; import com.bwie.com.bwie.beans.SuperClass; import com.bwie.utils.LoadImageUtil; import com.bwie.utils.NetWorkUtils; import com.bwie.utils.URLDB; import com.google.gson.Gson; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private Button btn1,btn2; private ListView lv; private NetWorkUtils netWorkUtils; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } private void init() { netWorkUtils = new NetWorkUtils(); btn1 = (Button) findViewById(R.id.btn1); btn2 = (Button) findViewById(R.id.btn2); lv = (ListView) findViewById(R.id.lv); btn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AsyncTask<String,Integer,String>(){ @Override protected String doInBackground(String... params) { String url = params[0];//得到url String json = netWorkUtils.getJsonByHttpUrlConnectionGet(url); return json; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); ShopClass shopClass = new Gson().fromJson(s,ShopClass.class); final ArrayList<ArrayList<String>> rs = shopClass.getResult(); lv.setAdapter(new BaseAdapter() { @Override public int getCount() { return rs.size(); } @Override public Object getItem(int position) { return rs.get(position); } @Override public long getItemId(int position) { return position; } 4000 @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHold hold = null; if(convertView == null){ hold = new ViewHold(); convertView = View.inflate(MainActivity.this,R.layout.listview_item,null); hold.img = (ImageView) convertView.findViewById(R.id.imageView); hold.tv1 = (TextView) convertView.findViewById(R.id.textView1); hold.tv2 = (TextView) convertView.findViewById(R.id.textView2); convertView.setTag(hold); }else{ hold = (ViewHold) convertView.getTag(); } //获得当前要显示的数据对象 ArrayList<String> strs = rs.get(position); hold.tv1.setText(strs.get(0)); hold.tv2.setText(strs.get(1)); //加载图片 return convertView; } class ViewHold{ TextView tv1,tv2; ImageView img; } }); } }.execute(URLDB.JSON_URL2); } }); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AsyncTask<String,Integer,String>(){ @Override protected String doInBackground(String... params) { String url = params[0];//得到url String json = netWorkUtils.getJsonByHttpUrlConnectionGet(url); return json; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); //解析json串 SuperClass superClass = new Gson().fromJson(s,SuperClass.class); Data data = superClass.getData(); final ArrayList<Book> topics = data.getTopics(); lv.setAdapter(new BaseAdapter() { //实例化加载和缓存图片的类 LoadImageUtil loadImageUtil = new LoadImageUtil(MainActivity.this); @Override public int getCount() { return topics.size(); } @Override public Object getItem(int position) { return topics.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, final ViewGroup parent) { ViewHold hold = null; if(convertView == null){ hold = new ViewHold(); convertView = View.inflate(MainActivity.this,R.layout.listview_item,null); hold.img = (ImageView) convertView.findViewById(R.id.imageView); hold.tv1 = (TextView) convertView.findViewById(R.id.textView1); hold.tv2 = (TextView) convertView.findViewById(R.id.textView2); convertView.setTag(hold); }else{ hold = (ViewHold) convertView.getTag(); } //获得当前要显示的数据对象 Book book = topics.get(position); hold.tv1.setText(book.getId()+""); if(book.getDescription().length() > 10){ hold.tv2.setText(book.getDescription().substring(0,10)+"..."); }else{ hold.tv2.setText(book.getDescription()); } //把imgview做好标记 hold.img.setTag(book.getCover_image_url()); //处理图片,通过缓存 //得到图片 Bitmap bitmap = loadImageUtil.loadBitmapByImgUrl(book.getCover_image_url(), new LoadImageUtil.CallBack() { @Override public void callBack(String imgUrl, Bitmap bitmap) { if(bitmap != null){ ImageView img = (ImageView) parent.findViewWithTag(imgUrl); img.setImageBitmap(bitmap); } } }); if(bitmap != null){//如果图片在缓存中,直接获取展示 hold.img.setImageBitmap(bitmap); } return convertView; } class ViewHold{ TextView tv1,tv2; ImageView img; } }); } }.execute(URLDB.JSON_URL1); } }); } }
下面来写一下 ImageLoader的原理
package com.bwie.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import java.lang.ref.SoftReference;
import java.util.HashMap;
/**
* Created by Administrator on 2017/9/5.
*/
public class LoadImageUtil {
private Context context;
private HashMap<String,SoftReference<Bitmap>> bitMaps;
public LoadImageUtil(Context context) {
this.context = context;
this.bitMaps = new HashMap<String,SoftReference<Bitmap>>();//实例化缓存容器
}
//回调的接口
public interface CallBack{
public void callBack(String imgUrl,Bitmap bitmap);
}
//加载图片,进行缓存
public Bitmap loadBitmapByImgUrl(final String imgUrl, final CallBack callBack){
//先判断缓存中有没有图片,得到图片
SoftReference<Bitmap> soft = bitMaps.get(imgUrl);
if(soft != null){
Bitmap bitmap = soft.get();//从软引用中获得bitmap
if(bitmap != null){//缓存中有次图片,直接用
return bitmap;
}else{
bitMaps.remove(imgUrl);//key(图片的url)对应的bitmap消耗了,key也没有意义
}
}
//代码走到此处,说明缓存中没有图片,需要到第三级缓存:网络缓存去取
//通过handler实现子线程和ui主线程的通信
final Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bitmap bitmap = (Bitmap) msg.obj;
callBack.callBack(imgUrl,bitmap);
}
};
//启动线程访问图片
new Thread(){
@Override
public void run() {
super.run();
//加载图片
Bitmap bitmap = new NetWorkUtils().getBitmapByHttpUrlConnectionGet(imgUrl);
//压缩图片
//把bitmap缓存到缓存中,通过软引用
bitMaps.put(imgUrl,new SoftReference<Bitmap>(bitmap));
handler.sendMessage(handler.obtainMessage(1,bitmap));//发给handler
}
}.start();
// //内存中没有图片,通过次线程去加载,然后放在缓存中
// bitMaps.put(imgUrl,bitmap);
return null;
}
}
3、网络请求的工具类
package com.bwie.utils;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* 网络请求的工具类
* Created by Administrator on 2017/9/1.
*/
public class NetWorkUtils {
//获得json串的方法,通过HttpClient get
public String getJsonByHttpClientGet(String url){
return "";
}
//获得json串的方法,通过HttpClient get
public String getJsonByHttpUrlConnectionGet(String jsonUrl){
URL url = null;
HttpURLConnection httpURLConnection = null;
String strJson = "";
InputStream inputStream = null;
try {
url = new URL(jsonUrl);
httpURLConnection = (HttpURLConnection) url.openConnection();
int responseCode = httpURLConnection.getResponseCode();
if(responseCode == 200){
inputStream = httpURLConnection.getInputStream();
byte[] b = new byte[1024];
int length = 0;
while((length = inputStream.read(b)) != -1){//循环读取json串,拼装
strJson += new String(b,0,length);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return strJson;//返回最终的json数据
}
//获得json串的方法,通过HttpClient get
public Bitmap getBitmapByHttpUrlConnectionGet(String imageUrl){
URL url = null;
HttpURLConnection httpURLConnection = null;
Bitmap bitmap = null;
InputStream inputStream = null;
try {
url = new URL(imageUrl);
httpURLConnection = (HttpURLConnection) url.openConnection();
int responseCode = httpURLConnection.getResponseCode();
if(responseCode == 200){
inputStream = httpURLConnection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);//把图片信息(输入流)
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bitmap;//返回最终的json数据
}
}
4、一定要记得加网络权限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.bwie.httpclienthomework1">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
今天写的网络请求图片,是ImageLoader的原理,所以用的不多,但是原理一定要懂,不然在工作中遇到实际的问题,会让你懵逼,对,懵逼!!
相关文章推荐
- Android 利用 AsyncTask 异步读取网络图片
- Android 中使用 AsyncTask 异步读取网络图片
- Android利用AsyncTask异步加载网络图片,详细教程,图+代码+文字+项目
- Android异步下载网络图片(其二AsyncTask)
- 【Android】网络图片加载优化(一)利用弱引用缓存异步加载
- android问题:从list集合中循环读取图片地址,使用异步下载,利用baseAdapter怎样显示到listView中
- Android异步下载网络图片(其二:AsyncTask)
- Android之AsyncTask异步任务下载网络图片
- android ListView利用SimpleAdapter显示特定布局并且异步加载网络图片
- Android异步任务AsyncTask使用解析 获取网络图片
- Android开发之图片处理专题(二):利用AsyncTask和回调接口实现图片的异步加载和压缩
- Android异步加载学习笔记之四:利用缓存优化网络加载图片及ListView加载优化
- Android异步下载网络图片(其二:AsyncTask)
- Android异步载入学习笔记之四:利用缓存优化网络载入图片及ListView载入优化
- Android使用ImageLoader异步加载网络图片(一)读取单张图片
- Android网络:HTTP之利用HttpURLConnection访问网页、获取网络图片实例 (附源码)
- android快速响应(二)AsyncTask实例!异步下载图片
- android从零开始(五)读取网络图片
- 网络相册:Gallery+AsyncTask+URLConnection 实现异步加载网络图片
- Android异步从网络下载图片并且缓存图片到本地的demo