/**
* @描述 操作文件的工具类
*/
public class Tools {
/**
* 获取versionCode(ANDROID版本号)
*/
public static int getVersionCode() {
int versioncode = 0;
try {
PackageInfo pinfo = BaseApp.getInstance().getPackageManager().getPackageInfo(UIUtils.getPackageName(), 0);
versioncode = pinfo.versionCode;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return versioncode;
}
/**
* 获取VersionName
*
* @return
*/
public static String getVersionName() {
try {
PackageInfo pinfo = BaseApp.getInstance().getPackageManager()
.getPackageInfo(UIUtils.getPackageName(), 0);
String versionName = pinfo.versionName;
if (null != versionName) {
return versionName.toLowerCase();
//return "2.2.1";
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* 获取IP
*
* @return
*/
public static String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address)) {
String ip = inetAddress.getHostAddress().toString();
if (ip.startsWith("10.")) {
return "";
} else if (ip.startsWith("192.168.")) {
return "";
} else if (ip.startsWith("176") && (Integer.valueOf(ip.split(".")[1]) >= 16)
&& (Integer.valueOf(ip.split(".")[1]) <= 31)) {
return "";
} else {
return ip;
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* 获取wifi的mac地址
*
* @return
*/
// public static String getMacAddress() {
// try {
// WifiManager wifi = (WifiManager) BaseApplication.BaseApp.getInstance().getSystemService(Context.WIFI_SERVICE);
// WifiInfo info = wifi.getConnectionInfo();
// String mac = info.getMacAddress();
// if (null != mac) {
// return mac;
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// return "";
// }
/**
* 获得当前日期和时间 格式 yyyy-MM-dd HH:mm
*/
public static String getCurrentDateTimeNoSS() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
Locale.getDefault());
String current_time = sdf.format(date);
return current_time;
}
/**
* * String日期转换为Long
*
* @param ("MM/dd/yyyy HH:mm:ss")
* @param date("12/31/2013 21:08:00")
* @return * @throws ParseException
*/
public static Long getLongTime(String date) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dt = sdf.parse(date);
return dt.getTime();
}
/**
* * String日期转换为Long
*
* @param ("MM/dd/yyyy HH:mm")
* @param date("12/31/2013 21:08:00")
* @return * @throws ParseException
*/
public static Long getLongTime1(String date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dt = null;
try {
dt = sdf.parse(date);
return dt.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return 0L;
}
/**
* * String日期转换为Long
*
* @param ("HH:mm")
* @param date(21:08:00")
* @return * @throws ParseException
*/
public static Long getLongTime3(String date) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date dt = sdf.parse(date);
return dt.getTime();
}
/**
* 获得当前日期和时间 格式 yyyy-MM-dd HH:mm:ss
*/
public static String getCurrentDateTime() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
String current_time = sdf.format(date);
return current_time;
}
/**
* 获得当前年份
*/
public static int getYear() {
Calendar calendar=Calendar.getInstance();
return calendar.get(Calendar.YEAR);
}
/**
* 获取月,英文
* @return
*/
public static String getMonth(){
int month = Calendar.getInstance().get(Calendar.MONTH);
String monthStr = "01";
switch (month){
case 0:
monthStr = "January";
break;
case 1:
monthStr = "February";
break;
case 2:
monthStr = "March";
break;
case 3:
monthStr = "April";
break;
case 4:
monthStr = "May";
break;
case 5:
monthStr = "June";
break;
case 6:
monthStr = "July";
break;
case 7:
monthStr = "August";
break;
case 8:
monthStr = "September";
break;
case 9:
monthStr = "October";
break;
case 10:
monthStr = "November";
break;
case 11:
monthStr = "December";
break;
}
return monthStr;
}
public static String getDay(){
Calendar instance = Calendar.getInstance();
int i = instance.get(Calendar.DAY_OF_MONTH);
if (i>9){
return i+"";
}else {
return "0"+i;
}
}
/**
* 获得当前日期和时间 格式yyyy-MM-dd HH:mm:ss:SS
*/
public static String getCurrentDateTimeWithSS() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
String current_time = sdf.format(date);
return current_time;
}
/**
* 获得当前日期和时间 格式yyyy-MM-dd HH:mm:ss:
*/
public static String getCurrentDateTimeWithSSS() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss", Locale.getDefault());
String current_time = sdf.format(date);
return current_time;
}
/**
* 获得当前时间的年月日
*/
public static String getymd() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String current_time = sdf.format(date);
return current_time;
}
/**
* 获得当前时间
*/
public static String getCurrentTime() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.getDefault());
String current_time = sdf.format(date);
return current_time;
}
/**
* 获得当前时间
*/
public static String getCurrentTimeMM() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("mm", Locale.getDefault());
String current_time = sdf.format(date);
return current_time;
}
/**
* 返回当前时间,单位毫秒
*
* @return
*/
public static long getCurrentTimeMillis() {
return System.currentTimeMillis();
}
/**
* 获取时间 string 2 long
*
* @param date
* @return
*/
public static long getDateStringToLong(String date) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dt2 = sdf.parse(date);
//继续转换得到秒数的long型
long time = dt2.getTime();
return time;
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
/**
* 获取时间 string 2 long
*
* @param date
* @return
*/
public static long getDateToLong(String date) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date dt2 = sdf.parse(date);
//继续转换得到秒数的long型
long time = dt2.getTime();
return time;
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
/**
* 得到指定的日期
*
* @param date
* @return
*/
public static long getDateTimeStringToLong(String date) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dt2 = sdf.parse(date);
//继续转换得到秒数的long型
long time = dt2.getTime();
return time;
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
/**
* 获得当前日期
*/
public static String getCurrentDate() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String current_time = sdf.format(date);
return current_time;
}
/**
* 获得当前日期
*/
public static String getTodayate() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
String current_time = sdf.format(date);
return current_time;
}
public static boolean isAfterToday(String curDate) {
long curLong = getDateTimeStringToLong(curDate);
long todayLong = System.currentTimeMillis();
return curLong > todayLong;
}
/**
* 获取指定时间的字符
*
* @param time
* @return
*/
public static String getDateToSS(long time) {
Date date = new Date(time);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
String current_time = sdf.format(date);
return current_time;
}
/**
* 获取指定时间的字符
*
* @param time
* @return
*/
public static String getDateToMM(long time) {
Date date = new Date(time);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
String current_time = sdf.format(date);
return current_time;
}
/**
* 获取指定时间的字符
*
* @param time
* @return
*/
public static String getDate(long time) {
Date date = new Date(time);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String current_time = sdf.format(date);
return current_time;
}
/**
* 对时间进行处理
*
* @param time
* @return
*/
public static String timeLongToString(long time) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.getDefault());
Date dt = new Date(time * 1000l);
String sDateTime = sdf.format(dt); // 得到精确到秒的表示:08/31/2006 21:08:00
return sDateTime;
}
/**
* 2015-12-7T16:00:00.000Z 转换成毫秒值
* @param date
* @return
*/
public static String parseData(String date){
if (TextUtils.isEmpty(date)){
return "";
}
date = date.replace("Z", " UTC");//注意是空格+UTC
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");//注意格式化的表达式
try {
Date d = format.parse(date );
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String format1 = sdf.format(d);
return format1;
} catch (ParseException e) {
e.printStackTrace();
}
return "";
}
/**
* 时间补零
*
* @param c
* @return
*/
public static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
/**
* 获得天数
*/
public static int getDayNum(long millisTime) {
int day = (int) (millisTime / (1000 * 60 * 60 * 24));
if (millisTime % (1000 * 60 * 60 * 24) != 0) {
return day + 1;
}
return day;
}
public static int getHourNum(long millisTime) {
int day = (int) (millisTime / (1000 * 60 * 60));
if (millisTime % (1000 * 60 * 60) != 0) {
return day + 1;
}
return day;
}
/**
* @param startTime
* @param endTime
* @return
* @Description: 两个日期之间相差天数
*/
public static int getDayBetweenDay(long startTime, long endTime) {
int startDay = getDayNum(startTime);
int endDay = getDayNum(endTime);
return Math.abs(startDay - endDay);
}
/**
* @param startTime
* @param endTime
* @return
* @Description: 两个日期之间相差的小时数
*/
public static int getHourBetweenDay(long startTime, long endTime) {
int startDay = getHourNum(startTime);
int endDay = getHourNum(endTime);
return Math.abs(startDay - endDay);
}
/**
* @param startTime
* @param endTime
* @return
* @Description: 两个日期之间相差的小时数
*/
public static int getHourBetweenDay(Date startTime, Date endTime) {
int startDay = getHourNum(startTime.getTime());
int endDay = getHourNum(endTime.getTime());
return Math.abs(startDay - endDay);
}
/**
* 返回两次的时间差的显示方式
*
* @param startTime
* @param nowTime
* @return
*/
public static String showRuleTime(long startTime, long nowTime) {
String re = "";
long difftime = nowTime - startTime;
if (difftime < 0) {
re = "1秒前";
} else if (difftime < 60 * 1000) {
// 小于60s
re = difftime / 1000 + "秒前";
} else if (difftime < 60 * 60 * 1000) {
// 小于60min
re = (difftime / 1000) / 60 + "分钟前";
} else {
Date date_start = new Date(startTime);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String nowDay = formatter.format(new Date(nowTime));
String yesterDay = formatter.format(new Date(nowTime - 24 * 60 * 60 * 1000));
String startDay = formatter.format(date_start);
if (startDay.equals(nowDay)) {
SimpleDateFormat myFormatter = new SimpleDateFormat("HH:mm", Locale.getDefault());
re = "今天 " + myFormatter.format(date_start);
} else if (startDay.equals(yesterDay)) {
SimpleDateFormat myFormatter = new SimpleDateFormat("HH:mm", Locale.getDefault());
re = "昨天 " + myFormatter.format(date_start);
} else {
SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
re = myFormatter.format(date_start);
}
}
return re;
}
/**
* 判断两个更新时间差
*
* @param beforeTime 上一次的时间
* @param nowTime 本次的时间
* @param defaultDiff 需要的差距
* @return
*/
public static boolean dateDiff(String beforeTime, String nowTime, long defaultDiff) {
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Date date_before = formatter.parse(beforeTime);
Date date_after = formatter.parse(nowTime);
long now_time = date_after.getTime();
long before_time = date_before.getTime();
long diff = now_time - before_time;
if (diff - defaultDiff > 0) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 秒转分钟或小时字符串
*
* @param second 总秒数
* @param isKeepSeconds 是否保留秒
* @return
*/
public static String secondToMin(long second, boolean isKeepSeconds) {
String timeStr = 0 + "分";
try {
if (second > 0) {
int minute = (int) (second / 60);
int seconds = (int) (second % 60);
if (minute > 0) {
if (seconds > 0) {
if (isKeepSeconds) {
if (seconds < 10) {
timeStr = minute + "分0" + seconds + "秒";
} else {
timeStr = minute + "分" + seconds + "秒";
}
} else {
if (seconds >= 30) {// 超过30秒+1分钟
timeStr = (minute + 1) + "分";
} else {// 不足30秒忽略掉
timeStr = minute + "分";
}
}
} else {
timeStr = minute + "分" + "00秒";
}
} else {
timeStr = seconds + "秒";
}
}
} catch (Exception e) {
e.printStackTrace();
}
return timeStr;
}
/**
* 秒转分钟或小时字符串,格式01:23:45
*
* @param second 总秒数
* @param isKeepSeconds 是否保留秒
* @return
*/
public static String secondToMin2(long second, boolean isKeepSeconds) {
String timeStr = "00:00";
try {
if (second > 0) {
int hour = (int)(second/3600);
int minute = (int) (second %3600 / 60);
int seconds = (int) (second %3600 % 60);
if (hour >0){
if ( hour >=10){
timeStr = hour+":";
}else {
timeStr = "0"+hour+":";
}
if (minute >= 10){
timeStr += minute+":";
if (seconds >= 10){
timeStr += seconds;
}else if (seconds > 0){
timeStr += "0"+seconds;
}else {
timeStr +="00";
}
}else if (minute > 0){
timeStr += "0"+minute+":";
if (seconds >= 10){
timeStr += seconds;
}else if (seconds > 0){
timeStr += "0"+seconds;
}else {
timeStr +="00";
}
}else {
timeStr += "00:";
if (seconds >= 10){
timeStr += seconds;
}else if (seconds > 0){
timeStr += "0"+seconds;
}else {
timeStr +="00";
}
}
}else {
if (minute >= 10){
timeStr = minute+":";
if (seconds >= 10){
timeStr += seconds;
}else if (seconds > 0){
timeStr += "0"+seconds;
}else {
timeStr +="00";
}
}else if (minute > 0){
timeStr = "0"+minute+":";
if (seconds >= 10){
timeStr += seconds;
}else if (seconds > 0){
timeStr += "0"+seconds;
}else {
timeStr +="00";
}
}else {
timeStr = "00:";
if (seconds >= 10){
timeStr += seconds;
}else if (seconds > 0){
timeStr += "0"+seconds;
}else {
timeStr +="00";
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return timeStr;
}
/**
* 添加桌面快捷方式
*
* @param activity
* @param icon 点击图标启动intent
* @param icon 桌面icon
*/
public static void addShortcut(Activity activity, int icon, Activity start) {
Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
// 快捷方式的名称
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, activity.getString(R.string.app_name));
shortcut.putExtra("duplicate", false); // 不允许重复创建
// 指定当前的Activity为快捷方式启动的对象: 如 com.everest.video.VideoPlayer
// 注意: ComponentName的第二个参数必须加上点号(.),否则快捷方式无法启动相应程序
// ComponentName comp = new ComponentName(activity.getPackageName(),
// "."+activity.getLocalClassName());
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(activity, start.getClass())
.setAction(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER));
// shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
// 快捷方式的图标
ShortcutIconResource iconRes = ShortcutIconResource.fromContext(activity, icon);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
activity.sendBroadcast(shortcut);
}
/**
* 限制特殊字符 密码输入等处需要做判断
*/
public static boolean limitSpecialCharacters(String str) {
String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、? ]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
return !m.replaceAll("").equalsIgnoreCase(str);
}
/**
* 读取图片资源
*
* @param resId 上下文
* @param resId 资源id
* @return
*/
public static Bitmap readBitmap(int resId) {
InputStream stream = null;
try {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Config.ARGB_8888;
opt.inPurgeable = true;
opt.inInputShareable = true;
stream = BaseApp.getInstance().getResources().openRawResource(resId);
return BitmapFactory.decodeStream(stream, null, opt);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stream != null) {
stream.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
return null;
}
/**
* 图片的不等比缩放
*
* @param src 源图片
* @param destWidth 缩放的宽度
* @param destHeigth 缩放的高度
* @return
*/
public static Bitmap lessenBitmap(Bitmap src, int destWidth, int destHeigth) {
try {
if (src == null)
return null;
int w = src.getWidth();// 源文件的大小
int h = src.getHeight();
float scaleWidth = ((float) destWidth) / w;// 宽度缩小比例
float scaleHeight = ((float) destHeigth) / h;// 高度缩小比例
Matrix m = new Matrix();// 矩阵
m.postScale(scaleWidth, scaleHeight);// 设置矩阵比例
Bitmap resizedBitmap = Bitmap.createBitmap(src, 0, 0, w, h, m, true);// 直接按照矩阵的比例把源文件画入进行
return resizedBitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 等比缩放图片
*
* @param src
* @param targetWidth
* @param targetHeight
* @return
*/
public static Bitmap isometricScaleBitmap(Bitmap src, int targetWidth, int targetHeight) {
if (src != null) {
int width = src.getWidth();
int height = src.getHeight();
if (width * targetHeight > targetWidth * height) {
targetHeight = targetWidth * height / width;
} else if (width * targetHeight < targetWidth * height) {
targetWidth = targetHeight * width / height;
}
float scaleWidth = ((float) targetWidth) / width;// 宽度缩小比例
float scaleHeight = ((float) targetHeight) / height;// 高度缩小比例
Matrix m = new Matrix();// 矩阵
m.postScale(scaleWidth, scaleHeight);// 设置矩阵比例
Bitmap resizedBitmap = Bitmap.createBitmap(src, 0, 0, width, height, m, true);// 直接按照矩阵的比例把源文件画入进行
return resizedBitmap;
}
return null;
}
/**
* 从指定路径读取图片(原图读取 不会改变大小)
*
* @param imagePath
* @return
*/
public static Bitmap readBitmapFormPath(String imagePath) {
if (TextUtils.isEmpty(imagePath)) {
return null;
}
try {
Bitmap bitmap = null;
File file = new File(imagePath);
if (file.exists()) {
bitmap = BitmapFactory.decodeFile(imagePath);
}
return bitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 从sdcard或data文件夹读取图片(会在原图基础上进行压缩)
*
* @param imagePath
* @return
*/
public static Bitmap createBitmapFormSdcardOrData(String imagePath) {
if (null == imagePath) {
return null;
}
InputStream stream = null;
try {
File file = new File(imagePath);
if (!file.exists())
return null;
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(imagePath), null, o);
final int REQUIRED_SIZE = 100;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale++;
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(imagePath), null, o2);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stream != null) {
stream.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
return null;
}
/**
* 从sdcard或data文件夹读取图片
*
* @param imagePath
* @return
*/
public static Bitmap createBitmapFormSdcardOrData(String imagePath, int height, int width) {
if (null == imagePath) {
return null;
}
InputStream stream = null;
try {
File file = new File(imagePath);
if (!file.exists() && !file.canRead() && !file.isFile())
return null;
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(imagePath), null, o);
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (width_tmp / scale > width && height_tmp / scale > height) {
width_tmp /= 2;
height_tmp /= 2;
scale++;
}
o.inJustDecodeBounds = false;
o.inSampleSize = scale;
Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(imagePath), null, o);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stream != null) {
stream.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
return null;
}
/**
* 图片圆角处理
*
* @param bitmap 源图片
* @param roundPx 圆角角度
* @return
*/
public static Bitmap getRoundBitmap(Bitmap bitmap, int roundPx) {
return getRoundBitmap(bitmap, roundPx, 1.0f, 1.0f);
}
/**
* 图片圆角处理
*
* @param bitmap 源图片
* @param roundPx 圆角角度
* @param widthScale 处理后的图片宽与原图宽比例 不需要改变宽度直接传1.0f
* @param heightScale 处理后的图片高度与原图高度比例 不需要改变高度直接传1.0f
* @return
*/
public static Bitmap getRoundBitmap(Bitmap bitmap, int roundPx, float widthScale, float heightScale) {
Bitmap roundBitmap = null;
try {
roundBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(roundBitmap);
final int color = 0xff424242;
final Paint paint = new Paint();
paint.setAntiAlias(true);
int width = (int) (bitmap.getWidth() * widthScale);
int height = (int) (bitmap.getHeight() * heightScale);
final Rect rect = new Rect(0, 0, width, height);
final RectF rectF = new RectF(rect);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
} catch (Exception e) {
e.printStackTrace();
roundBitmap = bitmap;
}
return roundBitmap;
}
/**
* 从assets文件夹读取图片
*
* @param imagePath
* @return
*/
public static Bitmap createBitmapFormAssets(String imagePath) {
InputStream stream = null;
try {
if (imagePath != null) {
stream = BaseApp.getInstance().getAssets().open(imagePath);
}
if (stream != null) {
return Bitmap.createBitmap(BitmapFactory.decodeStream(stream));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stream != null) {
stream.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
return null;
}
/**
* 获取详细地址
*
* @param location
* @return
*/
public static String getAddress(Location location) {
try {
if (location != null) {
Geocoder geo = new Geocoder(BaseApp.getInstance(), Locale.getDefault());
List<Address> addresses = geo.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (!addresses.isEmpty()) {
if (addresses.size() > 0) {
Address address = addresses.get(0);
String addressName = address.getAddressLine(0);
if (addressName == null || addressName.length() <= 3) {
addressName = address.getLocality();
}
return addressName;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return "定位失败";
}
/**
* 获取城市名
*
* @param location
* @return
*/
public static String getCurrentCity(Location location) {
try {
if (location != null) {
Geocoder geo = new Geocoder(BaseApp.getInstance(), Locale.getDefault());
List<Address> addresses = geo.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (!addresses.isEmpty()) {
if (addresses.size() > 0) {
Address address = addresses.get(0);
String addressName = address.getLocality();
return addressName;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return "北京";
}
/**
* 获得手机型号
*
* @return
*/
public static String getPhoneModel() {
try {
String phoneVersion = Build.MODEL;
if (null != phoneVersion) {
return phoneVersion;
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* 调用系统短信
* <p/>
* Activity自身
*
* @param body 信息内容
*/
public static void sendSms(Activity activity, String phoneNumber, String body) {
try {
Uri smsToUri = Uri.parse("smsto:" + phoneNumber);// 联系人地址
Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
intent.putExtra("address", phoneNumber);
intent.putExtra("sms_body", body);// 短信的内容
activity.startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 调用系统电话
*
* @param activity
* @param phoneNum
*/
public static void openSystemPhone(Activity activity, String phoneNum) {
try {
Intent it = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNum));
activity.startActivity(it);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 调用系统浏览器
*
* @param activity
* @param url
*/
public static void openSystemBrowser(Activity activity, String url) {
try {
Intent it = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
activity.startActivity(it);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 调用系统网络设置
*
* @param activity
*/
public static void openSystemNetworkSetting(Activity activity) {
try {
Intent i = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(i);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 调用系统地图
*
* @param activity
*/
public static void openSystemMap(Activity activity, String latitude, String longitude) {
try {
Uri mUri = Uri.parse("geo:" + latitude + "," + longitude);
Intent mIntent = new Intent(Intent.ACTION_VIEW, mUri);
activity.startActivity(mIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获得屏幕的宽度
*
* @return int
*/
public static int getScreenWidth() {
DisplayMetrics dm = new DisplayMetrics();
dm = BaseApp.getInstance().getApplicationContext().getResources().getDisplayMetrics();
return dm.widthPixels;
}
/**
* 获得屏幕的高度
*
* @return int
*/
public static int getScreenHeight() {
DisplayMetrics dm = new DisplayMetrics();
dm = BaseApp.getInstance().getResources().getDisplayMetrics();
return dm.heightPixels;
}
/**
* 获取使用内存大小
*/
public static int getMemory() {
int pss = 0;
ActivityManager myAM = (ActivityManager) BaseApp.getInstance()
.getSystemService(Context.ACTIVITY_SERVICE);
String packageName = BaseApp.getInstance().getPackageName();
List<RunningAppProcessInfo> appProcesses = myAM.getRunningAppProcesses();
for (RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.processName.equals(packageName)) {
int pids[] = {appProcess.pid};
Debug.MemoryInfo self_mi[] = myAM.getProcessMemoryInfo(pids);
pss = self_mi[0].getTotalPss();
}
}
return pss;
}
/**
* 获得CPU使用率
*/
public static int getCpuInfo() {
int cpu = 0;
try {
RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
String load = reader.readLine();
String[] toks = load.split(" ");
long idle1 = Long.parseLong(toks[5]);
long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
+ Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
reader.seek(0);
load = reader.readLine();
reader.close();
toks = load.split(" ");
long idle2 = Long.parseLong(toks[5]);
long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
+ Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
cpu = (int) (100 * (cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1)));
} catch (IOException ex) {
ex.printStackTrace();
}
return cpu;
}
/**
* 获得手机IMEI
*
* @return
*/
public static String getIMEI() {
try {
TelephonyManager tm = (TelephonyManager) BaseApp.getInstance()
.getSystemService(Context.TELEPHONY_SERVICE);
@SuppressLint("MissingPermission") String imei = tm.getDeviceId();
if (null != imei) {
return imei;
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* 获得手机IMSI
*
* @return
*/
public static String getIMSI() {
try {
TelephonyManager tm = (TelephonyManager) BaseApp.getInstance()
.getSystemService(Context.TELEPHONY_SERVICE);
@SuppressLint("MissingPermission") String imsi = tm.getSubscriberId();
if (null != imsi) {
return imsi;
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* 得到系统亮度
*
* @return
*/
public static int getSystemBrightness() {
int brightness = 5;
try {
brightness = Settings.System.getInt(BaseApp.getInstance().getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS);
brightness = brightness * 100 / 255;
} catch (SettingNotFoundException ex) {
ex.printStackTrace();
}
return brightness >= 5 ? brightness : 5;
}
网友评论