android上的Util,工具类

来源:互联网 发布:v8网络制式怎么查看 编辑:程序博客网 时间:2024/05/06 05:40
importandroid.app.Activity;
importandroid.content.ContentResolver;
importandroid.content.Context;
importandroid.database.Cursor;
importandroid.graphics.Bitmap;
importandroid.graphics.BitmapFactory;
importandroid.graphics.Rect;
importandroid.graphics.RectF;
importandroid.graphics.drawable.GradientDrawable;
importandroid.graphics.drawable.ShapeDrawable;
importandroid.graphics.drawable.shapes.RoundRectShape;
importandroid.media.ThumbnailUtils;
importandroid.net.Uri;
importandroid.os.Bundle;
importandroid.os.Environment;
importandroid.os.Handler;
importandroid.os.Message;
importandroid.provider.MediaStore;
importandroid.util.Log;
importandroid.util.TypedValue;
importandroid.view.MotionEvent;
importandroid.view.View;
importandroid.view.ViewGroup;
importandroid.widget.EditText;
importandroid.widget.Toast;
 
importjava.io.*;
importjava.lang.reflect.Method;
importjava.text.SimpleDateFormat;
importjava.util.Date;
importjava.util.concurrent.TimeUnit;
 
/**
 * created by tedzyc
 */
