工具類封裝的獲取網路資料+網路圖片+三級緩衝圖片的方法
阿新 • • 發佈:2018-11-10
呼叫:NewUtils .getInstance(content).方法名呼叫其中的方法
package com.example.renzhili20181106; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.util.LruCache; import com.google.gson.Gson; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class NewUtils { //單例 private static NewUtils instance; private LruCache<String,Bitmap> cache; private File saveDir; private NewUtils(Context context) { int size= (int) (Runtime.getRuntime().freeMemory()*0.3); cache=new LruCache<>(size); //圖片檔案快取目錄 saveDir = new File(context.getCacheDir(), "img_cache"); //不存在,建立 if(!saveDir.exists()) { saveDir.mkdirs(); } } public static NewUtils getInstance(Context context) { if (instance==null){ instance=new NewUtils(context); } return instance; } //介面 public interface RequeryCallBack<T>{ void Requery(T o); } //網路資料介面回撥的方法 public void getRequery(String url, final Class clazz, final RequeryCallBack callBack){ @SuppressLint("StaticFieldLeak") AsyncTask<String,Void,Object> asyncTask = new AsyncTask<String, Void, Object>() { @Override protected Object doInBackground(String... strings) { return getGson(strings[0],clazz); } @Override protected void onPostExecute(Object o) { callBack.Requery(o); } }.execute(url); } //解析json網路資料 public static <E> E getGson(String url,Class clazz){ String getdata = getdata(url); E e = (E) new Gson().fromJson(getdata,clazz); return e; } //HttpClient獲取網路資料的方法 public static String getdata(String url){ try { HttpClient client = HttpClients.createDefault(); HttpUriRequest request = RequestBuilder .get() .setUri(url) .build(); HttpResponse execute =client.execute(request); int statusCode = execute.getStatusLine().getStatusCode(); if (statusCode==200){ String s = EntityUtils.toString(execute.getEntity()); return s; } } catch (Exception e) { e.printStackTrace(); } return null; } //解析 public static <E> E getGsondata(String url,Class clazz){ String requery = getRequery(url); E e = (E) new Gson().fromJson(requery, clazz); return e; } //HttpURLConnection獲取網路資料的方法 public static String getRequery(String url){ String s=""; try { URL url1 = new URL(url); HttpURLConnection urlConnection = (HttpURLConnection) url1.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setConnectTimeout(5000); urlConnection.setReadTimeout(5000); int responseCode = urlConnection.getResponseCode(); if (responseCode==200){ s = getstrarn2string(urlConnection.getInputStream()); } } catch (Exception e) { e.printStackTrace(); } return s; } //轉換位元組流為字元流 private static String getstrarn2string(InputStream inputStream) throws IOException { StringBuilder builder = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); for (String tmp = br.readLine();tmp!=null;tmp=br.readLine()){ builder.append(tmp); } return builder.toString(); } //介面 public interface CallBack{ void loadimage(String url ,Bitmap bitmap); } //介面回撥 public void loadimage(final String urlimage, final CallBack callBack){ @SuppressLint("StaticFieldLeak") AsyncTask<String,Void,Bitmap> asyncTask = new AsyncTask<String, Void, Bitmap>() { @Override protected Bitmap doInBackground(String... strings) { return getBitmap(strings[0]); } @Override protected void onPostExecute(Bitmap bitmap) { callBack.loadimage(urlimage,bitmap); } }.execute(urlimage); } //獲取圖片三級快取 public Bitmap getBitmap(String urlimage){ Bitmap bitmap=null; //從記憶體中獲取圖片 bitmap=cache.get(url2Key(urlimage)); if (bitmap!=null){ return bitmap; } //從sd中獲取 bitmap=getBitmapForFile(urlimage); if (bitmap!=null){ //緩衝到記憶體中 cache.put(url2Key(urlimage),bitmap); return bitmap; } //從網路中獲取圖片 bitmap=loadimage(urlimage); if (bitmap!=null){ //存入磁碟 saveBitmap2File(urlimage, bitmap); //存入記憶體 cache.put(url2Key(urlimage),bitmap); } return bitmap; } //網磁碟寫檔案 private void saveBitmap2File(String urlimage, Bitmap bitmap) { FileOutputStream fileOutputStream=null; try { fileOutputStream = new FileOutputStream(new File(saveDir, url2Key(urlimage))); bitmap.compress(Bitmap.CompressFormat.JPEG,100,fileOutputStream); } catch (Exception e) { e.printStackTrace(); }finally { if(fileOutputStream!=null){ try { fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } //從檔案讀取圖片 private Bitmap getBitmapForFile(String urlStr) {/////// //解碼檔案為bitmap圖片 return BitmapFactory.decodeFile(new File(saveDir, url2Key(urlStr)).getAbsolutePath()); } //將url轉換成key //url 做key: 太長;如果作為檔名,不允許/ ? private String url2Key(String url) { //MD5 摘要方法 //MessageDigest return String.valueOf(url.hashCode()); } //獲取網路圖片 public static Bitmap loadimage(String urlimage){ try { URL url1 = new URL(urlimage); HttpURLConnection urlConnection = (HttpURLConnection) url1.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setConnectTimeout(5000); urlConnection.setReadTimeout(5000); int responseCode = urlConnection.getResponseCode(); if (responseCode==200){ Bitmap bitmap = BitmapFactory.decodeStream(urlConnection.getInputStream()); return bitmap; } } catch (Exception e) { e.printStackTrace(); } return null; } }