-工具类目录:
—1、异步任务工具类
—2、Handler 下载工具类
—3、图片缓存到内存工具类
—4、缓存工具类,缓存到一级缓存中
这几个是适合初学者使用的下载缓存工具类
——————异步任务下载的工具类
/**
* 异步任务的封装
* @author Ken
*
*/
public class AbsAsyncTask extends AsyncTask<String, Void, Object> {
//任务处理类型
private DownType downType;
private ImageView iv;
private OnDownListener onDownListener;
public AbsAsyncTask(DownType downType){
this.downType = downType;
}
@Override
protected Object doInBackground(String... params) {
byte[] bs = getByteArray(params[0]);
if (bs != null) {
switch (downType) {
case JSON:
//表示下载的是JSON
String json = new String(bs);
if(onDownListener != null){
Object datas = onDownListener.downJSON(json);
return datas;
}
break;
case IMAGE:
//表示下载的Image
Bitmap bitmap = BitmapFactory.decodeByteArray(bs, 0, bs.length);
return bitmap;
}
}
return null;
}
@Override
protected void onPostExecute(Object result) {
if(result != null){
switch (downType) {
case JSON:
if(onDownListener != null){
onDownListener.paresJSON(result);
}
break;
case IMAGE:
Bitmap bitmap = (Bitmap) result;
if(iv != null){
iv.setImageBitmap(bitmap);
}
break;
}
}
}
public AbsAsyncTask with(ImageView iv){
this.iv = iv;
return this;
}
//任务处理类型的枚举
public static enum DownType{
JSON,
IMAGE
}
/**
* 根据URL下载的到byte数组
* @param url
* @return
*/
private byte[] getByteArray(String urlStr){
InputStream in = null;
ByteArrayOutputStream out = null;
try {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(3000);
conn.connect();
if(conn.getResponseCode() == 200){
in = conn.getInputStream();
out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024 * 8];
int len = 0;
while((len = in.read(buffer)) != -1){
out.write(buffer, 0, len);
}
//得到下载好的json字符串
return out.toByteArray();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(in != null){
in.close();
}
if(out != null){
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* List<News>
*
* List<House>
* @author Ken
*
*/
public interface OnDownListener{
Object downJSON(String json);
void paresJSON(Object datas);
}
/**
* 设置json下载功能以后的回调方法
* @param onDownListener
*/
public AbsAsyncTask setOnDownListener(OnDownListener onDownListener) {
this.onDownListener = onDownListener;
return this;
}
}
———-Handler 下载工具类
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by Ken on 2016/9/9.17:09
*/
public class DownUtil {
/*
创建一个拥有5个线程的线程池
*/
private static ExecutorService executor = Executors.newFixedThreadPool(5);
private OnDownListener onDownListener;
private Handler handler = new Handler();
//设置解析JSON的接口回调
public DownUtil setOnDownListener(OnDownListener onDownListener) {
this.onDownListener = onDownListener;
return this;
}
private OnDownImageListener onDownImageListener;
//设置图片下载的接口
public DownUtil setOnDownImageListener(OnDownImageListener onDownImageListener) {
this.onDownImageListener = onDownImageListener;
return this;
}
/**
* 下载JSON数据
*/
public void downJSON(final String url){
executor.submit(new Runnable() {
@Override
public void run() {
//在子线程中执行
byte[] bytes = requestURL(url);
if(bytes != null){
String json = new String(bytes);
//解析JSON
if(onDownListener != null){
final Object object = onDownListener.paresJson(json);
//将解析的结果回传给主线程
handler.post(new Runnable() {
@Override
public void run() {
//在主线程中执行
onDownListener.downSucc(object);
}
});
}
}
}
});
}
/**
* 下载图片
* @param url
*/
public void downBitmap(final String url){
executor.submit(new Runnable() {
@Override
public void run() {
//在子线程中执行
byte[] bytes = requestURL(url);
if(bytes != null) {
final Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
if(onDownImageListener != null){
handler.post(new Runnable() {
@Override
public void run() {
onDownImageListener.downSuccImg(bitmap);
}
});
}
}
}
});
}
/**
* 下载资源
* @return
*/
private byte[] requestURL(String urlStr){
InputStream in = null;
ByteArrayOutputStream out = null;
try {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(3000);
conn.connect();
if(conn.getResponseCode() == 200){
in = conn.getInputStream();
out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024 * 8];
int len;
while((len = in.read(buffer)) != -1){
out.write(buffer, 0, len);
}
//得到下载好的json字符串
return out.toByteArray();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(in != null){
in.close();
}
if(out != null){
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 接口回调
*/
public interface OnDownListener{
//解析JSON时回调
Object paresJson(String json);
//解析完成后回调
void downSucc(Object object);
}
/**
* 下载图片的接口回调
*/
public interface OnDownImageListener{
void downSuccImg(Bitmap bitmap);
}
}
————-图片缓存工具类——–缓存到硬盘—————–
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
/**
* 图片缓存工具类
*
* Created by Administrator on 2016/9/11 0011.
*/
public class ImageUtil {
//
public static String path = Environment.getExternalStorageDirectory() +
"/imageCache";
public static boolean isMounted(){
return Environment.getExternalStorageState().equals
(Environment.MEDIA_MOUNTED);
}
//
public static void saveImage(Bitmap bitmap, String url){
//
if (!isMounted()){
return ;
}
//
File file = new File(path);
if (!file.exists()){
file.mkdirs();
}
File urlFile = new File(url);
file = new File(file,urlFile.getName());
try {
bitmap.compress(CompressFormat.PNG, 100,new FileOutputStream
(file));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//
public static Bitmap getIamge(String url){
File file = new File(url);
String name = file.getName();
File imageFile = new File(path,name);
if(imageFile.exists()){
return BitmapFactory.decodeFile(imageFile.getAbsolutePath());
}
Log.d("print",imageFile.getAbsolutePath());
return null;
}
}
——————–图片缓存工具类-缓存到一级缓存———————————————-
package com.qf.util;
import android.graphics.Bitmap;
import android.util.LruCache;
/**
* Created by Ken on 2016/9/19.9:45
* 图片缓存的工具类
*/
public class LruCacheUtil {
/**
* 内存缓存的对象
* 参数:内存缓存最大值 -- 通常设置为可使用的内存的1/8
*
* lrucache如果缓存的大小已经达到了最大值,采用的移除策略:最近时间最少使用的缓存数据被移除
*
* bitmap.getByteCount()
* bitmap.getRowBytes() * bitmap.getHeight()
* : 一个bitmap所占的内存大小(字节)
*/
private static LruCache<String, Bitmap> lruCache = new LruCache<String, Bitmap>((int) (Runtime.getRuntime().maxMemory() / 8)){
/**
* 该方法用于计算缓存数据的大小
* @param key
* @return
*/
@Override
protected int sizeOf(String key, Bitmap bitmap) {
return bitmap.getRowBytes() * bitmap.getHeight();
}
};
/**
* 添加缓存
*/
public static void putCache(String url, Bitmap bitmap){
String key = MD5Util.MD5(url);
lruCache.put(key, bitmap);
}
/**
* 获得缓存
* @param url
* @return
*/
public static Bitmap getCache(String url){
String key = MD5Util.MD5(url);
return lruCache.get(key);
}
}
————————MD5Util加密工具类—————————
/**
* Created by Ken on 2016/9/19.10:13
*/
public class MD5Util {
public final static String MD5(String s) {
char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
try {
byte[] btInput = s.getBytes();
// 获得MD5摘要算法的 MessageDigest 对象
MessageDigest mdInst = MessageDigest.getInstance("MD5");
// 使用指定的字节更新摘要
mdInst.update(btInput);
// 获得密文
byte[] md = mdInst.digest();
// 把密文转换成十六进制的字符串形式
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}