package com.fwupgrade.saymanss.utils;
|
|
import android.annotation.SuppressLint;
|
import android.annotation.TargetApi;
|
import android.app.Activity;
|
import android.app.ActivityManager;
|
import android.content.ComponentName;
|
import android.content.Context;
|
import android.content.Intent;
|
import android.content.pm.PackageInfo;
|
import android.content.pm.PackageManager;
|
import android.content.res.Resources;
|
import android.graphics.Bitmap;
|
import android.graphics.BitmapFactory;
|
import android.hardware.Camera;
|
import android.media.MediaMetadataRetriever;
|
import android.os.Build;
|
import android.os.Environment;
|
import android.os.IBinder;
|
import android.os.StatFs;
|
import android.provider.Settings;
|
import android.text.InputType;
|
import android.text.Selection;
|
import android.text.Spannable;
|
import android.text.TextUtils;
|
import android.view.Window;
|
import android.view.WindowManager;
|
import android.view.inputmethod.InputMethodManager;
|
import android.widget.EditText;
|
import android.widget.Toast;
|
|
import java.io.ByteArrayOutputStream;
|
import java.io.File;
|
import java.io.FileInputStream;
|
import java.io.FileOutputStream;
|
import java.io.InputStream;
|
import java.io.UnsupportedEncodingException;
|
import java.lang.reflect.Field;
|
import java.lang.reflect.InvocationTargetException;
|
import java.lang.reflect.Method;
|
import java.math.BigDecimal;
|
import java.net.URLDecoder;
|
import java.net.URLEncoder;
|
import java.security.MessageDigest;
|
import java.security.NoSuchAlgorithmException;
|
import java.text.DecimalFormat;
|
import java.text.ParseException;
|
import java.text.SimpleDateFormat;
|
import java.util.Collections;
|
import java.util.Comparator;
|
import java.util.Date;
|
import java.util.List;
|
import java.util.Locale;
|
import java.util.TimeZone;
|
import java.util.Timer;
|
import java.util.TimerTask;
|
import java.util.concurrent.atomic.AtomicInteger;
|
|
import javax.crypto.Cipher;
|
import javax.crypto.spec.IvParameterSpec;
|
import javax.crypto.spec.SecretKeySpec;
|
|
|
/**
|
* 工具类,大家在这个工具类中添加方法的时候请注意分类,
|
*/
|
@SuppressLint("SimpleDateFormat")
|
public class UtilTools {
|
|
/**************************************** android系统设备获取信息相关类 *****************************************/
|
|
/**
|
* 获取手机型号
|
* @author Snow
|
* @date 2014-4-10
|
* @return
|
*/
|
public static String getPhoneModel() {
|
return Build.MODEL;
|
}
|
|
/**
|
* 得到android的id
|
* @author Snow
|
* @date 2014-4-10
|
* @param mContext
|
* @return
|
*/
|
public static String getAndroidID(Context mContext) {
|
String androidId = Settings.Secure.getString(
|
mContext.getContentResolver(), Settings.Secure.ANDROID_ID);
|
return androidId;
|
}
|
|
/**
|
* 判断是否为飞行模式
|
* @param context
|
* @return
|
*/
|
@SuppressWarnings("deprecation")
|
public static boolean isAirplaneModeOn(Context context) {
|
return Settings.System.getInt(context.getContentResolver(),
|
Settings.System.AIRPLANE_MODE_ON, 0) != 0;
|
}
|
|
|
/**************************************** 文件相关类 *****************************************/
|
/**
|
* 截取文件类型,如"爱笑的眼睛.mp3",调用这个方法,则返回"mp3";
|
*
|
* @param name : 文件名称 ,如: "爱笑的眼睛.mp3"
|
*
|
* @return 返回文件的类型,如 : mp3
|
*/
|
public static String getFileTypeFromName(String name) {
|
String prefix = name.substring(name.lastIndexOf(".") + 1);
|
return prefix;
|
}
|
|
/**
|
* 截取文件类型,如"爱笑的眼睛.mp3",调用这个方法,则返回"mp3";
|
*
|
* @param name : 文件名称 ,如: "爱笑的眼睛.mp3"
|
*
|
* @return 返回文件的类型,如 : .mp3
|
*/
|
public static String getFilePrefixLength(String name) {
|
if(name == null || !name.contains(".")){
|
return name;
|
}
|
String prefix = name.substring(0, name.lastIndexOf("."));
|
return prefix;
|
}
|
|
/**
|
* 截取文件类型,如"爱笑的眼睛.mp3",调用这个方法,则返回"mp3";
|
*
|
* @param name : 文件名称 ,如: "爱笑的眼睛.mp3"
|
*
|
* @return 返回文件的类型,如 : .mp3
|
*/
|
public static String getFileSuffix(String name) {
|
if(name == null || !name.contains(".")){
|
return "";
|
}
|
String prefix = name.substring(name.lastIndexOf("."));
|
return prefix;
|
}
|
|
/**
|
* 创建文件
|
* @param createdir
|
* @return
|
*/
|
public static String createFolderPath(String createdir) {
|
final File downfolder = new File(createdir);
|
if (!downfolder.exists()) {
|
downfolder.mkdirs();
|
}
|
return createdir;
|
}
|
|
/**
|
* 创建文件
|
*/
|
public static boolean createFileInfSdcard(String createFile) {
|
final String status = Environment.getExternalStorageState();
|
if (!status.equals(Environment.MEDIA_MOUNTED)) return false;
|
|
boolean isCreateSu = false;
|
File downfile = new File(createFile);
|
if (!downfile.exists()) {
|
try {
|
isCreateSu = downfile.createNewFile();
|
} catch(Exception e) {
|
isCreateSu = false;
|
}
|
} else {
|
isCreateSu = false;
|
}
|
return isCreateSu;
|
}
|
|
/**
|
* 创建本地文件夹
|
*
|
* @param createdir
|
*
|
* @return
|
*/
|
public static boolean createFolderInSdcard(String createdir) {
|
String status = Environment.getExternalStorageState();
|
if (!status.equals(Environment.MEDIA_MOUNTED)) return false;
|
|
boolean isCreateSu = false;
|
File downfolder = new File(createdir);
|
if (!downfolder.exists()) {
|
downfolder.mkdirs();
|
isCreateSu = true;
|
} else {
|
isCreateSu = false;
|
}
|
return isCreateSu;
|
}
|
|
/**
|
* 从路径中获取文件名称.
|
* @param filePath
|
* @return
|
*/
|
public static String getFileName(String filePath) {
|
|
int idx = filePath.lastIndexOf("/");
|
filePath = filePath.substring(idx + 1, filePath.length());
|
return filePath;
|
|
}
|
|
/**
|
* 去掉文件名得到为文件所在的目录
|
* @param fileAllpath
|
* @return
|
*/
|
public static String getFilePath(String fileAllpath) {
|
if (fileAllpath == null) {
|
return null;
|
}
|
int idx = fileAllpath.lastIndexOf("/");
|
if (idx == -1) {
|
return null;
|
}
|
String filepath = fileAllpath.substring(0, idx);
|
return filepath;
|
}
|
|
/**
|
* 将默认的SDCard路径转换为/mnt/sdcard路径
|
* @param path
|
* @return
|
*/
|
public static String changeDefSDCardToMnt(String path) {
|
String defaultSDCard = Environment.getExternalStorageDirectory().toString();
|
|
if(path.startsWith(defaultSDCard)) {
|
String sdcard = AppPathInfo.app_sdcard;
|
String newPath = path.replace(defaultSDCard, sdcard);
|
return newPath;
|
} else {
|
return path;
|
}
|
}
|
|
/**
|
* 文件集合列表排序
|
* @param files
|
*/
|
public static void do_sort(List<File> files) {
|
if(!files.isEmpty()) {
|
Collections.sort(files, new Comparator<File>() {
|
@Override
|
public int compare(File object1, File object2) {
|
return (object1.getPath().substring(object1.getPath().lastIndexOf("/")).toLowerCase(Locale.getDefault()))
|
.compareTo((String) object2.getPath().substring(object1.getPath().lastIndexOf("/")).toLowerCase(Locale.getDefault()));
|
}
|
|
});
|
}
|
}
|
|
|
/**
|
* 删除路径中的最后一个组成部分,即"/"后的部分
|
*
|
* @param path 传入的路径参数
|
* @return 返回"/"之前的字符串
|
*/
|
public static String deleteFileNameFromPath(String path) {
|
int idx = path.lastIndexOf("/");
|
if(idx == -1){
|
return null;
|
}
|
String filePath = "";
|
filePath = path.substring(0, idx);
|
return filePath;
|
}
|
|
|
/**************************************** 字符串转码相关类 *****************************************/
|
/**
|
* UTF8编码转URL编码.
|
* @param urlStr
|
* @return
|
*/
|
public static String getUTF8CodeInfoFromURL(String urlStr) {
|
try {
|
StringBuffer sbuf = new StringBuffer();
|
int l = urlStr.length();
|
int ch = -1;
|
int b, sumb = 0;
|
int hb,lb;
|
int flag1 = 0;
|
for (int i = 0, more = -1; i < l; i++) {
|
/* Get next byte b from URL segment s */
|
switch (ch = urlStr.charAt(i)) {
|
case '%':
|
if(i >= l-2)
|
return urlStr;
|
ch = urlStr.charAt(++i);
|
if((ch >= 'a' && ch <='f') || (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F')) {
|
hb = (Character.isDigit((char) ch) ? ch - '0'
|
: 10 + Character.toLowerCase((char) ch) - 'a') & 0xF;
|
}else{
|
return urlStr;
|
}
|
ch = urlStr.charAt(++i);
|
if((ch >= 'a' && ch <='f') || (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F')) {
|
lb = (Character.isDigit((char) ch) ? ch - '0'
|
: 10 + Character.toLowerCase((char) ch) - 'a') & 0xF;
|
}else{
|
return urlStr;
|
}
|
b = (hb << 4) | lb;
|
flag1 = 1;
|
break;
|
default:
|
b = ch;
|
flag1 = 0;
|
}
|
if(flag1 == 0) {
|
sbuf.append((char) b);
|
continue;
|
}
|
/* Decode byte b as UTF-8, sumb collects incomplete chars */
|
if ((b & 0xc0) == 0x80) { // 10xxxxxx (continuation byte)
|
sumb = (sumb << 6) | (b & 0x3f); // Add 6 bits to sumb
|
if (--more == 0)
|
sbuf.append((char) sumb); // Add char to sbuf
|
} else if ((b & 0x80) == 0x00) { // 0xxxxxxx (yields 7 bits)
|
sbuf.append((char) b); // Store in sbuf
|
} else if ((b & 0xe0) == 0xc0) { // 110xxxxx (yields 5 bits)
|
sumb = b & 0x1f;
|
more = 1; // Expect 1 more byte
|
} else if ((b & 0xf0) == 0xe0) { // 1110xxxx (yields 4 bits)
|
sumb = b & 0x0f;
|
more = 2; // Expect 2 more bytes
|
} else if ((b & 0xf8) == 0xf0) { // 11110xxx (yields 3 bits)
|
sumb = b & 0x07;
|
more = 3; // Expect 3 more bytes
|
} else if ((b & 0xfc) == 0xf8) { // 111110xx (yields 2 bits)
|
sumb = b & 0x03;
|
more = 4; // Expect 4 more bytes
|
} else /*if ((b & 0xfe) == 0xfc)*/{ // 1111110x (yields 1 bit)
|
sumb = b & 0x01;
|
more = 5; // Expect 5 more bytes
|
}
|
/* We don't test if the UTF-8 encoding is well-formed */
|
}
|
return sbuf.toString();
|
} catch (Exception e) {
|
e.printStackTrace();
|
return urlStr;
|
}
|
}
|
|
/**
|
* 把String进行UTF-8编码.
|
* @param utf8Str
|
* @return
|
*/
|
public static String getURLCodeInfoFromUTF8(String utf8Str) {
|
try {
|
StringBuffer sb = new StringBuffer();
|
for (int i = 0; i < utf8Str.length(); i++) {
|
char c = utf8Str.charAt(i);
|
char begin;
|
if (c >= 0 && c <= 127) {
|
if((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z')
|
|| (c >= 'A' && c <= 'Z')
|
|| (c == '/')
|
|| (c == '.')
|
|| (c == '_')
|
|| (c == '-')) {
|
sb.append(c);
|
}else{
|
sb.append("%" + Integer.toHexString((c)&0xFF).toUpperCase());
|
}
|
} else {
|
byte[] b;
|
try {
|
b = String.valueOf(c).getBytes("utf-8");
|
} catch (Exception ex) {
|
System.out.println(ex);
|
b = new byte[0];
|
}
|
for (int j = 0; j < b.length; j++) {
|
int k = b[j];
|
if (k < 0)
|
k += 256;
|
sb.append("%" + Integer.toHexString(k).toUpperCase());
|
}
|
}
|
}
|
return sb.toString();
|
} catch (Exception e) {
|
e.printStackTrace();
|
return utf8Str;
|
}
|
}
|
|
/**
|
* 替换特殊字符,将strFind字符串替换为strInstead
|
* @param strText 目标字符串
|
* @param strFind 需要转换的字符
|
* @param strInstead 转换成需要的字符
|
* @return 返回转换之后的字符
|
*/
|
public static String replaceSpecialStingFormString(String strText, String strFind, String strInstead) {
|
|
if ((strText == null) || (strFind == null) || (strInstead == null))
|
return null;
|
|
String strTempFront = null;
|
String strTempBehind = null;
|
int length = strFind.length();
|
|
//循环查找,替换
|
int index = strText.indexOf(strFind);
|
while (index != -1) {
|
strTempFront = strText.substring(0, index);
|
strTempBehind = strText.substring(index + length);
|
strText = strTempFront + strInstead + strTempBehind;
|
|
//继续下一次查找
|
index = strText.indexOf(strFind);
|
}
|
|
return strText;
|
}
|
|
/**
|
* 将 "%2F"字符 转换为 "/" 字符。
|
* @param urlStr 需要转换的字符串
|
* @return 返回已经修改了的字符串
|
*/
|
public static String getURLCodeInfoForSpecialChar(String urlStr) {
|
//替换掉%2F为/特殊字符
|
urlStr = replaceSpecialStingFormString(urlStr, "%2F", "/");
|
return urlStr;
|
}
|
|
/**
|
* 将utf-8编码的字符转换为string
|
* @param utf8Str
|
* @return 如果成功转码则返回转码后的内容, 如果转码失败则返回原来的内容.
|
*/
|
public static String getInfoUTF8toStr(String utf8Str) {
|
String info;
|
try {
|
info = URLDecoder.decode(utf8Str, "UTF-8");
|
} catch (Exception e) {
|
info = utf8Str;
|
}
|
return info;
|
}
|
|
/**
|
* 去掉字符串中的%20
|
*/
|
public static String strSpaceConversionTo20(String ufilename) {
|
String strSC = "";
|
strSC = ufilename.replace(" ", "%20");
|
return strSC;
|
}
|
|
/** 16进制数字字符集 */
|
private static String hexString="0123456789ABCDEF";
|
/**
|
* 将字符串编码成16进制数字,适用于所有字符(包括中文)
|
*/
|
public static String encode(String str) {
|
//根据默认编码获取字节数组
|
byte[] bytes=str.getBytes();
|
StringBuilder sb=new StringBuilder(bytes.length*2);
|
//将字节数组中每个字节拆解成2位16进制整数
|
for(int i=0;i<bytes.length;i++) {
|
sb.append(hexString.charAt((bytes[i]&0xf0)>>4));
|
sb.append(hexString.charAt((bytes[i]&0x0f)>>0));
|
}
|
return sb.toString();
|
}
|
|
/**
|
* 将16进制数字解码成字符串,适用于所有字符(包括中文)
|
*/
|
public static String decode(String bytes) {
|
ByteArrayOutputStream baos=new ByteArrayOutputStream(bytes.length()/2);
|
//将每2位16进制整数组装成一个字节
|
for(int i=0;i<bytes.length();i+=2) {
|
baos.write((hexString.indexOf(bytes.charAt(i))<<4 | hexString.indexOf(bytes.charAt(i+1))));
|
}
|
return new String(baos.toByteArray());
|
}
|
|
/**************************************** 时间相关类 *****************************************/
|
|
public static final String[] months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
|
|
/**
|
* 设置时间格式
|
* @param file
|
* @return
|
*/
|
public static String getFileLastModifiedTime(File file) {
|
long modifiedTime = file.lastModified();
|
Date date = new Date(modifiedTime);
|
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
|
String dd = sdf.format(date);
|
return dd;
|
}
|
|
/**
|
* 设置时间格式
|
*/
|
public static String getTimeFromLong(long modifiedTime) {
|
Date date = new Date(modifiedTime);
|
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
|
String dd = sdf.format(date);
|
return dd;
|
}
|
|
/**
|
* 设置时间格式
|
*/
|
public static String getMsecTimeFromLong(long modifiedTime) {
|
Date date = new Date(modifiedTime);
|
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS", Locale.getDefault());
|
String dd = sdf.format(date);
|
return dd;
|
}
|
|
/**
|
* 截取时间标签
|
* @param time
|
* @return
|
*/
|
public static String getTimeTag(String time) {
|
if(time.contains("T")) {
|
int index = time.indexOf("T");
|
String timeTag = time.substring(0,index);
|
return timeTag;
|
}else if(time.contains(" ")) {
|
int index = time.indexOf(" ");
|
String timeTag = time.substring(0,index);
|
return timeTag;
|
}else {
|
return time;
|
}
|
}
|
|
/**
|
* 修改获取的时间的显示方式
|
* 获取到的时间显示方式:Fri, 06 Dec 2013 06:05:45 GMT
|
* 修改为:2013/12/06 06:05:45
|
* @author Wangcan
|
*/
|
public static String modifyTimeShowStyle(String time) {
|
String timeShowStyle = "";
|
String[] times = time.split(" ");
|
|
if(times.length == 2) {
|
//显示为 2014-12-06 06:05:45
|
timeShowStyle = time.replace("-", "/");
|
} else if(times.length == 6){
|
String createDay = times[1];
|
String createMonth = times[2];
|
String createYear = times[3];
|
String createTime = times[4];
|
|
int i=0;
|
for(; i<months.length; i++) {
|
if(createMonth.equals(months[i])) {
|
break;
|
}
|
}
|
|
String createMonthNew = "";
|
if(i < 10) {
|
createMonthNew = "0" + (i + 1);
|
} else {
|
createMonthNew = Integer.toString(i);
|
}
|
|
//日期为单个字符,前面加0
|
if(createDay.length() == 1) {
|
createDay += "0";
|
}
|
|
timeShowStyle = createYear + "/"
|
+ createMonthNew + "/"
|
+ createDay + " "
|
+ createTime;
|
} else {
|
timeShowStyle = time;
|
}
|
|
return timeShowStyle;
|
}
|
|
/**
|
* 转化格林时间
|
* @param formatDate
|
* @return
|
*/
|
@SuppressWarnings({ "deprecation", "finally" })
|
public static String formatGMTDate(String formatDate) {
|
String date = formatDate;
|
try {
|
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
|
date = sdf.format(new Date(formatDate));
|
|
} catch (Exception e) {
|
} finally {
|
return date;
|
}
|
}
|
|
/**
|
* 转化时间
|
* @param time
|
* @return
|
*/
|
public static long getPaserTime(String time) {
|
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
try {
|
return sdf.parse(time).getTime();
|
} catch (ParseException e) {
|
e.printStackTrace();
|
return 0;
|
}
|
}
|
|
|
/**************************************** MD5值转换相关类 *****************************************/
|
/**
|
* 将key路径的文件转换为MD5值
|
* @param key
|
* @return
|
*/
|
public static String cachePathMD5ValueForKey(String key) {
|
if (key == null || key.length() == 0) {
|
throw new IllegalArgumentException( "String to encript cannot be null or zero length");
|
}
|
|
StringBuffer hexString = new StringBuffer();
|
|
try {
|
MessageDigest md = MessageDigest.getInstance("MD5");
|
md.update(key.getBytes());
|
byte[] hash = md.digest();
|
|
for (int i = 0; i < hash.length; i++) {
|
if ((0xff & hash[i]) < 0x10) {
|
hexString.append("0"
|
+ Integer.toHexString((0xFF & hash[i])));
|
} else {
|
hexString.append(Integer.toHexString(0xFF & hash[i]));
|
}
|
}
|
} catch (NoSuchAlgorithmException e) {
|
}
|
|
return hexString.toString();
|
}
|
|
/**************************************** sdcard的空间大小相关类 *****************************************/
|
/**
|
* 获得card的可用空间大小
|
* @param path
|
* @return
|
*/
|
@SuppressWarnings("deprecation")
|
static public long getCardMemorySize(String path) {
|
StatFs stat = new StatFs(path);
|
// StatFs stat = new StatFs(UtilTools.getInfoUTF8toStr(path));
|
long blockSize = stat.getBlockSize();
|
long availableBlocks = stat.getAvailableBlocks();
|
return availableBlocks * blockSize;
|
}
|
|
/**
|
* 转换文件大小(MB、GB...).
|
* @param fileSize
|
* @return
|
*/
|
public static String FormetFileSize(String fileSize) {
|
DecimalFormat df = new DecimalFormat("#.0");
|
long fileS = 0;
|
if (fileSize.equals("")) {
|
fileS = 0;
|
} else {
|
fileS = Long.parseLong(fileSize);
|
}
|
String fileSizeString = "";
|
if (fileS < 1024) {
|
fileSizeString = df.format((double) fileS) + "B";
|
} else if (fileS < 1048576) {
|
fileSizeString = df.format((double) fileS / 1024) + "KB";
|
} else if (fileS < 1073741824) {
|
fileSizeString = df.format((double) fileS / 1048576) + "MB";
|
} else{
|
fileSizeString = df.format((double) fileS / 1073741824) + "GB";
|
}
|
|
if(fileSizeString.startsWith(".")) {
|
fileSizeString = "0" + fileSizeString;
|
}
|
|
return fileSizeString;
|
}
|
|
/**
|
* 获取文件类型
|
*/
|
public static String getFileType(String fileDevPath) {
|
int start = fileDevPath.lastIndexOf(".");
|
if (start < 0) {
|
return null;
|
}
|
int end = fileDevPath.length();
|
return fileDevPath.substring(start, end);
|
}
|
|
/**
|
* 获取存储路径
|
* @return
|
*/
|
public static String getExternalStoragePath() {
|
// 获取SdCard状态
|
String state = Environment.getExternalStorageState();
|
// 判断SdCard是否存在并且是可用的
|
if (Environment.MEDIA_MOUNTED.equals(state)) {
|
if (Environment.getExternalStorageDirectory().canWrite()) {
|
return Environment.getExternalStorageDirectory()
|
.getPath();
|
}
|
}
|
return null;
|
}
|
|
/**
|
* 获取指定路径文件剩余容量.
|
* @param filePath
|
* @return
|
*/
|
@SuppressWarnings("deprecation")
|
public static long getAvailableStore(String filePath) {
|
// 取得sdcard文件路径
|
StatFs statFs = new StatFs(filePath);
|
// 获取block的SIZE
|
long blocSize = statFs.getBlockSize();
|
// 获取BLOCK数量
|
// long totalBlocks = statFs.getBlockCount();
|
// 可使用的Block的数量
|
long availaBlock = statFs.getAvailableBlocks();
|
// long total = totalBlocks * blocSize;
|
long availableSpare = availaBlock * blocSize;
|
return availableSpare;
|
}
|
|
public static String getFileTypeWithNoNod(String fileDevPath) {
|
int start = fileDevPath.lastIndexOf(".");
|
if (start < 0) {
|
return null;
|
}
|
int end = fileDevPath.length();
|
return fileDevPath.substring(start + 1, end);
|
}
|
|
/**
|
* 隐藏软键盘
|
* @param context
|
* @param windowTockn
|
*/
|
public static void hideSoftKeyboard(Context context, IBinder windowTockn) {
|
InputMethodManager inputManger = (InputMethodManager) context
|
.getSystemService(Context.INPUT_METHOD_SERVICE);
|
if (inputManger != null) {
|
inputManger.hideSoftInputFromWindow(windowTockn, 0);
|
}
|
}
|
|
/**
|
* 定时器循环显示软键盘.
|
* @param editText
|
*/
|
public static void showKeyboard(final EditText editText){
|
Timer timer = new Timer();
|
|
timer.schedule(new TimerTask(){
|
|
public void run() {
|
|
InputMethodManager inputManager =
|
(InputMethodManager)editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
|
inputManager.showSoftInput(editText, 0);
|
}
|
|
},
|
|
1000);
|
}
|
|
/**
|
* URL转UTF-8编码.
|
* @param ufilename
|
* @return
|
*/
|
public static String getUTF8Info2(String ufilename) {
|
|
int index = -1;
|
StringBuilder retName = new StringBuilder();
|
String tmpstr;
|
while (true) {
|
index = ufilename.indexOf(' ');
|
|
if (index != -1) {
|
tmpstr = ufilename.substring(0, index);
|
try {
|
retName.append(URLEncoder.encode(tmpstr, "UTF-8"));
|
} catch (UnsupportedEncodingException e) {
|
}
|
retName.append("%20");
|
ufilename = ufilename.substring(index + 1);
|
} else
|
break;
|
}
|
|
try {
|
retName.append(URLEncoder.encode(ufilename, "UTF-8"));
|
} catch (UnsupportedEncodingException e) {
|
}
|
return retName.toString();
|
|
}
|
|
/*******************************************获取本地音乐缩略图的方法*************************************/
|
/**
|
* 获取本地音乐缩略图的方法
|
* @param filePath
|
* @return
|
*/
|
@SuppressLint("NewApi")
|
public static Bitmap getLocalMusicBitmap(String filePath) {
|
Bitmap bitmap = null;
|
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
|
mmr.setDataSource(filePath);
|
bitmap = Bytes2Bimap(mmr.getEmbeddedPicture());
|
return bitmap;
|
}
|
|
@SuppressLint("NewApi")
|
public static Bitmap getLocalVideoBitmap(String filePath) {
|
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
|
mmr.setDataSource(filePath);
|
return mmr.getFrameAtTime();
|
}
|
|
/**
|
* 将字节转换为Bitmap图片
|
* @param b
|
* @return
|
*/
|
public static Bitmap Bytes2Bimap(byte[] b) {
|
if(b == null) return null;
|
|
if (b.length != 0) {
|
return BitmapFactory.decodeByteArray(b, 0, b.length);
|
|
} else {
|
return null;
|
}
|
}
|
|
public static String FormetkbTo(String fileSize) {// 转换文件大小
|
DecimalFormat df = new DecimalFormat("#.0");
|
long fileS = 0;
|
if (fileSize.equals("")) {
|
fileS = 0;
|
} else {
|
fileS = Long.parseLong(fileSize);
|
}
|
String fileSizeString = "";
|
if (fileS == 0) {
|
fileSizeString = "0MB";
|
} else if (fileS < 1024) {
|
fileSizeString = df.format((double) fileS) + "MB";
|
} else if (fileS < 1048576) {
|
fileSizeString = df.format((double) fileS / 1024) + "GB";
|
} else if (fileS < 1073741824) {
|
fileSizeString = df.format((double) fileS / 1048576) + "TB";
|
} else {
|
// fileSizeString = df.format((double) fileS / 1073741824) + "T";
|
}
|
return fileSizeString;
|
}
|
|
/**
|
* 匹配由数字、26个英文字母或者下划线以及空格 组成的字符串
|
* @param str
|
* @return
|
*/
|
public static boolean isMatchValidator(String str) {
|
return str.matches("^[\\sA-Za-z0-9-]+$");
|
}
|
|
/**
|
* 密码由英文字母(字母区分大小写)和数字组成,且长度5~32位!
|
* @param str
|
* @return
|
*/
|
public static boolean isMatchValidator3(String str) {
|
boolean b = str.matches("^[A-Za-z0-9]+$");
|
return b;
|
}
|
|
/**
|
* 以英文字母开头,由字母、数字和‘-’组成,且长度2~8位.
|
* @param str
|
* @return
|
*/
|
public static boolean isMatchValidator2(String str) {
|
boolean b = str.matches("^[A-Za-z0-9-]+$");
|
if (b) {
|
String s = str.substring(0, 1);
|
b = s.matches("^[A-Za-z]+$");
|
}
|
return b;
|
}
|
|
/**
|
* 把加密的密码转换为正确的秘密.
|
* @param securityPwd
|
* @return
|
*/
|
public static String changeSecurityPwd(String securityPwd) {
|
String changeAfterPwd;
|
if (securityPwd != null && !securityPwd.equals("") && (securityPwd.contains("CDATA") || securityPwd.contains("[["))) {
|
final int endindex = securityPwd.indexOf("]]");
|
changeAfterPwd = securityPwd.substring(8, endindex);
|
} else {
|
changeAfterPwd = securityPwd;
|
}
|
return changeAfterPwd;
|
}
|
|
|
private static boolean copyFile(String oldPath, String newPath) {
|
try {
|
int bytesum = 0;
|
int byteread = 0;
|
File oldfile = new File(oldPath);
|
if (oldfile.exists()) { //文件存在时
|
InputStream inStream = new FileInputStream(oldPath); //读入原文件
|
FileOutputStream fs = new FileOutputStream(newPath);
|
byte[] buffer = new byte[1444];
|
|
while ( (byteread = inStream.read(buffer)) != -1) {
|
bytesum += byteread; //字节数 文件大小
|
fs.write(buffer, 0, byteread);
|
}
|
inStream.close();
|
fs.close();
|
}
|
|
return true;
|
} catch (Exception e) {
|
return false;
|
}
|
}
|
//----------->>>
|
|
|
/**
|
* 转换px单位的数值为dp单位的数值.
|
* @param px px单位的数值.
|
* @param context 上下文.
|
* @return dp单位的数值.
|
*/
|
public static float pixelsToDp(float px, Context context){
|
final float scale = context.getResources()
|
.getDisplayMetrics().density;
|
return (int) (px / scale + 0.5f);
|
}
|
|
/**
|
* 获取手机状态栏高度.
|
* @param context
|
* @return
|
*/
|
public static int getStatusBarHeight(Context context){
|
Class<?> c = null;
|
Object obj = null;
|
Field field = null;
|
int x = 0, statusBarHeight = 0;
|
try {
|
c = Class.forName("com.android.internal.R$dimen");
|
obj = c.newInstance();
|
field = c.getField("status_bar_height");
|
x = Integer.parseInt(field.get(obj).toString());
|
statusBarHeight = context.getResources().getDimensionPixelSize(x);
|
} catch (Exception e1) {
|
e1.printStackTrace();
|
}
|
return statusBarHeight;
|
}
|
|
public static int getNavigationBarHeight(Context context) {
|
Resources resources = context.getResources();
|
int resourceId = resources.getIdentifier("navigation_bar_height","dimen", "android");
|
int height = resources.getDimensionPixelSize(resourceId);
|
return height;
|
}
|
|
//获取是否存在NavigationBar
|
public static boolean checkDeviceHasNavigationBar(Context context) {
|
boolean hasNavigationBar = false;
|
Resources rs = context.getResources();
|
int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
|
if (id > 0) {
|
hasNavigationBar = rs.getBoolean(id);
|
}
|
try {
|
Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
|
Method m = systemPropertiesClass.getMethod("get", String.class);
|
String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
|
if ("1".equals(navBarOverride)) {
|
hasNavigationBar = false;
|
} else if ("0".equals(navBarOverride)) {
|
hasNavigationBar = true;
|
}
|
} catch (Exception e) {
|
|
}
|
return hasNavigationBar;
|
|
}
|
|
/**
|
* 获取名称的前缀
|
*
|
* @param name
|
* @return
|
*/
|
public static String getPrefixFromName(String name) {
|
String prefix = name.substring(0, name.lastIndexOf("."));
|
return prefix;
|
}
|
|
/**
|
* 设置光标在Edittext文本的末尾.
|
* @param text
|
*/
|
public static void setCursorLocation(final CharSequence text){
|
// 设置光标的位置在字符串的末尾
|
if (text instanceof Spannable) {
|
Spannable spanText = (Spannable)text;
|
Selection.setSelection(spanText, text.length());
|
}
|
}
|
|
/**
|
* 将星号显示的密码转为明文显示.
|
* @param editText
|
*/
|
public static void showEditTextPwd(EditText editText) {
|
editText.setInputType(InputType.TYPE_CLASS_TEXT
|
| InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
|
}
|
|
/**
|
* 将明文显示的密码转为星号显示.
|
* @param editText
|
*/
|
public static void hideEditTextPwd(EditText editText) {
|
editText.setInputType(InputType.TYPE_CLASS_TEXT
|
| InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
|
}
|
|
/**
|
* 获取名称的"/"分隔符后面的字段
|
*
|
* @param name
|
* @return
|
*/
|
public static String getSpecialFromName(String name) {
|
String prefix = name.substring(name.lastIndexOf("/") + 1);
|
return prefix;
|
}
|
|
/**
|
* 获取后缀名
|
*
|
* @param name
|
* @return
|
*/
|
public static String getExtensionFromName(String name) {
|
String prefix = name.substring(name.lastIndexOf(".") + 1);
|
return prefix;
|
}
|
|
|
/**
|
* 设置导航栏颜色
|
* @param activity
|
* @param colorResId
|
*/
|
public static void setNavigationBarColor(Activity activity, int colorResId) {
|
try {
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
|
Window window = activity.getWindow();
|
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
|
// window.setStatusBarColor(activity.getResources().getColor(colorResId));
|
|
//底部导航栏
|
window.setNavigationBarColor(activity.getResources().getColor(colorResId));
|
}
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
}
|
|
@TargetApi(19)
|
public static void setTranslucentStatus(Activity activity, boolean on) {
|
Window win = activity.getWindow();
|
WindowManager.LayoutParams winParams = win.getAttributes();
|
final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
|
if (on) {
|
winParams.flags |= bits;
|
} else {
|
winParams.flags &= ~bits;
|
}
|
win.setAttributes(winParams);
|
}
|
|
// <<<------------------------- 自动生成ID ---------------------------------------
|
public static final AtomicInteger sNextGeneratedId = new AtomicInteger(3000);
|
|
/**
|
* 自动生成View的ID.
|
* This value will not collide with ID values generated at build time by aapt for R.id.
|
*
|
* @return a generated ID value
|
*/
|
public static int generateViewId() {
|
for (; ; ) {
|
final int result = sNextGeneratedId.get();
|
int newValue = result + 1;
|
if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
|
if (sNextGeneratedId.compareAndSet(result, newValue)) {
|
return result;
|
}
|
}
|
}
|
// ---------------------------- 自动生成ID --------------------------------------->>>
|
|
|
// <<<---------------------------- Camera初始化相关 --------------------------------------->>>
|
/**
|
* @return the default camera on the device. Return null if there is no camera on the device.
|
*/
|
public static Camera getDefaultCameraInstance() {
|
return Camera.open();
|
}
|
|
/**
|
* Iterate over supported camera video sizes to see which one best fits the
|
* dimensions of the given view while maintaining the aspect ratio. If none can,
|
* be lenient with the aspect ratio.
|
*
|
* @param supportedVideoSizes Supported camera video sizes.
|
* @param previewSizes Supported camera preview sizes.
|
* @param w The width of the view.
|
* @param h The height of the view.
|
* @return Best match camera video size to fit in the view.
|
*/
|
public static Camera.Size getOptimalVideoSize(List<Camera.Size> supportedVideoSizes,
|
List<Camera.Size> previewSizes, int w, int h) {
|
// Use a very small tolerance because we want an exact match.
|
final double ASPECT_TOLERANCE = 0.1;
|
double targetRatio = (double) w / h;
|
|
// Supported video sizes list might be null, it means that we are allowed to use the preview
|
// sizes
|
List<Camera.Size> videoSizes;
|
if (supportedVideoSizes != null) {
|
videoSizes = supportedVideoSizes;
|
} else {
|
videoSizes = previewSizes;
|
}
|
Camera.Size optimalSize = null;
|
|
// Start with max value and refine as we iterate over available video sizes. This is the
|
// minimum difference between view and camera height.
|
double minDiff = Double.MAX_VALUE;
|
|
// Target view height
|
int targetHeight = h;
|
|
// Try to find a video size that matches aspect ratio and the target view size.
|
// Iterate over all available sizes and pick the largest size that can fit in the view and
|
// still maintain the aspect ratio.
|
for (Camera.Size size : videoSizes) {
|
double ratio = (double) size.width / size.height;
|
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)
|
continue;
|
if (Math.abs(size.height - targetHeight) < minDiff && previewSizes.contains(size)) {
|
optimalSize = size;
|
minDiff = Math.abs(size.height - targetHeight);
|
}
|
}
|
|
// Cannot find video size that matches the aspect ratio, ignore the requirement
|
if (optimalSize == null) {
|
minDiff = Double.MAX_VALUE;
|
for (Camera.Size size : videoSizes) {
|
if (Math.abs(size.height - targetHeight) < minDiff && previewSizes.contains(size)) {
|
optimalSize = size;
|
minDiff = Math.abs(size.height - targetHeight);
|
}
|
}
|
}
|
return optimalSize;
|
}
|
// ---------------------------- Camera初始化相关 --------------------------------------->>>
|
|
/**
|
* 设置状态栏图标为深色和魅族特定的文字风格,Flyme4.0以上
|
* 可以用来判断是否为Flyme用户
|
* @param window 需要设置的窗口
|
* @param dark 是否把状态栏字体及图标颜色设置为深色
|
* @return boolean 成功执行返回true
|
*
|
*/
|
public static boolean FlymeSetStatusBarLightMode(Window window, boolean dark) {
|
boolean result = false;
|
if (window != null) {
|
try {
|
WindowManager.LayoutParams lp = window.getAttributes();
|
Field darkFlag = WindowManager.LayoutParams.class
|
.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
|
Field meizuFlags = WindowManager.LayoutParams.class
|
.getDeclaredField("meizuFlags");
|
darkFlag.setAccessible(true);
|
meizuFlags.setAccessible(true);
|
int bit = darkFlag.getInt(null);
|
int value = meizuFlags.getInt(lp);
|
if (dark) {
|
value |= bit;
|
} else {
|
value &= ~bit;
|
}
|
meizuFlags.setInt(lp, value);
|
window.setAttributes(lp);
|
result = true;
|
} catch (Exception e) {
|
|
}
|
}
|
return result;
|
}
|
|
/**
|
* 设置状态栏字体图标为深色,需要MIUIV6以上
|
* @param window 需要设置的窗口
|
* @param dark 是否把状态栏字体及图标颜色设置为深色
|
* @return boolean 成功执行返回true
|
*
|
*/
|
public static boolean MIUISetStatusBarLightMode(Window window, boolean dark) {
|
boolean result = false;
|
if (window != null) {
|
Class clazz = window.getClass();
|
try {
|
int darkModeFlag = 0;
|
Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
|
Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
|
darkModeFlag = field.getInt(layoutParams);
|
Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
|
if(dark){
|
extraFlagField.invoke(window,darkModeFlag,darkModeFlag);//状态栏透明且黑色字体
|
}else{
|
extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字体
|
}
|
result=true;
|
}catch (Exception e){
|
|
}
|
}
|
return result;
|
}
|
|
private static Toast mToast;
|
|
/**
|
* 单例显示Toast消息.
|
* @param context 上下文.
|
* @param content 显示的内容.
|
*/
|
public static void showToast(Context context, String content) {
|
try {
|
if (mToast == null) {
|
mToast = Toast.makeText(context.getApplicationContext(), content, Toast.LENGTH_SHORT);
|
} else {
|
mToast.setText(content);
|
}
|
mToast.show();
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
}
|
|
/**
|
* 判断App是否已经启动.
|
* @param context
|
* @return
|
*/
|
public static boolean isAppOnForeground(Context context, Class homeName) {
|
// Returns a list of application processes that are running on the
|
// device
|
boolean isRunning = false;
|
Intent intent = new Intent(context, homeName);
|
ComponentName cmpName = intent.resolveActivity(context.getPackageManager());
|
if (cmpName != null) { // 说明系统中存在这个activity
|
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
|
List<ActivityManager.RunningTaskInfo> taskInfoList = am.getRunningTasks(10);
|
for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
|
if (taskInfo.baseActivity.equals(cmpName)) { // 说明它已经启动了
|
isRunning = true;
|
break;
|
} else {
|
isRunning = false;
|
}
|
}
|
}
|
return isRunning;
|
}
|
|
|
/**
|
* 获得文件大小
|
* @param size
|
* @return
|
*/
|
public static String getFileSize(long size) {
|
//如果字节数少于1024,则直接以B为单位,否则先除于1024,后3位因太少无意义
|
if (size < 1024) {
|
return String.valueOf(size) + "B";
|
} else {
|
size = size / 1024;
|
}
|
//如果原字节数除于1024之后,少于1024,则可以直接以KB作为单位
|
//因为还没有到达要使用另一个单位的时候
|
//接下去以此类推
|
if (size < 1024) {
|
return String.valueOf(size) + "KB";
|
} else {
|
size = size / 1024;
|
}
|
if (size < 1024) {
|
//因为如果以MB为单位的话,要保留最后1位小数,
|
//因此,把此数乘以100之后再取余
|
size = size * 100;
|
return String.valueOf((size / 100)) + "."
|
+ String.valueOf((size % 100)) + "MB";
|
} else {
|
//否则如果要以GB为单位的,先除于1024再作同样的处理
|
size = size * 100 / 1024;
|
return String.valueOf((size / 100)) + "."
|
+ String.valueOf((size % 100)) + "GB";
|
}
|
}
|
|
/**
|
* aes加密
|
* @param key
|
* @param data
|
* @param ivbyte
|
* @return
|
*/
|
public static String encrypt(String key, String data, String ivbyte){
|
try {
|
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
|
int blockSize = cipher.getBlockSize();
|
|
byte[] dataBytes = data.getBytes();
|
int plaintextLength = dataBytes.length;
|
if (plaintextLength % blockSize != 0) {
|
plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
|
}
|
|
byte[] plaintext = new byte[plaintextLength];
|
System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
|
|
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
|
IvParameterSpec ivspec = new IvParameterSpec(ivbyte.getBytes());
|
|
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
|
byte[] encrypted = cipher.doFinal(plaintext);
|
|
String s = bytes2hex02(encrypted);
|
return s;
|
|
} catch (Exception e) {
|
e.printStackTrace();
|
return null;
|
}
|
}
|
|
/**
|
* 转化为16进制
|
*
|
* @param bytes
|
* @return
|
*/
|
public static String bytes2hex02(byte[] bytes) {
|
StringBuilder sb = new StringBuilder();
|
String tmp = null;
|
for (byte b : bytes) {
|
// 将每个字节与0xFF进行与运算,然后转化为10进制,然后借助于Integer再转化为16进制
|
tmp = Integer.toHexString(0xFF & b);
|
if (tmp.length() == 1){// 每个字节8为,转为16进制标志,2个16进制位
|
tmp = "0" + tmp;
|
}
|
sb.append(tmp);
|
}
|
return sb.toString();
|
}
|
|
/**
|
* 判断是魅族操作系统
|
* <h3>Version</h3> 1.0
|
* <h3>CreateTime</h3> 2016/6/18,9:43
|
* <h3>UpdateTime</h3> 2016/6/18,9:43
|
* <h3>CreateAuthor</h3> vera
|
* <h3>UpdateAuthor</h3>
|
* <h3>UpdateInfo</h3> (此处输入修改内容,若无修改可不写.)
|
* @return true 为魅族系统 否则不是
|
*/
|
public static boolean isMeizuFlymeOS() {
|
/* 获取魅族系统操作版本标识*/
|
String meizuFlymeOSFlag = getSystemProperty("ro.build.display.id","");
|
if (TextUtils.isEmpty(meizuFlymeOSFlag)){
|
return false;
|
}else if (meizuFlymeOSFlag.contains("flyme") || meizuFlymeOSFlag.toLowerCase().contains("flyme")){
|
return true;
|
}else {
|
return false;
|
}
|
}
|
|
/**
|
* 获取系统属性
|
* <h3>Version</h3> 1.0
|
* <h3>CreateTime</h3> 2016/6/18,9:35
|
* <h3>UpdateTime</h3> 2016/6/18,9:35
|
* <h3>CreateAuthor</h3> vera
|
* <h3>UpdateAuthor</h3>
|
* <h3>UpdateInfo</h3> (此处输入修改内容,若无修改可不写.)
|
* @param key ro.build.display.id
|
* @param defaultValue 默认值
|
* @return 系统操作版本标识
|
*/
|
private static String getSystemProperty(String key, String defaultValue) {
|
try {
|
Class<?> clz = Class.forName("android.os.SystemProperties");
|
Method get = clz.getMethod("get", String.class, String.class);
|
return (String)get.invoke(clz, key, defaultValue);
|
} catch (ClassNotFoundException e) {
|
return null;
|
} catch (NoSuchMethodException e) {
|
return null;
|
} catch (IllegalAccessException e) {
|
return null;
|
} catch (IllegalArgumentException e) {
|
return null;
|
} catch (InvocationTargetException e) {
|
return null;
|
}
|
}
|
|
/**
|
* 检测支付宝是否安装.
|
* @return
|
*/
|
public static boolean isZFBInstall(Context context) {
|
boolean isInstall = false;
|
final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
|
List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
|
if (pinfo != null) {
|
for (int i = 0; i < pinfo.size(); i++) {
|
String pn = pinfo.get(i).packageName;
|
if (pn.equals("com.eg.android.AlipayGphone")) {
|
isInstall = true;
|
}
|
}
|
}
|
return isInstall;
|
}
|
|
/**
|
* 除法保留小数点
|
* @param v1
|
* @param v2
|
* @param scale
|
* @return
|
*/
|
public static double getRoundDecimal(long v1, long v2, int scale) {
|
try {
|
BigDecimal b1 = new BigDecimal(Double.toString(v1));
|
BigDecimal b2 = new BigDecimal(Double.toString(v2));
|
double result = b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
|
return result;
|
} catch (Exception e) {
|
e.printStackTrace();
|
return 0;
|
}
|
}
|
|
/**
|
* px2dp
|
* @param context
|
* @param pxValue
|
* @return
|
*/
|
public static int px2dp(Context context,float pxValue){
|
final float scale=context.getResources().getDisplayMetrics().density;
|
return (int)(pxValue/scale+0.5f);
|
}
|
|
/**
|
* dp2px
|
* @param context
|
* @param dpValue
|
* @return
|
*/
|
public static int dp2px(Context context,float dpValue){
|
final float scale=context.getResources().getDisplayMetrics().density;
|
return (int)(dpValue*scale+0.5f);
|
}
|
|
/**
|
* 判断Homepage 是否已经启动过
|
* @return
|
*/
|
public static boolean getAppIsRunning(Context context, Class mClass) {
|
boolean isRunning = false;
|
Intent intent = new Intent(context, mClass);
|
ComponentName cmpName = intent.resolveActivity(context.getPackageManager());
|
if (cmpName != null) { // 说明系统中存在这个activity
|
ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
|
List<ActivityManager.RunningTaskInfo> taskInfoList = am.getRunningTasks(10);
|
for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
|
if (taskInfo.baseActivity.equals(cmpName)) { // 说明它已经启动了
|
isRunning = true;
|
break;
|
} else {
|
isRunning = false;
|
}
|
}
|
}
|
return isRunning;
|
}
|
|
/**
|
* 显示成功或失败
|
* @param isOk
|
*/
|
public static void showResultToast(Context context, boolean isOk) {
|
// int resId = isOk ? R.mipmap.ic_toast_ok : R.mipmap.ic_toast_error;
|
// WdToast i4SeasonToast = WdToast.makeText(context, resId, Toast.LENGTH_SHORT);
|
// i4SeasonToast.setGravity(Gravity.CENTER, 0, 0);
|
// i4SeasonToast.show();
|
}
|
|
}
|