/**
* app工具类
* @author charlie
*
*/
@SuppressLint({ "SimpleDateFormat", "NewApi" })
public class AppTools {
/**
* 判断APK是否安装
*
* @param context
* @param pageName
* @return
*/
public static boolean appIsInstalled(Context context, String pageName) {
try {
context.getPackageManager().getPackageInfo(pageName, 0);
return true;
} catch (NameNotFoundException e) {
return false;
}
}
/**
* @方法名:fileToByte<br>
*
* @功能说明:将文件转换为字节数组<br>
*
* @param path
* @return
*/
public static String fileToByte(String path) {
String ret = null;
int count;
if (path != null) {
File file = new File(path);
long len = file.length();
if (file.exists()) {
FileInputStream fis = null;
StringBuffer sb = new StringBuffer();
try {
fis = new FileInputStream(file);
byte[] buffer = new byte[(int) len];
while ((count = fis.read(buffer)) != -1) {
sb.append(Base64.encode(buffer, count));
count++;
}
ret = sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return ret;
}
/**
* 方法名: 判断SD卡是否存在
* <p>
* 功能说明: 判断SD卡是否存在, 如果存在返回SD卡路径 , 如果不存在返回路径为空
* </p>
*
* @return
*/
public static String getSDPath() {
boolean sdCardExist = Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
if (sdCardExist) {
File sdDir = Environment.getExternalStorageDirectory();
return sdDir.toString();
}
return "";
}
/**
* 删除目录及子文件
*
* @param filepath
* @throws IOException
*/
public static void del(String filepath){
File f = new File(filepath);// 定义文件路径
if (f.exists() && f.isDirectory()) {// 判断是文件还是目录
if (f.listFiles().length == 0) {// 若目录下没有文件则直接删除
f.delete();
} else {// 若有则把文件放进数组,并判断是否有下级目录
File delFile[] = f.listFiles();
int i = f.listFiles().length;
for (int j = 0; j < i; j++) {
if (delFile[j].isDirectory()) {
del(delFile[j].getAbsolutePath());// 递归调用del方法并取得子目录路径
}
delFile[j].delete();// 删除文件
}
}
}
}
/**
* 方法名:拍照并返回图片存储路径
* <p>
* 功能说明:拍照并返回图片存储路径
* </p>
*
* @param activity
* @param requestCode
* @return
*/
public static String getCapturePath(Activity activity,int CAMERA_REQUEST_CODE,String path_save) {
String path = getImageSavePath(path_save) + "/" + getTime("yyyyMMddHHmmss")
+ ".jpg";
Intent cameraintent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraintent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(new File(path)));
activity.startActivityForResult(cameraintent,CAMERA_REQUEST_CODE);
return path;
}
/**
* 方法名:获取图片文件存取路径
* <p>
* 功能说明:获取图片文件存取路径
* </p>
*
* @return
*/
public static String getImageSavePath(String path) {
if (AppTools.getSDPath().equals("")) {
return "";
}
File file = new File(AppTools.getSDPath() + path);
if (!file.exists()) {
if (file.mkdirs()) {
return file.getPath();
}
return "";
}
return file.getPath();
}
/**
* 方法名: 获取系统当前时间
* <p>
* 功能说明: 获取系统当前时间
* </p>
*
* @param pattern
* @return
*/
public static String getTime(String pattern) {
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
return dateFormat.format(new Date());
}
/**
* 文件存取路径
*
* @param path
* @return
*/
public static String getImageSavePathCase(String path) {
if (AppTools.getSDPath().equals("")) {
return "";
}
File file = new File(AppTools.getSDPath() + path);
if (!file.exists()) {
if (file.mkdirs()) {
return file.getPath();
}
return "";
}
return file.getPath();
}
/**
* 判断版本并检测是否打开GPS
*/
public static boolean isOpenGps(Context context) {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
return false;
}
return true;
}
/**
* 方法名:将uri 转换为绝对路径
* <p>
* 功能说明: 将uri 转换为绝对路径
* </p>
*
* @param context
* @param uri
* @return
*/
public static String getAbsolutePath(Context context, Uri uri) {
if (uri == null) {
return null;
}
if (uri.toString().contains("file://")) {
String path = uri.toString().replace("file://", "");
return Uri.decode(path);
}
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(uri, proj, null,
null, null);
if (cursor == null) {
return null;
}
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
/**
* 安装APK文件
*
* @param activity
* @param file
*/
public static void inistallAPKFile(Activity activity, File file) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
activity.startActivity(intent);
// activity.finish();
}
/**
* 拷贝assets目录下文件到制定目录中
*
* @param context
* @param fileName
* @return
*/
public static File getAssetFileToCacheDir(Context context, String fileName,String save_path) {
try {
File cacheDir = new File(save_path);
final String cachePath = cacheDir.getAbsolutePath()
+ File.separator + fileName;
InputStream is = context.getAssets().open(fileName);
File file = new File(cachePath);
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
byte[] temp = new byte[1024];
int i = 0;
while ((i = is.read(temp)) > 0) {
fos.write(temp, 0, i);
}
fos.close();
is.close();
return file;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 退出系统
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
public static void quit(Activity context) {
if (context.getFragmentManager().getBackStackEntryCount() != 0) {
context.getFragmentManager().popBackStack();
} else {
context.finish();
}
}
/**
* 拨打电话
*
* @param context
* @param phoneCode
*/
public static void callPhone(Activity activity, String phoneCode) {
Intent intent = new Intent();
String tel = "tel:" + phoneCode;
intent.setData(Uri.parse(tel));
intent.setAction(Intent.ACTION_DIAL);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
}
/**
* 发送邮件
*
* @param context
* @param phoneCode
*/
public static void sendEmail(Activity activity, String email) {
String[] reciver = new String[] { email };
String[] mySbuject = new String[] { "test" };
String myCc = "cc";
String mybody = "测试Email Intent";
Intent myIntent = new Intent(android.content.Intent.ACTION_SEND);
myIntent.setType("plain/text");
myIntent.putExtra(android.content.Intent.EXTRA_EMAIL, reciver);
myIntent.putExtra(android.content.Intent.EXTRA_CC, myCc);
myIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, mySbuject);
myIntent.putExtra(android.content.Intent.EXTRA_TEXT, mybody);
activity.startActivity(Intent.createChooser(myIntent, "mail test"));
}
/**
* 将date转换成format格式
* @param date
* @param format
* @return
*/
public static final String convertDateString(Date date, String format) {
SimpleDateFormat df = null;
String returnValue = "";
if (date == null) {
android.util.Log.e("warn", "aDate is null!2");
} else {
df = new SimpleDateFormat(format);
returnValue = df.format(date);
}
return returnValue;
}
/**
* 验证邮箱
*
* @param email
* @return
*/
public static boolean isEmail(String email) {
String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
Pattern p = Pattern.compile(str);
Matcher m = p.matcher(email);
return m.matches();
}
/**
* 身份证验证
*
* @param IDStr
* @return
*/
public static boolean IDCardValidate(String IDStr) {
String str = "^(\\d{18,18}|\\d{15,15}|\\d{17,17}x)$";
Pattern p = Pattern.compile(str);
Matcher m = p.matcher(IDStr);
return m.matches();
}
/**
* 手机号码验证
*
* @param IDStr
* @return
*/
public static boolean isPhone(String phone) {
String str = "(^(\\d{3,4}-)?\\d{7,8})$|(13[0-9]{9})";
Pattern p = Pattern.compile(str);
Matcher m = p.matcher(phone);
return m.matches();
}
/**
* 邮政编码验证
*
* @param IDStr
* @return
*/
public static boolean isPlaceNum(String phone) {
String str = "^[1-9][0-9]{5}$";
Pattern p = Pattern.compile(str);
Matcher m = p.matcher(phone);
return m.matches();
}
/**
* 将时间yyyy-MM-dd转换成format数据格式
*
* @param adateStrteStr
* @param format
* @return
*/
public static String convertDate(String adateStrteStr, String format) {
if (adateStrteStr.isEmpty())
return "";
java.util.Date date = null;
String dateString = null;
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"yyyy-MM-dd");
date = simpleDateFormat.parse(adateStrteStr);
SimpleDateFormat sim = new SimpleDateFormat(format);
dateString = sim.format(date);
} catch (Exception ex) {
}
return dateString;
}
/**
* 将bitmap保存
* @param bitmap
* @param path
* @return
* @throws IOException
*/
public static String saveBitmap(Bitmap bitmap,String path) throws IOException {
File file = new File(path);
if(!file.getParentFile().exists()){
file.mkdirs();
}
if(!file.exists()){
file.createNewFile();
}
FileOutputStream out;
try {
out = new FileOutputStream(file);
if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)) {
out.flush();
out.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return path;
}
/**
* 将指定路径的图片显示为Bitmap
* @param myJpgPath
* @return
*/
public static Bitmap getImage(String myJpgPath){
File file=new File(myJpgPath);
if(file.exists()){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap bm = BitmapFactory.decodeFile(myJpgPath, options);
return bm;
}
return null;
}
/**
* 调用系统图片查看器
*/
public static void showView(Activity activity, String path) {
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.fromFile(new File(getImageSavePathCase(path))), "image/*");
activity.startActivity(intent);
}
/**
* 调用系统视频播放器
*
* @param activity
* @param videoPath
*/
public static void playVideo(Activity activity, String videoPath) {
Intent intent = new Intent(Intent.ACTION_VIEW);
String strend = "";
if (videoPath.toLowerCase().endsWith(".mp4")) {
strend = "mp4";
} else if (videoPath.toLowerCase().endsWith(".3gp")) {
strend = "3gp";
} else if (videoPath.toLowerCase().endsWith(".mov")) {
strend = "mov";
} else if (videoPath.toLowerCase().endsWith(".wmv")) {
strend = "wmv";
}
intent.setDataAndType(Uri.parse(videoPath), "video/" + strend);
activity.startActivity(intent);
}
/**
* 将集合转换成字符串数组
* @param list
* @return
*/
public String[] convertCollectionToArray(List<String> list) {
String[] array = list.toArray(new String[list.size()]);
return array;
}
/**
* //读文件在./data/data/包名/files/下面
*
* @param fileName
* @return
*/
public static String readFileData(Context context,String fileName) {
String res = "";
try {
FileInputStream fin = context.openFileInput(fileName);
int length = fin.available();
byte[] buffer = new byte[length];
fin.read(buffer);
res = EncodingUtils.getString(buffer, "UTF-8");
fin.close();
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
/**
* 指定格式返回当前系统时间
*/
public static String getDataTime(String format) {
SimpleDateFormat df = new SimpleDateFormat(format);
return df.format(new Date());
}
/**
* 返回当前系统时间(格式以HH:mm形式)
*/
public static String getDataTime() {
return getDataTime("HH:mm");
}
/**
* 获取手机IMEI码
*/
public static String getPhoneIMEI(Context cxt) {
TelephonyManager tm = (TelephonyManager) cxt
.getSystemService(Context.TELEPHONY_SERVICE);
return tm.getDeviceId();
}
/**
* 获取手机系统SDK版本
*
* @return 如API 17 则返回 17
*/
public static int getSDKVersion() {
return android.os.Build.VERSION.SDK_INT;
}
/**
* 获取安卓系统版本
*
* @return 形如2.3.3
*/
public static String getSystemVersion() {
return android.os.Build.VERSION.RELEASE;
}
/**
* 调用系统发送短信
*/
public static void sendSMS(Context cxt, String smsBody) {
Uri smsToUri = Uri.parse("smsto:");
Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
intent.putExtra("sms_body", smsBody);
cxt.startActivity(intent);
}
/**
* 判断网络是否连接
*/
public static boolean checkNet(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
return info != null;// 网络是否连接
}
/**
* 判断是否为wifi联网
*/
public static boolean isWiFi(Context cxt) {
ConnectivityManager cm = (ConnectivityManager) cxt
.getSystemService(Context.CONNECTIVITY_SERVICE);
// wifi的状态:ConnectivityManager.TYPE_WIFI
// 3G的状态:ConnectivityManager.TYPE_MOBILE
State state = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.getState();
return State.CONNECTED == state;
}
/**
* 隐藏系统键盘
*
* <br>
* <b>警告</b> 必须是确定键盘显示时才能调用
*/
public static void hideKeyBoard(Activity aty) {
((InputMethodManager) aty
.getSystemService(Context.INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(
aty.getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
/**
* 判断当前应用程序是否后台运行
*/
public static boolean isBackground(Context context) {
ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.processName.equals(context.getPackageName())) {
if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
// 后台运行
return true;
} else {
// 前台运行
return false;
}
}
}
return false;
}
/**
* 判断手机是否处理睡眠
*/
public static boolean isSleeping(Context context) {
KeyguardManager kgMgr = (KeyguardManager) context
.getSystemService(Context.KEYGUARD_SERVICE);
boolean isSleeping = kgMgr.inKeyguardRestrictedInputMode();
return isSleeping;
}
/**
* 安装apk
*
* @param context
* @param file
*/
public static void installApk(Context context, File file) {
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.setType("application/vnd.android.package-archive");
intent.setData(Uri.fromFile(file));
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
/**
* 获取当前应用程序的版本号
*/
public static String getAppVersion(Context context) {
String version = "0";
try {
version = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException(AppTools.class.getName()
+ "the application not found");
}
return version;
}
/**
* 回到home,后台运行
*/
public static void goHome(Context context) {
Intent mHomeIntent = new Intent(Intent.ACTION_MAIN);
mHomeIntent.addCategory(Intent.CATEGORY_HOME);
mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
context.startActivity(mHomeIntent);
}
/**
* 获取应用签名
*
* @param context
* @param pkgName
*/
public static String getSign(Context context, String pkgName) {
try {
PackageInfo pis = context.getPackageManager().getPackageInfo(
pkgName, PackageManager.GET_SIGNATURES);
return hexdigest(pis.signatures[0].toByteArray());
} catch (NameNotFoundException e) {
throw new RuntimeException(AppTools.class.getName() + "the "
+ pkgName + "'s application not found");
}
}
/**
* 将签名字符串转换成需要的32位签名
*/
private static String hexdigest(byte[] paramArrayOfByte) {
final char[] hexDigits = { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97,
98, 99, 100, 101, 102 };
try {
MessageDigest localMessageDigest = MessageDigest.getInstance("MD5");
localMessageDigest.update(paramArrayOfByte);
byte[] arrayOfByte = localMessageDigest.digest();
char[] arrayOfChar = new char[32];
for (int i = 0, j = 0;; i++, j++) {
if (i >= 16) {
return new String(arrayOfChar);
}
int k = arrayOfByte[i];
arrayOfChar[j] = hexDigits[(0xF & k >>> 4)];
arrayOfChar[++j] = hexDigits[(k & 0xF)];
}
} catch (Exception e) {
}
return "";
}
/**
* 获取设备的可用内存大小
*
* @param cxt
* 应用上下文对象context
* @return 当前内存大小
*/
public static int getDeviceUsableMemory(Context cxt) {
ActivityManager am = (ActivityManager) cxt
.getSystemService(Context.ACTIVITY_SERVICE);
//得到内存使用情况
MemoryInfo mi = new MemoryInfo();
am.getMemoryInfo(mi);
// 返回当前系统的可用内存
return (int) (mi.availMem / (1024 * 1024));
}
// /**
// * 清理后台进程与服务
// *
// * @param cxt
// * 应用上下文对象context
// * @return 被清理的数量
// */
// public static int gc(Context cxt) {
// long i = getDeviceUsableMemory(cxt);
// int count = 0; // 清理掉的进程数
// ActivityManager am = (ActivityManager) cxt
// .getSystemService(Context.ACTIVITY_SERVICE);
// // 获取正在运行的service列表
// List<RunningServiceInfo> serviceList = am.getRunningServices(100);
// if (serviceList != null)
// for (RunningServiceInfo service : serviceList) {
// if (service.pid == android.os.Process.myPid())
// continue;
// try {
// android.os.Process.killProcess(service.pid);
// count++;
// } catch (Exception e) {
// e.getStackTrace();
// continue;
// }
// }
//
// // 获取正在运行的进程列表
// List<RunningAppProcessInfo> processList = am.getRunningAppProcesses();
// if (processList != null)
// for (RunningAppProcessInfo process : processList) {
// // 一般数值大于RunningAppProcessInfo.IMPORTANCE_SERVICE的进程都长时间没用或者空进程了
// // 一般数值大于RunningAppProcessInfo.IMPORTANCE_VISIBLE的进程都是非可见进程,也就是在后台运行着
// if (process.importance > RunningAppProcessInfo.IMPORTANCE_VISIBLE) {
// // pkgList 得到该进程下运行的包名
// String[] pkgList = process.pkgList;
// for (String pkgName : pkgList) {
// KJLoger.debug("======正在杀死包名:" + pkgName);
// try {
// am.killBackgroundProcesses(pkgName);
// count++;
// } catch (Exception e) { // 防止意外发生
// e.getStackTrace();
// continue;
// }
// }
// }
// }
// KJLoger.debug("清理了" + (getDeviceUsableMemory(cxt) - i) + "M内存");
// return count;
// }
//获取屏幕的宽度
public static int getScreenWidth(Context context) {
WindowManager manager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
return display.getWidth();
}
//获取屏幕的高度
public static int getScreenHeight(Context context) {
WindowManager manager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
return display.getHeight();
}
public static int getW(Activity context){
DisplayMetrics dm = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(dm);
int screenWidth = dm.widthPixels;
int screenHeight = dm.heightPixels;
return screenWidth;
}
public static int getH(Activity context){
DisplayMetrics dm = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(dm);
int screenWidth = dm.widthPixels;
int screenHeight = dm.heightPixels;
return screenHeight;
}
/**
* 以最省内存的方式读取本地资源的图片
* @param context
* @param resId
* @return
*/
public static Bitmap readBitMap(Context context, int resId){
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.RGB_565;
opt.inPurgeable = true;
opt.inInputShareable = true;
//获取资源图片
InputStream is = context.getResources().openRawResource(resId);
return BitmapFactory.decodeStream(is,null,opt);
}
}
* app工具类
* @author charlie
*
*/
@SuppressLint({ "SimpleDateFormat", "NewApi" })
public class AppTools {
/**
* 判断APK是否安装
*
* @param context
* @param pageName
* @return
*/
public static boolean appIsInstalled(Context context, String pageName) {
try {
context.getPackageManager().getPackageInfo(pageName, 0);
return true;
} catch (NameNotFoundException e) {
return false;
}
}
/**
* @方法名:fileToByte<br>
*
* @功能说明:将文件转换为字节数组<br>
*
* @param path
* @return
*/
public static String fileToByte(String path) {
String ret = null;
int count;
if (path != null) {
File file = new File(path);
long len = file.length();
if (file.exists()) {
FileInputStream fis = null;
StringBuffer sb = new StringBuffer();
try {
fis = new FileInputStream(file);
byte[] buffer = new byte[(int) len];
while ((count = fis.read(buffer)) != -1) {
sb.append(Base64.encode(buffer, count));
count++;
}
ret = sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return ret;
}
/**
* 方法名: 判断SD卡是否存在
* <p>
* 功能说明: 判断SD卡是否存在, 如果存在返回SD卡路径 , 如果不存在返回路径为空
* </p>
*
* @return
*/
public static String getSDPath() {
boolean sdCardExist = Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
if (sdCardExist) {
File sdDir = Environment.getExternalStorageDirectory();
return sdDir.toString();
}
return "";
}
/**
* 删除目录及子文件
*
* @param filepath
* @throws IOException
*/
public static void del(String filepath){
File f = new File(filepath);// 定义文件路径
if (f.exists() && f.isDirectory()) {// 判断是文件还是目录
if (f.listFiles().length == 0) {// 若目录下没有文件则直接删除
f.delete();
} else {// 若有则把文件放进数组,并判断是否有下级目录
File delFile[] = f.listFiles();
int i = f.listFiles().length;
for (int j = 0; j < i; j++) {
if (delFile[j].isDirectory()) {
del(delFile[j].getAbsolutePath());// 递归调用del方法并取得子目录路径
}
delFile[j].delete();// 删除文件
}
}
}
}
/**
* 方法名:拍照并返回图片存储路径
* <p>
* 功能说明:拍照并返回图片存储路径
* </p>
*
* @param activity
* @param requestCode
* @return
*/
public static String getCapturePath(Activity activity,int CAMERA_REQUEST_CODE,String path_save) {
String path = getImageSavePath(path_save) + "/" + getTime("yyyyMMddHHmmss")
+ ".jpg";
Intent cameraintent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraintent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(new File(path)));
activity.startActivityForResult(cameraintent,CAMERA_REQUEST_CODE);
return path;
}
/**
* 方法名:获取图片文件存取路径
* <p>
* 功能说明:获取图片文件存取路径
* </p>
*
* @return
*/
public static String getImageSavePath(String path) {
if (AppTools.getSDPath().equals("")) {
return "";
}
File file = new File(AppTools.getSDPath() + path);
if (!file.exists()) {
if (file.mkdirs()) {
return file.getPath();
}
return "";
}
return file.getPath();
}
/**
* 方法名: 获取系统当前时间
* <p>
* 功能说明: 获取系统当前时间
* </p>
*
* @param pattern
* @return
*/
public static String getTime(String pattern) {
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
return dateFormat.format(new Date());
}
/**
* 文件存取路径
*
* @param path
* @return
*/
public static String getImageSavePathCase(String path) {
if (AppTools.getSDPath().equals("")) {
return "";
}
File file = new File(AppTools.getSDPath() + path);
if (!file.exists()) {
if (file.mkdirs()) {
return file.getPath();
}
return "";
}
return file.getPath();
}
/**
* 判断版本并检测是否打开GPS
*/
public static boolean isOpenGps(Context context) {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
return false;
}
return true;
}
/**
* 方法名:将uri 转换为绝对路径
* <p>
* 功能说明: 将uri 转换为绝对路径
* </p>
*
* @param context
* @param uri
* @return
*/
public static String getAbsolutePath(Context context, Uri uri) {
if (uri == null) {
return null;
}
if (uri.toString().contains("file://")) {
String path = uri.toString().replace("file://", "");
return Uri.decode(path);
}
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(uri, proj, null,
null, null);
if (cursor == null) {
return null;
}
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
/**
* 安装APK文件
*
* @param activity
* @param file
*/
public static void inistallAPKFile(Activity activity, File file) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
activity.startActivity(intent);
// activity.finish();
}
/**
* 拷贝assets目录下文件到制定目录中
*
* @param context
* @param fileName
* @return
*/
public static File getAssetFileToCacheDir(Context context, String fileName,String save_path) {
try {
File cacheDir = new File(save_path);
final String cachePath = cacheDir.getAbsolutePath()
+ File.separator + fileName;
InputStream is = context.getAssets().open(fileName);
File file = new File(cachePath);
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
byte[] temp = new byte[1024];
int i = 0;
while ((i = is.read(temp)) > 0) {
fos.write(temp, 0, i);
}
fos.close();
is.close();
return file;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 退出系统
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
public static void quit(Activity context) {
if (context.getFragmentManager().getBackStackEntryCount() != 0) {
context.getFragmentManager().popBackStack();
} else {
context.finish();
}
}
/**
* 拨打电话
*
* @param context
* @param phoneCode
*/
public static void callPhone(Activity activity, String phoneCode) {
Intent intent = new Intent();
String tel = "tel:" + phoneCode;
intent.setData(Uri.parse(tel));
intent.setAction(Intent.ACTION_DIAL);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
}
/**
* 发送邮件
*
* @param context
* @param phoneCode
*/
public static void sendEmail(Activity activity, String email) {
String[] reciver = new String[] { email };
String[] mySbuject = new String[] { "test" };
String myCc = "cc";
String mybody = "测试Email Intent";
Intent myIntent = new Intent(android.content.Intent.ACTION_SEND);
myIntent.setType("plain/text");
myIntent.putExtra(android.content.Intent.EXTRA_EMAIL, reciver);
myIntent.putExtra(android.content.Intent.EXTRA_CC, myCc);
myIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, mySbuject);
myIntent.putExtra(android.content.Intent.EXTRA_TEXT, mybody);
activity.startActivity(Intent.createChooser(myIntent, "mail test"));
}
/**
* 将date转换成format格式
* @param date
* @param format
* @return
*/
public static final String convertDateString(Date date, String format) {
SimpleDateFormat df = null;
String returnValue = "";
if (date == null) {
android.util.Log.e("warn", "aDate is null!2");
} else {
df = new SimpleDateFormat(format);
returnValue = df.format(date);
}
return returnValue;
}
/**
* 验证邮箱
*
* @param email
* @return
*/
public static boolean isEmail(String email) {
String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
Pattern p = Pattern.compile(str);
Matcher m = p.matcher(email);
return m.matches();
}
/**
* 身份证验证
*
* @param IDStr
* @return
*/
public static boolean IDCardValidate(String IDStr) {
String str = "^(\\d{18,18}|\\d{15,15}|\\d{17,17}x)$";
Pattern p = Pattern.compile(str);
Matcher m = p.matcher(IDStr);
return m.matches();
}
/**
* 手机号码验证
*
* @param IDStr
* @return
*/
public static boolean isPhone(String phone) {
String str = "(^(\\d{3,4}-)?\\d{7,8})$|(13[0-9]{9})";
Pattern p = Pattern.compile(str);
Matcher m = p.matcher(phone);
return m.matches();
}
/**
* 邮政编码验证
*
* @param IDStr
* @return
*/
public static boolean isPlaceNum(String phone) {
String str = "^[1-9][0-9]{5}$";
Pattern p = Pattern.compile(str);
Matcher m = p.matcher(phone);
return m.matches();
}
/**
* 将时间yyyy-MM-dd转换成format数据格式
*
* @param adateStrteStr
* @param format
* @return
*/
public static String convertDate(String adateStrteStr, String format) {
if (adateStrteStr.isEmpty())
return "";
java.util.Date date = null;
String dateString = null;
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"yyyy-MM-dd");
date = simpleDateFormat.parse(adateStrteStr);
SimpleDateFormat sim = new SimpleDateFormat(format);
dateString = sim.format(date);
} catch (Exception ex) {
}
return dateString;
}
/**
* 将bitmap保存
* @param bitmap
* @param path
* @return
* @throws IOException
*/
public static String saveBitmap(Bitmap bitmap,String path) throws IOException {
File file = new File(path);
if(!file.getParentFile().exists()){
file.mkdirs();
}
if(!file.exists()){
file.createNewFile();
}
FileOutputStream out;
try {
out = new FileOutputStream(file);
if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)) {
out.flush();
out.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return path;
}
/**
* 将指定路径的图片显示为Bitmap
* @param myJpgPath
* @return
*/
public static Bitmap getImage(String myJpgPath){
File file=new File(myJpgPath);
if(file.exists()){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap bm = BitmapFactory.decodeFile(myJpgPath, options);
return bm;
}
return null;
}
/**
* 调用系统图片查看器
*/
public static void showView(Activity activity, String path) {
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.fromFile(new File(getImageSavePathCase(path))), "image/*");
activity.startActivity(intent);
}
/**
* 调用系统视频播放器
*
* @param activity
* @param videoPath
*/
public static void playVideo(Activity activity, String videoPath) {
Intent intent = new Intent(Intent.ACTION_VIEW);
String strend = "";
if (videoPath.toLowerCase().endsWith(".mp4")) {
strend = "mp4";
} else if (videoPath.toLowerCase().endsWith(".3gp")) {
strend = "3gp";
} else if (videoPath.toLowerCase().endsWith(".mov")) {
strend = "mov";
} else if (videoPath.toLowerCase().endsWith(".wmv")) {
strend = "wmv";
}
intent.setDataAndType(Uri.parse(videoPath), "video/" + strend);
activity.startActivity(intent);
}
/**
* 将集合转换成字符串数组
* @param list
* @return
*/
public String[] convertCollectionToArray(List<String> list) {
String[] array = list.toArray(new String[list.size()]);
return array;
}
/**
* //读文件在./data/data/包名/files/下面
*
* @param fileName
* @return
*/
public static String readFileData(Context context,String fileName) {
String res = "";
try {
FileInputStream fin = context.openFileInput(fileName);
int length = fin.available();
byte[] buffer = new byte[length];
fin.read(buffer);
res = EncodingUtils.getString(buffer, "UTF-8");
fin.close();
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
/**
* 指定格式返回当前系统时间
*/
public static String getDataTime(String format) {
SimpleDateFormat df = new SimpleDateFormat(format);
return df.format(new Date());
}
/**
* 返回当前系统时间(格式以HH:mm形式)
*/
public static String getDataTime() {
return getDataTime("HH:mm");
}
/**
* 获取手机IMEI码
*/
public static String getPhoneIMEI(Context cxt) {
TelephonyManager tm = (TelephonyManager) cxt
.getSystemService(Context.TELEPHONY_SERVICE);
return tm.getDeviceId();
}
/**
* 获取手机系统SDK版本
*
* @return 如API 17 则返回 17
*/
public static int getSDKVersion() {
return android.os.Build.VERSION.SDK_INT;
}
/**
* 获取安卓系统版本
*
* @return 形如2.3.3
*/
public static String getSystemVersion() {
return android.os.Build.VERSION.RELEASE;
}
/**
* 调用系统发送短信
*/
public static void sendSMS(Context cxt, String smsBody) {
Uri smsToUri = Uri.parse("smsto:");
Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
intent.putExtra("sms_body", smsBody);
cxt.startActivity(intent);
}
/**
* 判断网络是否连接
*/
public static boolean checkNet(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
return info != null;// 网络是否连接
}
/**
* 判断是否为wifi联网
*/
public static boolean isWiFi(Context cxt) {
ConnectivityManager cm = (ConnectivityManager) cxt
.getSystemService(Context.CONNECTIVITY_SERVICE);
// wifi的状态:ConnectivityManager.TYPE_WIFI
// 3G的状态:ConnectivityManager.TYPE_MOBILE
State state = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.getState();
return State.CONNECTED == state;
}
/**
* 隐藏系统键盘
*
* <br>
* <b>警告</b> 必须是确定键盘显示时才能调用
*/
public static void hideKeyBoard(Activity aty) {
((InputMethodManager) aty
.getSystemService(Context.INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(
aty.getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
/**
* 判断当前应用程序是否后台运行
*/
public static boolean isBackground(Context context) {
ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.processName.equals(context.getPackageName())) {
if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
// 后台运行
return true;
} else {
// 前台运行
return false;
}
}
}
return false;
}
/**
* 判断手机是否处理睡眠
*/
public static boolean isSleeping(Context context) {
KeyguardManager kgMgr = (KeyguardManager) context
.getSystemService(Context.KEYGUARD_SERVICE);
boolean isSleeping = kgMgr.inKeyguardRestrictedInputMode();
return isSleeping;
}
/**
* 安装apk
*
* @param context
* @param file
*/
public static void installApk(Context context, File file) {
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.setType("application/vnd.android.package-archive");
intent.setData(Uri.fromFile(file));
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
/**
* 获取当前应用程序的版本号
*/
public static String getAppVersion(Context context) {
String version = "0";
try {
version = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException(AppTools.class.getName()
+ "the application not found");
}
return version;
}
/**
* 回到home,后台运行
*/
public static void goHome(Context context) {
Intent mHomeIntent = new Intent(Intent.ACTION_MAIN);
mHomeIntent.addCategory(Intent.CATEGORY_HOME);
mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
context.startActivity(mHomeIntent);
}
/**
* 获取应用签名
*
* @param context
* @param pkgName
*/
public static String getSign(Context context, String pkgName) {
try {
PackageInfo pis = context.getPackageManager().getPackageInfo(
pkgName, PackageManager.GET_SIGNATURES);
return hexdigest(pis.signatures[0].toByteArray());
} catch (NameNotFoundException e) {
throw new RuntimeException(AppTools.class.getName() + "the "
+ pkgName + "'s application not found");
}
}
/**
* 将签名字符串转换成需要的32位签名
*/
private static String hexdigest(byte[] paramArrayOfByte) {
final char[] hexDigits = { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97,
98, 99, 100, 101, 102 };
try {
MessageDigest localMessageDigest = MessageDigest.getInstance("MD5");
localMessageDigest.update(paramArrayOfByte);
byte[] arrayOfByte = localMessageDigest.digest();
char[] arrayOfChar = new char[32];
for (int i = 0, j = 0;; i++, j++) {
if (i >= 16) {
return new String(arrayOfChar);
}
int k = arrayOfByte[i];
arrayOfChar[j] = hexDigits[(0xF & k >>> 4)];
arrayOfChar[++j] = hexDigits[(k & 0xF)];
}
} catch (Exception e) {
}
return "";
}
/**
* 获取设备的可用内存大小
*
* @param cxt
* 应用上下文对象context
* @return 当前内存大小
*/
public static int getDeviceUsableMemory(Context cxt) {
ActivityManager am = (ActivityManager) cxt
.getSystemService(Context.ACTIVITY_SERVICE);
//得到内存使用情况
MemoryInfo mi = new MemoryInfo();
am.getMemoryInfo(mi);
// 返回当前系统的可用内存
return (int) (mi.availMem / (1024 * 1024));
}
// /**
// * 清理后台进程与服务
// *
// * @param cxt
// * 应用上下文对象context
// * @return 被清理的数量
// */
// public static int gc(Context cxt) {
// long i = getDeviceUsableMemory(cxt);
// int count = 0; // 清理掉的进程数
// ActivityManager am = (ActivityManager) cxt
// .getSystemService(Context.ACTIVITY_SERVICE);
// // 获取正在运行的service列表
// List<RunningServiceInfo> serviceList = am.getRunningServices(100);
// if (serviceList != null)
// for (RunningServiceInfo service : serviceList) {
// if (service.pid == android.os.Process.myPid())
// continue;
// try {
// android.os.Process.killProcess(service.pid);
// count++;
// } catch (Exception e) {
// e.getStackTrace();
// continue;
// }
// }
//
// // 获取正在运行的进程列表
// List<RunningAppProcessInfo> processList = am.getRunningAppProcesses();
// if (processList != null)
// for (RunningAppProcessInfo process : processList) {
// // 一般数值大于RunningAppProcessInfo.IMPORTANCE_SERVICE的进程都长时间没用或者空进程了
// // 一般数值大于RunningAppProcessInfo.IMPORTANCE_VISIBLE的进程都是非可见进程,也就是在后台运行着
// if (process.importance > RunningAppProcessInfo.IMPORTANCE_VISIBLE) {
// // pkgList 得到该进程下运行的包名
// String[] pkgList = process.pkgList;
// for (String pkgName : pkgList) {
// KJLoger.debug("======正在杀死包名:" + pkgName);
// try {
// am.killBackgroundProcesses(pkgName);
// count++;
// } catch (Exception e) { // 防止意外发生
// e.getStackTrace();
// continue;
// }
// }
// }
// }
// KJLoger.debug("清理了" + (getDeviceUsableMemory(cxt) - i) + "M内存");
// return count;
// }
//获取屏幕的宽度
public static int getScreenWidth(Context context) {
WindowManager manager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
return display.getWidth();
}
//获取屏幕的高度
public static int getScreenHeight(Context context) {
WindowManager manager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
return display.getHeight();
}
public static int getW(Activity context){
DisplayMetrics dm = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(dm);
int screenWidth = dm.widthPixels;
int screenHeight = dm.heightPixels;
return screenWidth;
}
public static int getH(Activity context){
DisplayMetrics dm = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(dm);
int screenWidth = dm.widthPixels;
int screenHeight = dm.heightPixels;
return screenHeight;
}
/**
* 以最省内存的方式读取本地资源的图片
* @param context
* @param resId
* @return
*/
public static Bitmap readBitMap(Context context, int resId){
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.RGB_565;
opt.inPurgeable = true;
opt.inInputShareable = true;
//获取资源图片
InputStream is = context.getResources().openRawResource(resId);
return BitmapFactory.decodeStream(is,null,opt);
}
}