我们的工程中会有很多工具类,工具类通常有如下的特点。
- 工具类的方法大多是静态方法。(使用的过程中,不需要new创建对象)
- 构造方法应该是private的,做到一种强制性的非new创建 ,而是通过类名直接调用。如PackgeUtils.getPackageInforation();
- 方法中需要的变量如Context,是通过参数传入,非属性(因为在静态的方法中,需要静态的属性,静态的属性会引用当前对象,阻止了垃圾回收)。
- 类名通常是XXXUtils
package com.android.phone; import android.graphics.Bitmap; import android.os.SystemClock; import android.os.SystemProperties; import android.util.Log; public class BitmapUtils { /** This class is never instantiated.正如这个英文的说明,私有的构造器是一种强制非new */ private BitmapUtils() { } public static Bitmap createBlurredBitmap(Bitmap bitmap) { long startTime = SystemClock.uptimeMillis(); if (bitmap == null) { return null; } final int scaledSize = 128; bitmap = Bitmap.createScaledBitmap(bitmap, scaledSize, scaledSize, true /* filter */); bitmap = gaussianBlur(bitmap); long endTime = SystemClock.uptimeMillis(); return bitmap; } public static Bitmap gaussianBlur(Bitmap source) {//静态方法,需要的变量传入 int width = source.getWidth(); int height = source.getHeight(); int numPixels = width * height; int[] in = new int[numPixels]; int[] tmp = new int[numPixels]; source.getPixels(in, 0, width, 0, 0, width, height); gaussianBlurFilter(in, tmp, width, height); gaussianBlurFilter(tmp, in, width, height); Bitmap filtered = Bitmap.createBitmap(in, width, height, Bitmap.Config.ARGB_8888); source.recycle(); return filtered; } private static void gaussianBlurFilter(int[] in, int[] out, int width, int height) { final int RADIUS = 4; final int[] weights = { 13, 23, 32, 39, 42, 39, 32, 23, 13}; // Adds up to 256 int inPos = 0; int widthMask = width - 1; // width must be a power of two. for (int y = 0; y < height; ++y) { int alpha = 0xff; int outPos = y; for (int x = 0; x < width; ++x) { int red = 0; int green = 0; int blue = 0; for (int i = -RADIUS; i <= RADIUS; ++i) { int argb = in[inPos + (widthMask & (x + i))]; int weight = weights[i+RADIUS]; red += weight *((argb & RED_MASK) >> RED_MASK_SHIFT); green += weight *((argb & GREEN_MASK) >> GREEN_MASK_SHIFT); blue += weight *(argb & BLUE_MASK); } out[outPos] = (alpha << 24) | ((red >> 8) << RED_MASK_SHIFT) | ((green >> 8) << GREEN_MASK_SHIFT) | (blue >> 8); outPos += height; } inPos += width; } } }