Android开发——常用功能源码

编程入门 行业动态 更新时间:2024-10-09 13:25:30

Android开发——常用功能<a href=https://www.elefans.com/category/jswz/34/1770099.html style=源码"/>

Android开发——常用功能源码

1.三级缓存

package com.heima.zhbj55.view;import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.HttpURLConnection;
import java.MalformedURLException;
import java.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;import com.heima.zhbj55.utils.MD5Utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.LruCache;
import android.util.Log;public class ImageCache {private Context context;private LruCache<String, Bitmap> lruCache;private ExecutorService newFixedThreadPool;private Handler handler;public static final int SUCCESS = 10;public static final int FAIL = 20;private static final String tag = "ImageCache";//handler对象是由使用者传入过来的,说明处理数据的方法在使用者那边public ImageCache(Context context,Handler handler) {this.context = context;// 获取最大内存的1/8作为lru最大可使用的内存int cacSize = (int) (Runtime.getRuntime().maxMemory() / 8);// 原理:// 如果现在添加某一张图片,加上原有已使用内存大小以后大于cacSize大小,会自动移除最近最少使用的图片,保证内存大小不超过cacSizelruCache = new LruCache<String, Bitmap>(cacSize) {// 想删除某一张图片,前提必须知道图片的大小@Overrideprotected int sizeOf(String key, Bitmap value) {return value.getRowBytes() * value.getHeight();}};this.handler = handler;// 创建一个线程池,线程池中可开启的线程数量(cpu个数*2+1)这是最佳数量的个数newFixedThreadPool = Executors.newFixedThreadPool(5);}/*** 解析指定地址的图片并且三级缓存图片* @param url 图片地址* @param position 图片的标示,为了获取到每一张图片所用* @return 返回Bitmap对象*/public Bitmap parseUrl(String url, int position) {Bitmap cacheBitmap = getBitmapFromCache(url);if (cacheBitmap != null) {Log.i(tag, "从内存中获取图片");return cacheBitmap;}Bitmap localBitmap = getBitmapFromLocal(url);if (localBitmap != null) {Log.i(tag, "从硬盘中获取图片");return localBitmap;}getBitmapFromNet(url, position);Log.i(tag, "从网络获取图片");return null;}// 从内存中获取图片资源private Bitmap getBitmapFromCache(String url) {Bitmap bitmap = lruCache.get(url);return bitmap;}// 从本地获取图片资源private Bitmap getBitmapFromLocal(String url) {// 从本地地址中获取图片资源,并且存入内存中String fileName = MD5Utils.md5(url).substring(10);File file = new File(context.getCacheDir(), fileName);try {Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(file));lruCache.put(url, bitmap);return bitmap;} catch (FileNotFoundException e) {e.printStackTrace();}return null;}// 从网络获取图片资源private void getBitmapFromNet(String url, int position) {// 开发中必须以线程池开启线程,不能自己定义线程开启,这样方便管理,增加效率newFixedThreadPool.execute(new ThreadTask(url, position));}/*** 网络获取图片* @author UPC**/private class ThreadTask implements Runnable {private String url;private int position;public ThreadTask(String url, int position) {this.url = url;this.position = position;}@Overridepublic void run() {try {URL urlObject = new URL(url);HttpURLConnection con = (HttpURLConnection) urlObject.openConnection();con.setConnectTimeout(2000);con.setReadTimeout(2000);con.setRequestMethod("GET");int code = con.getResponseCode();if (code==200) {InputStream in = con.getInputStream();Bitmap bitmap = BitmapFactory.decodeStream(in);//子线程不能更新UIMessage msg = Message.obtain();msg.obj = bitmap;msg.what = SUCCESS;//保存图片的标示,通过这个标示,然后再通过父控件的fingViewByTag()方法获取到指定的控件msg.arg1 = position;handler.sendMessage(msg);//保存图片到内存lruCache.put(url, bitmap);//保存图片到本地writeToLocal(url, bitmap);return;}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}//抛出异常,放松获取图片失败的消息Message msg = Message.obtain();msg.what = FAIL;handler.sendMessage(msg);}}public void writeToLocal(String url,Bitmap bitmap){String fileName = MD5Utils.md5(url).substring(10);File file = new File(context.getCacheDir(),fileName);try {FileOutputStream fos = new FileOutputStream(file);bitmappress(CompressFormat.JPEG, 70, fos);} catch (FileNotFoundException e) {e.printStackTrace();}}
}

