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文件和图片的处理工具类(一)的更多相关文章
- Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类
Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类 ============================== ©Copyright 蕃薯耀 20 ...
- Android PermissionUtils:运行时权限工具类及申请权限的正确姿势
Android PermissionUtils:运行时权限工具类及申请权限的正确姿势 ifadai 关注 2017.06.16 16:22* 字数 318 阅读 3637评论 1喜欢 6 Permis ...
- 文件压缩、解压工具类。文件压缩格式为zip
package com.JUtils.file; import java.io.BufferedOutputStream; import java.io.File; import java.io.Fi ...
- 【Android代码片段之六】Toast工具类(实现带图片的Toast消息提示)
转载请注明出处,原文网址:http://blog.csdn.net/m_changgong/article/details/6841266 作者:张燕广 实现的Toast工具类ToastUtil封装 ...
- PHP 图片上传工具类(支持多文件上传)
====================ImageUploadTool======================== <?php class ImageUploadTool { private ...
- Android 自定义的圆角矩形ImageView 工具类
上图看效果 自定义圆角矩形ImageView工具类 package com.wechaotou.utils; import android.content.Context; import androi ...
- 图片压缩java工具类
package com.net.util; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.Fil ...
- android的Log日志打印管理工具类(一)
android的Log日志的打印管理工具类: package com.gzcivil.utils; import android.util.Log; /** * 日志打印管理 * * @author ...
- Android手机刘海屏(附工具类)
工具类 根据VIVO.OPPO.华为官方文档,这里整理了一个刘海屏工具类,判断设备是否为刘海屏,其他厂商公布相关方法后也会在此更新. OPPO: /** * OPPO * * @param conte ...
随机推荐
- 《编写高质量代码 改善Java程序的151个建议》书摘
例子1:三元操作符的陷阱 int i = 80; String str1 = String.valueOf(i < 100 ? 90 : 100); String str2 = String.v ...
- 虚拟机使用PuTTY、SSH Secure Shell Client前的配置
1 仅主机模式 2 检查子网IP 为192.168.154.0 3 进入虚拟机,检查IP地址 ip addr show 添加IP地址 ip addr add dev eno16777736 192.1 ...
- 全国计算机等级考试二级教程-C语言程序设计_第5章_循环结构
for循环结构的嵌套 外层循环每循环一次,内层循环会完整循环一次. 外层循环是竖. 内层循环是横. for, do...while, while的选择: 如果有固定次数,如阶乘! ,判断素数,用 fo ...
- Unity 之 Redux 模式(第二篇)—— Rigidbody 改造,摄像机控制
作者:软件猫 日期:2016年12月8日 转载请注明出处:http://www.cnblogs.com/softcat/p/6144041.html 上一篇文章中存在一个很严重的问题,首先我们先让 M ...
- Hexo 官方主题 landscape-plus 优化
博主喜欢简洁大方的Hexo主题,看了不下100个主题之后,最终选择了 landscape-plus 主题(针对中国大陆地区,对Hexo官方主题landscape进行优化后的版本).更多Hexo主题资源 ...
- 【27前端】字体图标 Font Face
设计师做的高保真原型图,难免会用到艺术字体. 采用切片的方式,简单,粗暴,节省时间.除了retina屏其它兼容性也是一流.但是在修改的时候,会花很大的力气.即使只是修改文字大小,也需要重新切图,更别说 ...
- 关于ASP.NET中的负载均衡
ASP.NET站点中做负载均衡: 基于HTTP协议我们可能发现我们要解决两点问题: 第一做到负载均衡,我们需要一个负载均衡器. 可以通过DNS轮询来做,在DNS服务器上配置为每次对我们做负载均衡的同一 ...
- ubuntu 开启 rewrite 模块
1.sudo a2enmod rewrite 开启Rewrite模块 (停用模块,使用 a2dismod) 2. 在/etc/apache2/ 修改apache2.conf 文件中把AllowOver ...
- php中的一些编程例子
#一到一百不能被三整除的数 for($i=1;$i<=100;$i++){ if($i%3 != 0){ $arr[] = $i; }} var_dump($arr); #水仙花数for($i= ...
- PHP 魔术常量__FUNCTION__与__METHOD__的区别
__FUNCTION__ 返回 函数名称(PHP 4.3.0 新加).自 PHP 5 起本常量返回该函数被定义时的名字(区分大小写).在 PHP 4 中该值总是小写字母的. __METHOD__ ...