android文件和图片的处理工具类(一)

 package com.gzcivil.utils;

 import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;
import java.util.UUID; import android.app.ActivityManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView; import com.gzcivil.R;
import com.igexin.sdk.PushManager; public class CommonUtil { /**
* 回收ImageView图片
*
* @param imageView
*/
public static synchronized void recycleImage(ImageView imageView) {
if (imageView == null)
return;
Drawable drawable = imageView.getDrawable();
recycleDrawable(drawable);
imageView.setImageBitmap(null);
} /**
* 回收View背景图片
*
* @param view
*/
@SuppressWarnings("deprecation")
public static synchronized void recycleBackground(View view) {
if (view == null)
return;
Drawable drawable = view.getBackground();
recycleDrawable(drawable);
view.setBackgroundDrawable(null);
} /**
* 回收方法
*/
private static void recycleDrawable(Drawable drawable) {
if (drawable != null && drawable instanceof BitmapDrawable) {
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
if (bitmap != null && !bitmap.isRecycled()) {
LogUtils.e(SysUtils.LOG_TAG, "图片回收了");
bitmap.recycle();
}
}
} public static double getDirSize(File file) {
// 判断文件是否存在
if (file.exists()) {
// 如果是目录则递归计算其内容的总大小
if (file.isDirectory()) {
File[] children = file.listFiles();
double size = 0;
for (File f : children)
size += getDirSize(f);
return size;
} else {// 如果是文件则直接返回其大小,以“兆”为单位
return file.length();
}
} else {
return 0.0;
}
} public static String FormetFileSize(double fileS) {// 转换文件大小
DecimalFormat df = new DecimalFormat("#.00");
String fileSizeString = "";
if (fileS < 1024) {
fileSizeString = "0.0" + "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;
} /*
* Java文件操作 获取文件扩展名
*/
public static String getExtensionName(String filename) {
if ((filename != null) && (filename.length() > 0)) {
int dot = filename.lastIndexOf('.');
if ((dot > -1) && (dot < (filename.length() - 1))) {
return filename.substring(dot + 1);
}
}
return filename;
} /*
* Java文件操作 获取不带扩展名的文件名
*/
public static String getFileNameNoEx(String filename) {
if ((filename != null) && (filename.length() > 0)) {
int dot = filename.lastIndexOf('.');
if ((dot > -1) && (dot < (filename.length()))) {
return filename.substring(0, dot);
}
}
return filename;
} public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
} int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
} ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
} /**
* 检查是否存在SDCard
*
* @return
*/
public static boolean hasSdcard() {
String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED)) {
return true;
} else {
return false;
}
} /**
* 四舍五入
*
* @param v
* @param scale
* 多少位
* @return
*/
public static double decimalFormat(Float v, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(v));
BigDecimal one = new BigDecimal("1");
return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).floatValue();
} // 获取个推CID
public static String GetCid(Context context) {
return PushManager.getInstance().getClientid(context);
} // 获取机器码
public static String GetMachineCode(Context context) {
String code = "";
final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
final String tmDevice, tmSerial, androidId;
tmDevice = "" + tm.getDeviceId();
tmSerial = "" + tm.getSimSerialNumber();
androidId = "" + android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
UUID deviceUuid = new UUID(androidId.hashCode(), ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
code = deviceUuid.toString();
return code;
} /**
* 派单状态
*
* @param param
* @return
*/
public static String getCheetStatus(String param) {
if (param == null || param.equals("")) {
return "";
}
String Status = "";
if (param == "00" || param.equals("00")) {
Status = "<font color='#e53c41'>未接</font>";
} else if (param == "01" || param.equals("01")) {
Status = "<font color='#e53c41'>执行中</font>";
} else if (param == "02" || param.equals("02")) {
Status = "<font color='#2ab823'>完成</font>";
} else if (param == "08" || param.equals("08")) {
Status = "<font color='#f13f1b'>终止</font>";
} else if (param == "09" || param.equals("09")) {
Status = "<font color='#f13f1b'>拒收</font>";
} else {
Status = "";
}
return Status;
} /**
* 会议通知状态
*
* @param param
* @return
*/
public static String getMeetStatus(String param) {
String Status = "";
if (param == null || param.equals("")) {
return Status;
}
if (param.equals("1")) {
Status = "<font color='#e53c41'>未接</font>";
} else if (param.equals("2")) {
Status = "<font color='#2ab823'>已同意</font>";
} else if (param.equals("3")) {
Status = "<font color='#f13f1b'>请假</font>";
}
return Status;
} /**
* 检测应用程序 是否前台运行
*
* @param context
* @return
*/
public static boolean isServiceStarted(Context context) {
boolean isStarted = false;
try {
ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
int intGetTastCounter = 1000;
List<ActivityManager.RunningServiceInfo> mRunningService = mActivityManager.getRunningServices(intGetTastCounter);
for (ActivityManager.RunningServiceInfo amService : mRunningService) {
if (0 == amService.service.getPackageName().compareTo("com.msd.terminal")) {
isStarted = true;
break;
}
}
} catch (SecurityException e) {
e.printStackTrace();
}
return isStarted;
} public static boolean isServiceRunning(Context mContext, String className) {
boolean isRunning = false;
ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(30);
if (!(serviceList.size() > 0)) {
return false;
}
for (int i = 0; i < serviceList.size(); i++) {
if (serviceList.get(i).service.getClassName().equals(className) == true) {
isRunning = true;
break;
}
}
return isRunning;
} // 获取版本号
public static String getVersion(Context context) {
try {
PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return pi.versionName;
} catch (NameNotFoundException e) {
e.printStackTrace();
return context.getString(R.string.version_unknown);
}
} /** 保存方法 */
public static boolean saveBigImgToSmall(String bigImgPath, String smallImgPath, String smallImgName, int min) { boolean flag = false;
try {
File lFile = new File(bigImgPath);
if (lFile.exists() && lFile.isFile()) {
InputStream is = new FileInputStream(bigImgPath);
Bitmap bitmap = BitmapFactory.decodeStream(is, null, getBitmapOption());
int w = bitmap.getWidth();
int h = bitmap.getHeight();
LogUtils.e(SysUtils.LOG_TAG, "压缩前:w = " + w + ", h = " + h);
if (min < 200) {
min = 200;
}
if (w > h) {
w = w * min / h;
h = min;
} else {
h = h * min / w;
w = min;
}
LogUtils.e(SysUtils.LOG_TAG, "压缩后:w = " + w + ", h = " + h);
// 压缩原图为小图显示
bitmap = ThumbnailUtils.extractThumbnail(bitmap, w, h, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
File f = new File(smallImgPath);
if (f.exists())
f.delete();
FileOutputStream out = new FileOutputStream(f);
flag = bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return flag;
} /**
* 获取Bitmap的读取参数
*/
public static final BitmapFactory.Options getBitmapOption() {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.RGB_565;
opt.inPurgeable = true;
opt.inInputShareable = true;
return opt;
} public static void openFile(Context context, File file) {
try {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 设置intent的Action属性
intent.setAction(Intent.ACTION_VIEW);
// 获取文件file的MIME类型
String type = getMIMEType(file);
// 设置intent的data和Type属性。
intent.setDataAndType(Uri.fromFile(file), type);
// 跳转
context.startActivity(intent);
// Intent.createChooser(intent, "请选择对应的软件打开该附件!");
} catch (ActivityNotFoundException e) {
// TODO: handle exception
MyToast.showToast(context, "sorry附件不能打开,请下载相关软件!", 0);
}
} private static String getMIMEType(File file) { String type = "*/*";
String fName = file.getName();
// 获取后缀名前的分隔符"."在fName中的位置。
int dotIndex = fName.lastIndexOf(".");
if (dotIndex < 0) {
return type;
}
/* 获取文件的后缀名 */
String end = fName.substring(dotIndex, fName.length()).toLowerCase();
if (end == "")
return type;
// 在MIME和文件类型的匹配表中找到对应的MIME类型。
for (int i = 0; i < MIME_MapTable.length; i++) { if (end.equals(MIME_MapTable[i][0]))
type = MIME_MapTable[i][1];
}
return type;
} // 可以自己随意添加
private static String[][] MIME_MapTable = {
// {后缀名,MIME类型}
{ ".3gp", "video/3gpp" }, { ".apk", "application/vnd.android.package-archive" }, { ".asf", "video/x-ms-asf" }, { ".avi", "video/x-msvideo" }, { ".bin", "application/octet-stream" }, { ".bmp", "image/bmp" }, { ".c", "text/plain" }, { ".class", "application/octet-stream" }, { ".conf", "text/plain" }, { ".cpp", "text/plain" }, { ".doc", "application/msword" }, { ".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }, { ".xls", "application/vnd.ms-excel" }, { ".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }, { ".exe", "application/octet-stream" }, { ".gif", "image/gif" }, { ".gtar", "application/x-gtar" }, { ".gz", "application/x-gzip" }, { ".h", "text/plain" }, { ".htm", "text/html" }, { ".html", "text/html" },
{ ".jar", "application/java-archive" }, { ".java", "text/plain" }, { ".jpeg", "image/jpeg" }, { ".jpg", "image/jpeg" }, { ".js", "application/x-javascript" }, { ".log", "text/plain" }, { ".m3u", "audio/x-mpegurl" }, { ".m4a", "audio/mp4a-latm" }, { ".m4b", "audio/mp4a-latm" }, { ".m4p", "audio/mp4a-latm" }, { ".m4u", "video/vnd.mpegurl" }, { ".m4v", "video/x-m4v" }, { ".mov", "video/quicktime" }, { ".mp2", "audio/x-mpeg" }, { ".mp3", "audio/x-mpeg" }, { ".mp4", "video/mp4" }, { ".mpc", "application/vnd.mpohun.certificate" }, { ".mpe", "video/mpeg" }, { ".mpeg", "video/mpeg" }, { ".mpg", "video/mpeg" }, { ".mpg4", "video/mp4" }, { ".mpga", "audio/mpeg" }, { ".msg", "application/vnd.ms-outlook" }, { ".ogg", "audio/ogg" }, { ".pdf", "application/pdf" }, { ".png", "image/png" },
{ ".pps", "application/vnd.ms-powerpoint" }, { ".ppt", "application/vnd.ms-powerpoint" }, { ".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation" }, { ".prop", "text/plain" }, { ".rc", "text/plain" }, { ".rmvb", "audio/x-pn-realaudio" }, { ".rtf", "application/rtf" }, { ".sh", "text/plain" }, { ".tar", "application/x-tar" }, { ".tgz", "application/x-compressed" }, { ".txt", "text/plain" }, { ".wav", "audio/x-wav" }, { ".wma", "audio/x-ms-wma" }, { ".wmv", "audio/x-ms-wmv" }, { ".wps", "application/vnd.ms-works" }, { ".xml", "text/plain" }, { ".z", "application/x-compress" }, { ".zip", "application/x-zip-compressed" }, { "", "*/*" } }; }
上一篇:Android Assert工具类


下一篇:java类在eclipse上打jar包,Linux上成功运行的实例