package com.example.zhiyuan.teacheryunifang.utils;
import android.content.Context;import android.graphics.Bitmap;import com.example.zhiyuan.teacheryunifang.R;import com.nostra13.universalimageloader.core.DisplayImageOptions;import com.nostra13.universalimageloader.core.ImageLoader;import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;import com.nostra13.universalimageloader.core.ImageLoaderConfiguration.Builder;import com.nostra13.universalimageloader.core.assist.ImageScaleType;import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;public class ImageLoaderUtils { /** * 初始化ImageLoaderConfiguration 這個可以只做簡單的初始化,此方法建議在 * application中進行初始化 * * @param context */ public static void initConfiguration(Context context) { Builder configuration = new ImageLoaderConfiguration.Builder(context);//--------------------------------------------------------------------// 本段代碼,如果是測試使用時,可以不添加,不影響ImageLoader的正常使用// configuration.memoryCacheExtraOptions(480, 800)// // default = device screen dimensions// // 緩存到磁盤中的圖片寬高// .diskCacheExtraOptions(480, 800, null)// // .taskExecutor(null)// // .taskExecutorForCachedImages()// .threadPoolSize(3)// // default 線程優先級// .threadPRiority(Thread.NORM_PRIORITY - 2)// // default// .tasksProcessingOrder(QueueProcessingType.FIFO)// // // default設置在內存中緩存圖像的多種尺寸// // 加載同一URL圖片時,imageView從小變大時,從內存緩存中加載// .denyCacheImageMultipleSizesInMemory()// // 超過設定的緩存大小時,內存緩存的清除機制// .memoryCache(new LruMemoryCache(2 * 1024 * 1024))// // 內存的一個大小// .memoryCacheSize(2 * 1024 * 1024).memoryCacheSizePercentage(13)// // default 將圖片信息緩存到該路徑下// // default 磁盤緩存的大小// .diskCacheSize(50 * 1024 * 1024)// // 磁盤緩存文件的個數// .diskCacheFileCount(100)// // 磁盤緩存的文件名的命名方式//一般使用默認值 (獲取文件名稱的hashcode然后轉換成字符串)或md5 new// // Md5FileNameGenerator()源文件的名稱同過md5加密后保存// .diskCacheFileNameGenerator(new HashCodeFileNameGenerator())// // 設置默認的圖片加載// // 使用默認的圖片解析器// .imageDecoder(new BaseImageDecoder(true)) // default// .defaultDisplayImageOptions(DisplayImageOptions.createSimple())// .writeDebugLogs();//--------------------------------------------------------------------- ImageLoader.getInstance().init(configuration.build()); } /** * 初始化DisplayImageOptions * * @param * @return */ public static DisplayImageOptions initOptions() { DisplayImageOptions options = new DisplayImageOptions.Builder() // 設置圖片在下載期間顯示的圖片 .showImageOnLoading(R.mipmap.ic_empty_page) // 設置圖片Uri為空或是錯誤的時候顯示的圖片 .showImageOnFail(R.mipmap.ic_empty_page) // 設置下載的圖片是否緩存在內存中 .cacheInMemory(true) // 設置下載的圖片是否緩存在SD卡中 .cacheOnDisc(true)//--------------------------------------------------------------------//如果您只想簡單使用ImageLoader這塊也可以不用配置 // 是否考慮JPEG圖像EXIF參數(旋轉,翻轉) .considerExifParams(true) // 設置圖片以如何的編碼方式顯示 .imageScaleType(ImageScaleType.EXACTLY_STRETCHED) // 設置圖片的解碼類型// .bitmapConfig(Bitmap.Config.RGB_565) // 設置圖片的解碼配置 // .decodingOptions(options) // .delayBeforeLoading(int delayInMillis)//int // delayInMillis為你設置的下載前的延遲時間 // 設置圖片加入緩存前,對bitmap進行設置 // .preProcessor(BitmapProcessor preProcessor) // 設置圖片在下載前是否重置,復位 .resetViewBeforeLoading(true) // 是否設置為圓角,弧度為多少 .displayer(new RoundedBitmapDisplayer(20)) // 是否圖片加載好后漸入的動畫時間 .displayer(new FadeInBitmapDisplayer(100)) // 構建完成//------------------------------------------------------------------- .build(); return options; }}
-----------------------------------------------------------------------------------------------
SDcard讀寫工具
--------------------------------------------------------------------
package com.ynf.app.utils;import android.content.Context;import android.os.Environment;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.OptionalDataException;import java.io.StreamCorruptedException;import java.text.DecimalFormat;/** * @author: Leiqiuyun * @date: 2016/3/21. */public class SdCardCache { public static void saveInSdCard(Object loop, Context context, String filepath) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { //File sdCardDir = Environment.getExternalStorageDirectory();//獲取SDCard目錄 File sdFile = new File(context.getExternalFilesDir(""), filepath); try { FileOutputStream fos = new FileOutputStream(sdFile); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(loop);// 寫入 fos.close(); // 關閉輸出流 } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //Toast.makeText(WebviewTencentActivity.this, "成功保存到sd卡", Toast.LENGTH_LONG).show(); } } public static Object readSdcard(Context context, String filepath) { Object oAuth_1 = null; //File sdCardDir = Environment.getExternalStorageDirectory();//獲取SDCard目錄 File sdFile = new File(context.getExternalFilesDir(""), filepath); try { FileInputStream fis = new FileInputStream(sdFile); //獲得輸入流 ObjectInputStream ois = new ObjectInputStream(fis); oAuth_1 = (Object) ois.readObject(); return oAuth_1; } catch (StreamCorruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (OptionalDataException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return oAuth_1; } /** * // 轉換文件大小 * * @param fileS * @return */ public static String formetFileSize(long fileS) { DecimalFormat df = new DecimalFormat("#.00"); String fileSizeString = ""; if (fileS < 1024) { fileSizeString = df.format((double) fileS) + "B"; } else if (fileS < 1048576) { fileSizeString = df.format((double) fileS / 1024) + "K"; } else if (fileS < 1073741824) { fileSizeString = df.format((double) fileS / 1048576) + "M"; } else { fileSizeString = df.format((double) fileS / 1073741824) + "G"; } return fileSizeString; } public static void deleteFile(File directory) { if (directory != null && directory.exists() && directory.isDirectory()) { for (File item : directory.listFiles()) { item.delete(); } } }}
-------------------------------------
md5加密工具
----------------------------------
package com.example.zhiyuan.teacheryunifang.utils;import java.security.MessageDigest;public class MD5Encoder {/*** Md5Encoder* * @param string* @return* @throws Exception*/public static String encode(String string) throws Exception {byte[] hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));StringBuilder hex = new StringBuilder(hash.length * 2);for (byte b : hash) {if ((b & 0xFF) < 0x10) {hex.append("0");}hex.append(Integer.toHexString(b & 0xFF));}return hex.toString();}}
-------------------------------------------------
網絡請求緩存工具
----------------------------
package com.example.zhiyuan.teacheryunifang.Base;import android.text.TextUtils;import com.example.zhiyuan.teacheryunifang.manager.ThreadManager;import com.example.zhiyuan.teacheryunifang.utils.CommonUtils;import com.example.zhiyuan.teacheryunifang.utils.LogUtils;import com.example.zhiyuan.teacheryunifang.utils.MD5Encoder;import com.example.zhiyuan.teacheryunifang.utils.NetUtils;import org.xutils.common.Callback;import org.xutils.http.RequestParams;import org.xutils.x;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;/** * Created by zhiyuan on 16/8/31. */public abstract class BaseData<T> { /** * 網絡出錯 */ public static final int Error_Net = 100; /** * 請求出錯 */ public static final int Error_Request = 200; public static final long LONGTTIME = 1000 * 60 * 60 * 72; public static final long SHORTTIME = 1000 * 60 * 10; public static final long NOTIME = 0; public void getData(String path, String args, int index, long time) { //判斷一下緩存時間,如果緩存時間為0,說明是要最新的時間,直接請求網絡獲取數據 if (time == 0) { getDataFromNet(path, args, index, time); } else { //先看本地是否有數據 String data = getDataFromLocal(path, index, time); //如果為空,說明本地沒有數據 if (TextUtils.isEmpty(data)) { //再看網絡 getDataFromNet(path, args, index, time); } else { //如果從本地將數據請求到了數據,設置數據 setResultData(data); } } } /** * 本類不知道如何設置數據,將設置數據的方法進行抽象 * * @param data */ public abstract void setResultData(String data); private void getDataFromNet(final String path, String args, final int index, final long time) { //先判斷網絡狀態 int netWorkType = NetUtils.getNetWorkType(CommonUtils.getContext()); //如果網絡狀態是可用的,就進行網絡請求 if (netWorkType != NetUtils.NETWORKTYPE_INVALID) { //請求時,對數據進行拼接,path+args 路徑+參數 RequestParams requestParams = new RequestParams(path + args); LogUtils.e("AAAAAAAAAAAAAAAAAA", path + args); //開始請求網絡 x.http().get(requestParams, new Callback.CommonCallback<String>() { @Override public void onSuccess(final String json) { //請求數據成功之后,進行數據設置 setResultData(json); //開啟線程,將數據寫到本地 ThreadManager.getThreadPoolProxy().execute(new Runnable() { @Override public void run() { writeDataToLocal(json, path, index, time); } }); } //請求失敗,將結果回傳 @Override public void onError(Throwable throwable, boolean b) { setFailResult(Error_Request); } @Override public void onCancelled(CancelledException e) { } @Override public void onFinished() { } }); } else { //網絡問題 setFailResult(Error_Net); } } protected abstract void setFailResult(int error_Net); /** * 將數據寫到本地 * * @param json * @param path * @param index * @param time */ private void writeDataToLocal(String json, String path, int index, long time) { //獲取緩存路徑 File cacheDir = CommonUtils.getContext().getCacheDir(); File file = null; try { file = new File(cacheDir, MD5Encoder.encode(path + index)); } catch (Exception e) { e.printStackTrace(); } if (!file.exists()) { try { //創建該文件 file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } BufferedWriter bufferedWriter = null; try { bufferedWriter = new BufferedWriter(new FileWriter(file.getAbsolutePath())); //在文件第一行寫入當前時間+有效時間 //21408348372737+1000*60*60 bufferedWriter.write(System.currentTimeMillis() + time + "/r/n"); //寫入json bufferedWriter.write(json); //數據刷新 bufferedWriter.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (bufferedWriter != null) bufferedWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 從本地獲取信息 * * @param path * @param index * @param time @return */ private String getDataFromLocal(String path, int index, long time) { //獲取本地路徑 File cacheDir = CommonUtils.getContext().getCacheDir(); File file = null; try { //找到和寫入時對應的文件名稱 file = new File(cacheDir, MD5Encoder.encode(path + index)); } catch (Exception e) { e.printStackTrace(); } BufferedReader bufferedReader = null; try { //定義字符緩沖流,指向文件 bufferedReader = new BufferedReader(new FileReader(file.getAbsolutePath())); //之前時間+有效時間 long t = Long.parseLong(bufferedReader.readLine()); //在有效時間之內 //90 +10 if (System.currentTimeMillis() - t < 0) { StringBuilder stringBuilder = new StringBuilder(); String line = null; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line); } return stringBuilder.toString(); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (bufferedReader != null) bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } return null; }}
新聞熱點
疑難解答