调用时的逻辑

private Handler handler = new Handler() {public void handleMessage(Message msg) {switch (msg.what) {case ImageCache.SUCCESS:// 下载成功Bitmap bitmap = (Bitmap) msg.obj;// 根据传递进去的索引去拿到,显示这个图片的控件int position = msg.arg1;ImageView imageView = (ImageView) view.findViewWithTag(position);if (bitmap != null && imageView != null) {imageView.setImageBitmap(BitmapUtil.toRoundBitmap(bitmap));}break;case ImageCache.FAIL:// 下载失败Toast.makeText(mContext, "头像获取失败", Toast.LENGTH_SHORT).show();break;}}};

2.对字符串进行MD5加密

package com.heima.zhbj55.utils;import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;public class MD5Utils {public static String md5(String source){try {MessageDigest digest = MessageDigest.getInstance("MD5");byte[] md5Source = digest.digest(source.getBytes());StringBuilder sb = new StringBuilder();for (byte b : md5Source) {int i = b & 0xff;// 获取该字节的低八位信息, 11111111String hexString = Integer.toHexString(i);if (hexString.length() < 2) {hexString = "0" + hexString;}sb.append(hexString);}return sb.toString();} catch (NoSuchAlgorithmException e) {e.printStackTrace();}return null;}
}

3.图片相关操作

(1)图片缩放

a.缩放图片普通

/*** 缩放图片多指定比例* @param path 图片路径* @param width 宽* @param height 高* @return*/public static Bitmap resizeImage(String path, int width, int height) {BitmapFactory.Options options = new BitmapFactory.Options();options.inJustDecodeBounds = true;// 不加载bitmap到内存中BitmapFactory.decodeFile(path, options);int outWidth = options.outWidth;int outHeight = options.outHeight;options.inDither = false;options.inPreferredConfig = Bitmap.Config.ARGB_8888;options.inSampleSize = 1;if (outWidth != 0 && outHeight != 0 && width != 0 && height != 0) {int sampleSize = (outWidth / width + outHeight / height) / 2;options.inSampleSize = sampleSize;}options.inJustDecodeBounds = false;return BitmapFactory.decodeFile(path, options);}//使用Bitmap加Matrix来缩放public static Bitmap resizeImage(Bitmap bitmap, int w, int h)  {  Bitmap BitmapOrg = bitmap;  int width = BitmapOrg.getWidth();  int height = BitmapOrg.getHeight();  int newWidth = w;  int newHeight = h;  float scaleWidth = ((float) newWidth) / width;  float scaleHeight = ((float) newHeight) / height;  Matrix matrix = new Matrix();  matrix.postScale(scaleWidth, scaleHeight);  // if you want to rotate the Bitmap   // matrix.postRotate(45);   Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,  height, matrix, true);  return resizedBitmap;  }

b.防止OOM(据说)

/*** 加载本地图片 防止oom* * @param filePath* @param outWidth* @param outHeight* @return*/public static Bitmap readBitmapAutoSize(Context context, String filePath,int outWidth, int outHeight) {// outWidth和outHeight是目标图片的最大宽度和高度,用作限制// BufferedInputStream bs = null;FileInputStream fs = null;BufferedInputStream bs = null;try {File newFile = new File(filePath);if (!newFile.exists()) {return null;}int rad = readPictureDegree(filePath);try {fs = new FileInputStream(filePath);bs = new BufferedInputStream(fs);if (fs != null && bs != null) {BitmapFactory.Options options = setBitmapOption(context,filePath, outWidth, outHeight);if (rad != 0) {return rotaingImageView(rad,BitmapFactory.decodeStream(bs, null, options));} elsereturn BitmapFactory.decodeStream(bs, null, options);} else {try {File file = new File(filePath);if (file.exists()) {file.delete();}} catch (Exception e) {// TODO: handle exception}return null;}} catch (Exception e) {e.printStackTrace();}} catch (Exception e) {e.printStackTrace();} finally {try {bs.close();fs.close();} catch (Exception e) {e.printStackTrace();}}return null;}public static Bitmap rotaingImageView(int angle, Bitmap mBitmap) {Matrix matrix = new Matrix();matrix.postRotate(angle);Bitmap b = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(),mBitmap.getHeight(), matrix, true);return b;}public static int readPictureDegree(String imagePath) {int imageDegree = 0;try {ExifInterface exifInterface = new ExifInterface(imagePath);int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_NORMAL);switch (orientation) {case ExifInterface.ORIENTATION_ROTATE_90:imageDegree = 90;break;case ExifInterface.ORIENTATION_ROTATE_180:imageDegree = 180;break;case ExifInterface.ORIENTATION_ROTATE_270:imageDegree = 270;break;}} catch (IOException e) {e.printStackTrace();}return imageDegree;}

c.根据指定像素数来缩放

注:调用——opts.inSampleSize = computeSampleSize(opts, -1, 295000);

/*** 缩放图片到指定比例* @param options	目标图片的属性对象* @param minSideLength	不知道,用的时候传入的是-1* @param maxNumOfPixels 目标像素点* @return*/public static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {  int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);  int roundedSize;  if (initialSize <= 8) {  roundedSize = 1;  while (roundedSize < initialSize) {  roundedSize <<= 1;  }  } else {  roundedSize = (initialSize + 7) / 8 * 8;  }  return roundedSize;  }  private static int computeInitialSampleSize(BitmapFactory.Options options,int minSideLength, int maxNumOfPixels) {  double w = options.outWidth;  double h = options.outHeight;  int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));  int upperBound = (minSideLength == -1) ? 128 :(int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength));  if (upperBound < lowerBound) {  // return the larger one when there is no overlapping zone.  return lowerBound;  }  if ((maxNumOfPixels == -1) && (minSideLength == -1)) {  return 1;  } else if (minSideLength == -1) {  return lowerBound;  } else {  return upperBound;  }  }  

d.最早自己写的

(2)图片变形

/*** 转换图片成圆形* * @param bitmap*            传入Bitmap对象* @return*/public static Bitmap toRoundBitmap(Bitmap bitmap) {int width = bitmap.getWidth();int height = bitmap.getHeight();float roundPx;float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;if (width <= height) {roundPx = width / 2;top = 0;bottom = width;left = 0;right = width;height = width;dst_left = 0;dst_top = 0;dst_right = width;dst_bottom = width;} else {roundPx = height / 2;float clip = (width - height) / 2;left = clip;right = width - clip;top = 0;bottom = height;width = height;dst_left = 0;dst_top = 0;dst_right = height;dst_bottom = height;}Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);Canvas canvas = new Canvas(output);final int color = 0xff424242;final Paint paint = new Paint();final Rect src = new Rect((int) left, (int) top, (int) right,(int) bottom);final Rect dst = new Rect((int) dst_left, (int) dst_top,(int) dst_right, (int) dst_bottom);final RectF rectF = new RectF(dst);paint.setAntiAlias(true);canvas.drawARGB(0, 0, 0, 0);paint.setColor(color);canvas.drawRoundRect(rectF, roundPx, roundPx, paint);paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));canvas.drawBitmap(bitmap, src, dst, paint);return output;}

4.中文转换为拼音

注:需要第三方jar包【pinyin4j-2.5.0】

/** * 汉字转换位汉语拼音,英文字符不变 * @param chines 汉字 * @return 拼音 */  public static String converterToSpell(String chines){          String pinyinName = "";  char[] nameChar = chines.toCharArray();  HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();  defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);  defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);  for (int i = 0; i < nameChar.length; i++) {  if (nameChar[i] > 128) {  try {  pinyinName += PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat)[0];  } catch (BadHanyuPinyinOutputFormatCombination e) {  e.printStackTrace();  }  }else{  pinyinName += nameChar[i];  }  }  return pinyinName;  }  

5.解析Excel

需要第三方开源包:jxl

File excel = new File(context.getCacheDir(),"areaid_v.xls");//创建解析对象Workbook book;try {book = Workbook.getWorkbook(excel);} catch (Exception e) {throw new RuntimeException("file not found");}//获取第一张表格Sheet sheet = book.getSheet(0);Cell cellCityCode, cellCityName;int row = 1;while (true) {//获取第几行第一列内容cellCityCode = sheet.getCell(0, row);//获取第几行第三列内容cellCityName = sheet.getCell(2, row);//这是退出逻辑,因情况而定if (cellCityName.getContents().equals(address.getName())) {address.setWeatherIndexCode(cellCityCode.getContents());break; }if ("".equals(cellCityCode.getContents()) == true) //如果读取的数据为空break;row++;}book.close();


更多推荐

Android开发——常用功能源码

本文发布于:2024-02-26 03:02:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1701151.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:源码   常用   功能   Android

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!