收录了一下Android常用的Util类方法:
package com.pc.myapp.utils;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.*;
import android.provider.MediaStore;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.*;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
/**
* Created by pc on 15-6-8.
*/
public class Util {
public static class Converter{
public static int dp2px(int dp,Context context){
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,dp,context.getResources().getDisplayMetrics());
}
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
public static float px2dp(float px, Context context){
return px / (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,1,context.getResources().getDisplayMetrics()));
}
public static byte[] bitmap2ByteArray(Bitmap bitmap){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
return baos.toByteArray();
}
public static Bitmap byteArray2Bitmap(byte[] byteArray){
return BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
}
public static String imageUri2Path(Context context, Uri contentUri){
Cursor cursor = context.getContentResolver().query(contentUri, null, null, null, null);
cursor.moveToFirst();
String mediaFilePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return mediaFilePath;
}
}
public static class ReflectionUtil{
public static Object invokeMethod(Object receiver, String methodName, Class<?>[] paramTypes, Object[] paramValues){
return invokeMethodInternal(receiver, receiver.getClass(), methodName, paramTypes, paramValues);
}
public static Object invokeStaticMethod(String className, String methodName, Class<?>[] paramTypes, Object[] paramValues) {
try {
return invokeMethodInternal(null, Class.forName(className), methodName, paramTypes, paramValues);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
private static Object invokeMethodInternal(Object receiver, Class<?> clazz, String methodName, Class<?>[] paramTypes, Object[] paramValues) {
try {
Method method = clazz.getDeclaredMethod(methodName, paramTypes);
method.setAccessible(true);
return method.invoke(receiver, paramValues);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
public static class HandlerUtil{
public static void sendMsg(Handler handler, int msgCode, Bundle bundle){
Message msg = handler.obtainMessage(msgCode);
if (bundle != null){
msg.setData(bundle);
}
handler.sendMessage(msg);
}
}
public static class FileUtil{
public static long getFileSize(String path){
return getFileSize(path);
}
public static long getFileSize(File file){
if (file.exists()) {
if (file.isDirectory()){
long size = 0;
for (File subFile : file.listFiles()){
size += getFileSize(subFile);
}
return size;
} else {
return file.length();
}
} else {
throw new IllegalArgumentException("File does not exist!");
}
}
public static void copyFile(String originalFilePath,String destFilePath) throws IOException {
copyFile(new File(originalFilePath), destFilePath);
}
public static void copyFile(String originalFilePath,File destFile) throws IOException {
copyFile(new File(originalFilePath), destFile);
}
public static void copyFile(File originalFile, String destFilePath) throws IOException {
copyFile(originalFile, new File(destFilePath));
}
public static void copyFile(File originalFile, File destFile) throws IOException {
copy(new FileInputStream(originalFile), new FileOutputStream(destFile));
}
public static void copy(InputStream inputStream, OutputStream outPutStream) throws IOException {
byte buf[] = new byte[1024];
int numRead = 0;
while ((numRead = inputStream.read(buf)) != -1) {
outPutStream.write(buf,0,numRead);
}
close(outPutStream,inputStream);
}
public static void deleteFile(String path){
deleteFile(new File(path));
}
public static 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);
}
}
public static void deleteFileRecursively(File file){
if (file.isDirectory()){
for (String fileName : file.list()) {
File item = new File(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());
}
}
}
public static String read2String(File file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(file));
StringBuffer sb = new StringBuffer();
String readLine = null;
while ((readLine = reader.readLine()) != null) {
sb.append(readLine);
sb.append("\n");
}
reader.close();
return sb.toString();
}
public static byte[] read2ByteArray(File file) throws IOException {
ByteArrayOutputStream outPutStream = new ByteArrayOutputStream(1024);
copy(new FileInputStream(file), outPutStream);
return outPutStream.toByteArray();
}
public static void writeByteArray (byte[] byteArray, String filePath) throws IOException {
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath));
outputStream.write(byteArray);
outputStream.close();
}
public static void saveBitmapToFile(String fileForSaving, Bitmap bitmap) {
File targetFile = new File(Environment.getExternalStorageDirectory().getPath() + "/" + fileForSaving + ".png");
if (!targetFile.exists()) {
try {
targetFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
FileOutputStream fos = new FileOutputStream(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"
*/
public static String toCatenatedPath(String... sequentialPathStrs) {
String catenatedPath = "";
for (int i = 0; i < sequentialPathStrs.length - 1; i++) {
catenatedPath += sequentialPathStrs[i] + File.separator;
}
catenatedPath += sequentialPathStrs[sequentialPathStrs.length - 1];
return catenatedPath;
}
}
public static class TimeUtil {
public static String format(String pattern, long milliseconds) {
return (new SimpleDateFormat(pattern)).format(new Date(milliseconds));
}
/**
* 将以毫秒为单位的时间转化为“小时:分钟:秒”的格式(不足1小时的没有小时部分)。
* 适用于显示一段视频的时长(有些视频时长是大于1小时,有些是不足1小时的)
*/
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static String formatHMS(long millis) {
final long millisOfOneHour = TimeUnit.HOURS.toMillis(1);
if (millis < millisOfOneHour) {
return String.format("%1$tM:%1$tS", millis);
} else {
return String.format("%1$d:%2$TM:%2$TS", millis / millisOfOneHour, millis % millisOfOneHour);
}
}
}
public static class BitmapUtil{
/**
* 此函数用于提取缩略图,以减少内存
* @param isFromAssets 是否来自assets
* @param path 路径
* @param requireWidth 宽度
* @param requireHeigth 高度
* @param loseLessQuality 是否较少地丢失图片质量 如果为true表示按宽度和高度的缩小倍数中的较少者进行采样。
* @return bitmap
*/
public static Bitmap sample(boolean isFromAssets, String path, int requireWidth,int requireHeigth, boolean loseLessQuality){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPurgeable = true;
options.inInputShareable = true;
/**
* 设置options.inSampleSize
*/
options.inJustDecodeBounds = true;
InputStream is = null;
try {
is = new FileInputStream(path);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BitmapFactory.decodeStream(is, null, options);
int widthMinification = (int) Math.ceil((float)options.outWidth/(float)requireWidth);
int heightMinification = (int) Math.ceil((float)options.outHeight/(float)requireHeigth);
if (loseLessQuality) {
options.inSampleSize = Math.min(widthMinification, heightMinification);
} else {
options.inSampleSize = Math.max(widthMinification, heightMinification);
}
close(is);
/**
* 这里才是提取缩略图
*/
options.inJustDecodeBounds = false;
try {
is = new FileInputStream(path);
} catch (FileNotFoundException e) {
return null;
}
Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);
close(is);
return bitmap;
}
/**
* 根据指定的图像路径和大小来获取缩略图
* 此方法有两点好处:
* 1. 使用较小的内存空间,第一次获取的bitmap实际上为null,只是为了读取宽度和高度,
* 第二次读取的bitmap是根据比例压缩过的图像,第三次读取的bitmap是所要的缩略图。
* 2. 缩略图对于原图像来讲没有拉伸,这里使用了2.2版本的新工具ThumbnailUtils,使
* 用这个工具生成的图像不会被拉伸。
*
* @param imagePath 图像的路径
* @param width 图像的宽度
* @param height 图像的高度
* @return bitmap
*/
public static Bitmap getImageThumbnail(String imagePath, int width, int height){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
// 获取这个图片的宽和高,注意此处的bitmap为null
BitmapFactory.decodeFile(imagePath, options);
// 重新读入图片,读取缩放后的bitmap,注意这次要把options.inJustDecodeBounds 设为 false
options.inJustDecodeBounds = false; // 设为 false
// 计算缩放比
int h = options.outHeight;
int w = options.outWidth;
int beWidth = w / width;
int beHeight = h / height;
int be = 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);
return bitmap;
}
/**
* 获取视频的缩略图
* 先通过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 指定大小的视频缩略图
*/
public static Bitmap getVideoThumbnail(String videoPath, int width, int height, int kind) {
Bitmap bitmap;
// 获取视频的缩略图
bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, kind);
bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
return bitmap;
}
}
public static class SDcard {
public static boolean isSDcardReadable(){
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
public static boolean checkIsSDcardFull(IOException e){
/** 在应用层通过异常判断是否是SD卡已满,除了下面的方式,目前尚未找到更好的方法。 **/
return e.getMessage().contains("No space left on device");
}
}
public static class Notifier {
public static void showLongToast(CharSequence content, Context cxt){
Toast.makeText(cxt,content,Toast.LENGTH_LONG).show();
}
public static void showShortToast(CharSequence content, Context cxt){
Toast.makeText(cxt,content,Toast.LENGTH_SHORT).show();
}
public static void showLongToast(Context cxt, int resId){
showLongToast(cxt.getResources().getText(resId),cxt);
}
public static void showShortToast(Context cxt, int resId){
showShortToast(cxt.getResources().getText(resId), cxt);
}
}
public static class GraphUtil {
public static ShapeDrawable createRoundCornerShapeDrawable(float radius, int color) {
float[] outerRadii = new float[8];
for (int i=0; i < 8; i++){
outerRadii[i] = radius;
}
ShapeDrawable sd = new ShapeDrawable(new RoundRectShape(outerRadii, null, null));
sd.getPaint().setColor(color);
return sd;
}
public static GradientDrawable createGradientDrawable(int fillColor, int strokeWidth, int strokeColor, float cornerRadius) {
GradientDrawable gd = new GradientDrawable();
gd.setColor(fillColor);
if (strokeWidth > 0) {
gd.setStroke(strokeWidth, strokeColor);
}
gd.setCornerRadius(cornerRadius);
return gd;
}
}
public static class AnimUtil {
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
public static void alphaAnim(View v, long duration, float animateToValue) {
v.animate().setDuration(duration).alpha(animateToValue);
}
}
public static class LogUtil{
private static final String TAG = LogUtil.class.getPackage().getName();
private static final int PRINT_DETAIL_LOG_LEVEL = Log.ERROR;
public static void v(Object object){
Log.v(TAG, buildMsg(Log.INFO, object));
}
public static void d(Object object){
Log.d(TAG, buildMsg(Log.INFO, object));
}
public static void i(Object object){
Log.i(TAG, buildMsg(Log.INFO, object));
}
public static void w(Object object){
Log.w(TAG, buildMsg(Log.INFO, object));
}
public static void e(Object object){
Log.e(TAG, buildMsg(Log.ERROR, object));
}
private static String buildMsg(int logLevel, Object object) {
StringBuilder buffer = new StringBuilder();
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);
return buffer.toString();
}
}
public static class TextUtil {
public static String getEditTextContent(EditText editText) {
return editText.getText().toString();
}
public static boolean isChinese(char c) {
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) {
return true;
}
return false;
}
public static boolean isEnglish(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
}
public static boolean isInsideView(MotionEvent event, View v) {
Rect rect = new Rect();
v.getGlobalVisibleRect(rect);
return rect.contains((int) event.getRawX(), (int) event.getRawY());
}
public static void close(Closeable... closeables) {
for (Closeable closeable : closeables) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static boolean isExistedInDb(ContentResolver resolver, Uri uri, String selection, String[] selectionArgs) {
Cursor c = resolver.query(uri, null, selection, selectionArgs, null);
boolean isExistedInDb = (c != null || c.getCount() > 0);
if (c != null) {
c.close();
}
return isExistedInDb;
}
}