国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

幾個常用的工具類-異步下載、handler下載工具類、圖片緩存等

2019-11-09 15:15:12
字體:
來源:轉載
供稿:網友

-工具類目錄: —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 blocke.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*/@Overrideprotected 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;} }}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 皋兰县| 肇庆市| 广安市| 富裕县| 阳新县| 阿克陶县| 松阳县| 西吉县| 永昌县| 桃源县| 闻喜县| 鲁甸县| 肥城市| 忻城县| 黄浦区| 汶川县| 准格尔旗| 西宁市| 莆田市| 东安县| 丰原市| 酒泉市| 加查县| 台州市| 阳泉市| 乌海市| 长子县| 海口市| 肇东市| 辛集市| 九龙县| 宁国市| 漳浦县| 锡林浩特市| 鱼台县| 毕节市| 大渡口区| 台山市| 宝山区| 稷山县| 新安县|