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; }}
新闻热点
疑难解答