publicclass Util {
 
    publicstatic class Converter {
 
        publicstatic int dp2px(intdp, Context context) {
            return(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics());
        }
 
        publicstatic float px2dp(floatpx, Context context) {
            returnpx / TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, context.getResources().getDisplayMetrics());
        }
 
        publicstatic byte[] bitmap2ByteArray(Bitmap bitmap) {
            ByteArrayOutputStream baos = newByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
            returnbaos.toByteArray();
        }
 
        publicstatic Bitmap byteArray2Bitmap(byte[] byteArray) {
            returnBitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
        }
 
        publicstatic String imageUri2Path(Context context, Uri contentUri) {
            Cursor c = context.getContentResolver().query(contentUri, null,null,null,null);
            c.moveToFirst();
            String mediaFilePath = c.getString(c.getColumnIndex(MediaStore.Images.Media.DATA));
            c.close();
            returnmediaFilePath;
        }
    }
 
    publicstatic class ReflectionUtil {
 
        publicstatic Object invokeMethod(Object receiver, String methodName, Class<?>[] paramTypes, Object[] paramValues) {
            returninvokeMethodInternal(receiver, receiver.getClass(), methodName, paramTypes, paramValues);
        }
 
        publicstatic Object invokeStaticMethod(String className, String methodName, Class<?>[] paramTypes, Object[] paramValues) {
            try{
                returninvokeMethodInternal(null, Class.forName(className), methodName, paramTypes, paramValues);
            }catch(ClassNotFoundException e) {
                e.printStackTrace();
            }
            returnnull;
        }
 
        privatestatic Object invokeMethodInternal(Object receiver, Class<?> clazz, String methodName, Class<?>[] paramTypes, Object[] paramValues) {
            try{
                Method method = clazz.getDeclaredMethod(methodName, paramTypes);
                method.setAccessible(true);
                returnmethod.invoke(receiver, paramValues);
            }catch(Exception e) {
                e.printStackTrace();
            }
            returnnull;
        }
    }
 
    publicstatic class HandlerUtil {
 
        publicstatic void sendMsg(Handler handler, intmsgCode, Bundle bundle) {
            Message msg = handler.obtainMessage(msgCode);
            if(bundle != null) {
                msg.setData(bundle);
            }
            handler.sendMessage(msg);
        }
    }
 
    publicstatic class FileUtil {
 
        /**
         * @param path : can be path of file or directory.
         */
        publicstatic long getFileSize(String path) {
            returngetFileSize(newFile(path));
        }
 
        /**
         * @param file : can be file or directory.
         */
        publicstatic long getFileSize(File file) {
            if(file.exists()) {
                if(file.isDirectory()) {
                    longsize = 0;
                    for(File subFile : file.listFiles()) {
                        size += getFileSize(subFile);
                    }
                    returnsize;
                }else{
                    returnfile.length();
                }
            }else{
                thrownew IllegalArgumentException("File does not exist!");
            }
        }
 
        publicstatic void copyFile(String originalFilePath, String destFilePath) throwsIOException {
            copyFile(newFile(originalFilePath), destFilePath);
        }
 
        publicstatic void copyFile(String originalFilePath, File destFile) throwsIOException {
            copyFile(newFile(originalFilePath), destFile);
        }
 
        publicstatic void copyFile(File originalFile, String destFilePath) throwsIOException {
            copyFile(originalFile,newFile(destFilePath));
        }
 
        publicstatic void copyFile(File originalFile, File destFile) throwsIOException {
            copy(newFileInputStream(originalFile), newFileOutputStream(destFile));
        }
 
        publicstatic void copy(InputStream inputStream, OutputStream outputStream) throwsIOException {
            bytebuf[] = newbyte[1024];
            intnumRead = 0;
 
            while((numRead = inputStream.read(buf)) != -1) {
                outputStream.write(buf,0, numRead);
            }
 
            close(outputStream, inputStream);
        }
 
        /**
         * @param path : can be file's absolute path or directories' path.
         */
        publicstatic void deleteFile(String path) {
            deleteFile(newFile(path));
        }
 
        /**
         * @param file : can be file or directory.
         */
        publicstatic void deleteFile(File file) {
            if(!file.exists()) {
                LogUtil.e("The file to be deleted does not exist! File's path is: " + file.getPath());
            }else{
                deleteFileRecursively(file);
            }
        }
 
        /**
         * Invoker must ensure that the file to be deleted exists.
         */
        privatestatic void deleteFileRecursively(File file) {
            if(file.isDirectory()) {
                for(String fileName : file.list()) {
                    File item = newFile(file, fileName);
 
                    if(item.isDirectory()) {
                        deleteFileRecursively(item);
                    }else{
                        if(!item.delete()) {
                            LogUtil.e("Failed in recursively deleting a file, file's path is: " + item.getPath());
                        }
                    }
                }
 
                if(!file.delete()) {
                    LogUtil.e("Failed in recursively deleting a directory, directories' path is: " + file.getPath());
                }
            }else{
                if(!file.delete()) {
                    LogUtil.e("Failed in deleting this file, its path is: " + file.getPath());
                }
            }
        }
 
        publicstatic String readToString(File file) throwsIOException {
            BufferedReader reader = newBufferedReader(newFileReader(file));
 
            StringBuffer buffer = newStringBuffer();
            String readLine = null;
 
            while((readLine = reader.readLine()) != null) {
                buffer.append(readLine);
                buffer.append("\n");
            }
 
            reader.close();
 
            returnbuffer.toString();
        }
 
        publicstatic byte[] readToByteArray(File file) throwsIOException {
            ByteArrayOutputStream outputStream = newByteArrayOutputStream(1024);
            copy(newFileInputStream(file), outputStream);
 
            returnoutputStream.toByteArray();
        }
 
        publicstatic void writeByteArray(byte[] byteArray, String filePath) throwsIOException {
            BufferedOutputStream outputStream = newBufferedOutputStream(newFileOutputStream(filePath));
            outputStream.write(byteArray);
            outputStream.close();
        }
 
        publicstatic void saveBitmapToFile(String fileForSaving, Bitmap bitmap) {
            File targetFile = newFile(Environment.getExternalStorageDirectory().getPath() + "/"+ fileForSaving + ".png");
 
            if(!targetFile.exists()) {
                try{
                    targetFile.createNewFile();
                }catch(IOException e) {
                    e.printStackTrace();
                }
            }
 
            try{
                FileOutputStream fos = newFileOutputStream(targetFile);
                bitmap.compress(Bitmap.CompressFormat.PNG,100, fos);
                fos.flush();
                fos.close();
            }catch(IOException e) {
                e.printStackTrace();
            }
        }
 
        /**
         * If sequentialPathStrs are "a","b","c", below method return "a/b/c"
         */
        publicstatic String toCatenatedPath(String... sequentialPathStrs) {
            String catenatedPath = "";
            for(inti = 0; i < sequentialPathStrs.length - 1; i++) {
                catenatedPath += sequentialPathStrs[i] + File.separator;
            }
            catenatedPath += sequentialPathStrs[sequentialPathStrs.length - 1];
            returncatenatedPath;
        }
    }
 
    publicstatic class TimeUtil {
 
        publicstatic String format(String pattern, longmilliseconds) {
            return(newSimpleDateFormat(pattern)).format(newDate(milliseconds));
        }
 
        /**
         * 将以毫秒为单位的时间转化为“小时:分钟:秒”的格式(不足1小时的没有小时部分)。
         * 适用于显示一段视频的时长(有些视频时长是大于1小时,有些是不足1小时的)
         */
        publicstatic String formatHMS(longmillis) {
            finallong millisOfOneHour = TimeUnit.HOURS.toMillis(1);
 
            if(millis < millisOfOneHour) {
                returnString.format("%1$tM:%1$tS", millis);
            }else{
                returnString.format("%1$d:%2$TM:%2$TS", millis / millisOfOneHour, millis % millisOfOneHour);
            }
        }
    }
 
    publicstatic class BitmapUtil {
 
        /**
         * 此函数用于提取缩略图,以节省内存。
         * l
         *
         * @param path
         * @param loseLessQuality 是否较少地丢失图片质量 如果为true表示按宽度和高度的缩小倍数中的较少者进行采样。
         */
        publicstatic Bitmap sample(booleanisFromAssets, String path, intrequireWidth, intrequireHeight,
                                    booleanloseLessQuality) {
            BitmapFactory.Options options = newBitmapFactory.Options();
            options.inPurgeable = true;
            options.inInputShareable = true;
 
            /**
             * "options.inJustDecodeBounds = true"这步是为了设置options.inSampleSize
             */
            options.inJustDecodeBounds = true;
            InputStream is = null;
            try{
                is = newFileInputStream(path);
            }catch(FileNotFoundException e) {
                returnnull;
            }
            BitmapFactory.decodeStream(is,null, options);
            intwidthMinification = (int) Math.ceil((float) options.outWidth / (float) requireWidth);
            intheightMinification = (int) Math.ceil((float) options.outHeight / (float) requireHeight);
 
            if(loseLessQuality) {
                options.inSampleSize = Math.min(widthMinification, heightMinification);
            }else{
                options.inSampleSize = Math.max(widthMinification, heightMinification);
            }
            close(is);
 
            /**
             * 这一步做真正的提取缩略图
             */
            options.inJustDecodeBounds = false;
            try{
                is = newFileInputStream(path);
            }catch(FileNotFoundException e) {
                returnnull;
            }
            Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);
            close(is);
 
            returnbitmap;
        }
 
        /**
         * 根据指定的图像路径和大小来获取缩略图
         * 此方法有两点好处:
         * 1. 使用较小的内存空间,第一次获取的bitmap实际上为null,只是为了读取宽度和高度,
         * 第二次读取的bitmap是根据比例压缩过的图像,第三次读取的bitmap是所要的缩略图。
         * 2. 缩略图对于原图像来讲没有拉伸,这里使用了2.2版本的新工具ThumbnailUtils,使
         * 用这个工具生成的图像不会被拉伸。
         *
         * @param imagePath 图像的路径
         * @param width     指定输出图像的宽度
         * @param height    指定输出图像的高度
         * @return 生成的缩略图
         */
        publicstatic Bitmap getImageThumbnail(String imagePath, intwidth, intheight) {
            BitmapFactory.Options options = newBitmapFactory.Options();
            options.inJustDecodeBounds = true;
            // 获取这个图片的宽和高,注意此处的bitmap为null
            BitmapFactory.decodeFile(imagePath, options);
 
            // 重新读入图片,读取缩放后的bitmap,注意这次要把options.inJustDecodeBounds 设为 false
            options.inJustDecodeBounds = false;// 设为 false
            // 计算缩放比
            inth = options.outHeight;
            intw = options.outWidth;
            intbeWidth = w / width;
            intbeHeight = h / height;
            intbe = 1;
            if(beWidth < beHeight) {
                be = beWidth;
            }else{
                be = beHeight;
            }
            if(be <= 0) {
                be = 1;
            }
            options.inSampleSize = be;
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
            // 利用ThumbnailUtils来创建缩略图,这里要指定要缩放哪个Bitmap对象
            bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
                    ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
            returnbitmap;
        }
 
        /**
         * 获取视频的缩略图
         * 先通过ThumbnailUtils来创建一个视频的缩略图,然后再利用ThumbnailUtils来生成指定大小的缩略图。
         * 如果想要的缩略图的宽和高都小于MICRO_KIND,则类型要使用MICRO_KIND作为kind的值,这样会节省内存。
         *
         * @param videoPath 视频的路径
         * @param width     指定输出视频缩略图的宽度
         * @param height    指定输出视频缩略图的高度度
         * @param kind      参照MediaStore.Images.Thumbnails类中的常量MINI_KIND和MICRO_KIND。
         *                  其中,MINI_KIND: 512 x 384,MICRO_KIND: 96 x 96
         * @return 指定大小的视频缩略图
         */
        publicstatic Bitmap getVideoThumbnail(String videoPath, intwidth, intheight, intkind) {
            Bitmap bitmap;
            // 获取视频的缩略图
            bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, kind);
            bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
                    ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
            returnbitmap;
        }
    }
 
    publicstatic class Sdcard {
 
        publicstatic boolean isSdcardReadable() {
            returnEnvironment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        }
 
        publicstatic boolean checkIsSdcardFull(IOException e) {
            /** 在应用层通过异常判断是否是SD卡已满,除了下面的方式,目前尚未找到更好的方法。 **/
            returne.getMessage().contains("No space left on device");
        }
    }
 
    publicstatic class Notifier {
 
        publicstatic void showLongToast(CharSequence content, Context cxt) {
            Toast.makeText(cxt, content, Toast.LENGTH_LONG).show();
        }
 
        publicstatic void showShortToast(CharSequence content, Context cxt) {
            Toast.makeText(cxt, content, Toast.LENGTH_SHORT).show();
        }
 
        publicstatic void showLongToast(Context cxt, intresId) {
            showLongToast(cxt.getResources().getText(resId), cxt);
        }
 
        publicstatic void showShortToast(Context cxt, intresId) {
            showShortToast(cxt.getResources().getText(resId), cxt);
        }
    }
 
    publicstatic class GraphUtil {
 
        /**
         * this method is used more frequently
         */
        publicstatic ShapeDrawable createRoundCornerShapeDrawable(floatradius, intcolor) {
            float[] outerRadii = newfloat[8];
            for(inti = 0; i < 8; i++) {
                outerRadii[i] = radius;
            }
 
            ShapeDrawable sd = newShapeDrawable(newRoundRectShape(outerRadii, null,null));
            sd.getPaint().setColor(color);
 
            returnsd;
        }
 
        publicstatic ShapeDrawable createRoundCornerShapeDrawableWithBoarder(floatradius, floatborderLength, intborderColor) {
            float[] outerRadii = newfloat[8];
            float[] innerRadii = newfloat[8];
            for(inti = 0; i < 8; i++) {
                outerRadii[i] = radius + borderLength;
                innerRadii[i] = radius;
            }
 
            ShapeDrawable sd = newShapeDrawable(newRoundRectShape(outerRadii, newRectF(borderLength, borderLength,
                    borderLength, borderLength), innerRadii));
            sd.getPaint().setColor(borderColor);
 
            returnsd;
        }
 
        /**
         * @param strokeWidth "stroke"表示描边, 传小于或等于0的值表示没有描边,同时忽略传入的strokeColor参数。
         */
        publicstatic GradientDrawable createGradientDrawable(intfillColor, intstrokeWidth, intstrokeColor, floatcornerRadius) {
            GradientDrawable gd = newGradientDrawable();
 
            gd.setColor(fillColor);
            if(strokeWidth > 0) {
                gd.setStroke(strokeWidth, strokeColor);
            }
            gd.setCornerRadius(cornerRadius);
 
            returngd;
        }
    }
 
    publicstatic class AnimUtil {
 
        publicstatic void alphaAnim(View v, longduration, floatanimateToValue) {
            v.animate().setDuration(duration).alpha(animateToValue);
        }
    }
 
    publicstatic class LogUtil {
 
        privatestatic final String TAG = LogUtil.class.getPackage().getName();
 
        /** Define your log level for printing out detail here. **/
        privatestatic final int PRINT_DETAIL_LOG_LEVEL = Log.ERROR;
 
        publicstatic void v(Object object) {
            Log.v(TAG, buildMsg(Log.INFO, object));
        }
 
        publicstatic void d(Object object) {
            Log.d(TAG, buildMsg(Log.INFO, object));
        }
 
        publicstatic void i(Object object) {
            Log.i(TAG, buildMsg(Log.INFO, object));
        }
 
        publicstatic void w(Object object) {
            Log.w(TAG, buildMsg(Log.INFO, object));
        }
 
        publicstatic void e(Object object) {
            Log.e(TAG, buildMsg(Log.ERROR, object));
        }
 
        privatestatic String buildMsg(intlogLevel, Object object) {
            StringBuilder buffer = newStringBuilder();
 
            if(logLevel >= PRINT_DETAIL_LOG_LEVEL) {
                StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[4];
                buffer.append("[ thread name is ");
                buffer.append(Thread.currentThread().getName());
                buffer.append(", ");
                buffer.append(stackTraceElement.getFileName());
                buffer.append(", method is ");
                buffer.append(stackTraceElement.getMethodName());
                buffer.append("(), at line ");
                buffer.append(stackTraceElement.getLineNumber());
                buffer.append(" ]");
                buffer.append("\n");
            }
 
            buffer.append("___");
            buffer.append(object);
 
            returnbuffer.toString();
        }
    }
 
    publicstatic class TextUtil {
 
        publicstatic String getEditTextContent(EditText editText) {
            returneditText.getText().toString();
        }
 
        publicstatic boolean isChinese(charc) {
            Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
            if(ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                    || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                    || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                    || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                    || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                    || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
                returntrue;
            }
            returnfalse;
        }
 
        publicstatic boolean isEnglish(charc) {
            return(c >= 'a'&& c <= 'z') || (c >= 'A'&& c <= 'Z');
        }
    }
 
    // >>>
    publicstatic void setEnableForChildrenView(ViewGroup parent, booleanenabled) {
        for(inti = 0; i < parent.getChildCount(); ++i) {
            View child = parent.getChildAt(i);
            child.setEnabled(enabled);
            if(child instanceofViewGroup) {
                setEnableForChildrenView((ViewGroup) child, enabled);
            }
        }
    }
 
    publicstatic View getContentView(Activity activity) {
        returnactivity.getWindow().getDecorView().getRootView();
    }
 
    publicstatic void freezeContentView(Activity activity) {
        setEnableForChildrenView(((ViewGroup) getContentView(activity)), false);
    }
    // <<<
 
    publicstatic boolean isInsideView(MotionEvent event, View v) {
        Rect rect = newRect();
        v.getGlobalVisibleRect(rect);
 
        returnrect.contains((int) event.getRawX(), (int) event.getRawY());
    }
 
    publicstatic void close(Closeable... closeables) {
        for(Closeable closeable : closeables) {
            if(closeable != null) {
                try{
                    closeable.close();
                }catch(IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
 
    publicstatic boolean isExistedInDb(ContentResolver resolver, Uri uri, String selection, String[] selectionArgs) {
        Cursor c = resolver.query(uri, null, selection, selectionArgs, null);
        booleanisExistedInDb = (c != null|| c.getCount() > 0);
        if(c != null) {
            c.close();
        }
        returnisExistedInDb;
    }
}
0 0
原创粉丝点击