把项目中常用的小工具做个总结吧,方便自己以后用到

2024-05-10 10:08

本文主要是介绍把项目中常用的小工具做个总结吧,方便自己以后用到,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1、根据手机的分辨率从 dp 的单位 转成为 px(像素) 

public static int dip2px(Context context, float dpValue) {  final float scale = context.getResources().getDisplayMetrics().density;  return (int) (dpValue * scale + 0.5f);  }

2、根据手机的分辨率从 px(像素) 的单位 转成为 dp

public static int px2dip(Context context, float pxValue) {  final float scale = context.getResources().getDisplayMetrics().density;  return (int) (pxValue / scale + 0.5f);  } 

3、获取屏幕的宽度

public static int getScreenWidth(Context context) {DisplayMetrics dm = new DisplayMetrics();dm = context.getApplicationContext().getResources().getDisplayMetrics();int width = dm.widthPixels;return width;}

4、获取屏幕的高度

public static int getScreenHeight(Context context) {DisplayMetrics dm = new DisplayMetrics();dm = context.getApplicationContext().getResources().getDisplayMetrics();int height = dm.heightPixels;return height;}

5、验证手机号格式

public static boolean isMobileNO(String mobiles) {Pattern p = Pattern.compile("^[1][3,4,5,8,7][0-9]{9}$");Matcher m = p.matcher(mobiles);return m.matches();}

6、验证邮箱格式正确性,仅验证邮箱是否是字母或数字组成、以及@符号后是否为字母或数字

public static boolean checkEmail(String arg0) {return arg0.matches("^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$");}

7、用户名,由字母数字下划线组成,并以字母下划线开头,6到20个字符之间

public boolean checkUserName(String name){Pattern pattern = Pattern.compile("^^[a-zA-Z_][a-zA-Z0-9_]{5,19}$");Matcher matcher = pattern.matcher(name);  return matcher.matches();}

8、根据身份证获取性别

public static String getSex(String arg0) {if(checkNullMethod(arg0) && arg0.length() >= 18){String sex = arg0.substring(16, 17);int sex2 = Integer.valueOf(sex);if (sex2 % 2 == 0) {return "女";}}else{return "男";}return "";}

9、根据身份证获取出生日期

public static String getBirth(String arg0) {String year = arg0.substring(6, 10);String month = arg0.substring(10, 12);String day = arg0.substring(12, 14);return year + "-" + month + "-" + day;}

10、根据身份证获取年龄

public static String getAge(String arg0) {String year = arg0.substring(6, 10);SimpleDateFormat sdf = new SimpleDateFormat("yyyy");String nowYear = sdf.format(System.currentTimeMillis());int age = Integer.valueOf(nowYear) - Integer.valueOf(year);return age + "";}

11、String字符串判空

public static boolean checkNullMethod(String arg0) {if(arg0 == null)return false;arg0 = arg0.trim();if (arg0 != null  && arg0.length() != 0 && !arg0.equals("null") && !arg0.equals("")) {return true;}return false;}

 
 

12、图片uri转换为bitmap

public Bitmap decodeUriAsBitmap(Uri uri) {Bitmap bitmap = null;try {bitmap = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(uri));} catch (FileNotFoundException e) {e.printStackTrace();return null;}return bitmap;}

13、动态设置item中listview的高度

public static void setListheight(ListView listview) {ListAdapter listadapter = listview.getAdapter();if (listadapter == null) {return;}int totalheight = 0;for (int i = 0; i < listadapter.getCount(); i++) {View listItem = listadapter.getView(i, null, listview);listItem.measure(0, 0);totalheight += listItem.getMeasuredHeight();}ViewGroup.LayoutParams params = listview.getLayoutParams();params.height = totalheight+ (listview.getDividerHeight() * (listadapter.getCount() - 1));listview.setLayoutParams(params);}

14、获取应用版本名称,此处是versionName

public String getVersionName() {String versionName = "v1.0";try {PackageManager pm = context.getPackageManager();PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);versionName = pi.versionName;} catch (NameNotFoundException e) {e.printStackTrace();}return versionName;}

15、获取应用版本号,此处是versionCode

public int getVersionCode() {try {PackageManager pm = context.getPackageManager();PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);return pi.versionCode;} catch (NameNotFoundException e) {e.printStackTrace();}return 0;}

16、关闭软键盘

public void closeInput(EditText ed_text) {InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);// 得到InputMethodManager的实例if (imm.isActive()) {imm.hideSoftInputFromWindow(ed_text.getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);}}

17、根据uri获取路径,如果是uri路径则通过uri返回文件绝对路径

public String getUriPath(Uri fileUri) {Uri filePathUri = fileUri;if (fileUri != null) {/** content://  开头的uri*/if (fileUri.getScheme().toString().compareTo("content") == 0) {// 通过uri获取选中的图片文件路径String[] proj = { MediaStore.Images.Media.DATA };@SuppressWarnings("deprecation")Cursor cursor = ((Activity) context).managedQuery(fileUri,proj, null, null, null);int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);cursor.moveToFirst();// 最后根据索引值获取图片路径String path = cursor.getString(column_index);return path;}/** file://   开头的uri*/else if (fileUri.getScheme().compareTo("file") == 0) {String fileName = filePathUri.toString();fileName = filePathUri.toString().replace("file://", "");return fileName;}}return null;}

18、检测屏幕是否是锁屏状态;为true,表示有两种状态:a、屏幕是黑的 b、目前正处于解锁状态 。为false,表示目前未锁屏

public boolean getIsLockScreen(){KeyguardManager mKeyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);return mKeyguardManager.inKeyguardRestrictedInputMode();}

19、日期转换;long类型转成String类型

public static String longToString(long currentTime, String formatType) throws ParseException {Date date = longToDate(currentTime, formatType); // long类型转成Date类型String strTime = dateToString(date, formatType); // date类型转成Stringreturn strTime;}

20、日期转换;string类型转换为long类型

public static long stringToLong(String strTime, String formatType) throws ParseException {Date date = stringToDate(strTime, formatType); // String类型转成date类型if (date == null) {return 0;} else {long currentTime = dateToLong(date); // date类型转成long类型return currentTime;}}

21、日期转换;date类型转换为long类型

public static long dateToLong(Date date) {return date.getTime();}

22、日期转换;long类型转成date类型

public static Date longToDate(long currentTime, String formatType) throws ParseException {Date dateOld = new Date(currentTime); // 根据long类型的毫秒数生命一个date类型的时间String sDateTime = dateToString(dateOld, formatType); // 把date类型的时间转换为stringDate date = stringToDate(sDateTime, formatType); // 把String类型转换为Date类型return date;}

23、日期转换;String类型转成date类型

public static Date stringToDate(String strTime, String formatType) throws ParseException {SimpleDateFormat formatter = new SimpleDateFormat(formatType);Date date = null;try {date = formatter.parse(strTime);} catch (java.text.ParseException e) {e.printStackTrace();}return date;}

24、date类型转换为String类型; formatType格式为 yyyy-MM-dd HH:mm:ss(yyyy年MM月dd日  HH时mm分ss秒); data为Date类型的时间

public static String dateToString(Date data, String formatType) {return new SimpleDateFormat(formatType).format(data);}

25、隐藏系统级别导航

public static void hideVirtualButtons(Activity activity) {if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE);}}

26、获取系统内存剩余

public static long getAvailableMemory(Context context) {ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();am.getMemoryInfo(memoryInfo);return memoryInfo.availMem;}

27、判断APP是否在前台

public static boolean isAppOnForeground(Context context) {ActivityManager activityManager = (ActivityManager) context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);String packageName = context.getApplicationContext().getPackageName();List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();if (appProcesses == null)return false;for (RunningAppProcessInfo appProcess : appProcesses) {if (appProcess.processName.equals(packageName)&& appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {return true;}}return false;}

28、判断SD卡是否可用

public static boolean hasSdcard() {if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {return true;} return false;}

29、复制文件

public static void copyfile(File fromFile, File toFile){if(toFile.exists()){toFile.delete();}FileInputStream fosform;try {fosform = new FileInputStream(fromFile);FileOutputStream fosto = new FileOutputStream(toFile);byte b[] = new byte[1024];int len;while((len = fosform.read(b)) > 0){fosto.write(b,0,len);}fosform.close();fosto.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}

30、转换文件大小

public static String getFormetFileSize(){long fileS = getCacheSize();DecimalFormat df = new DecimalFormat("#0.00");String fileSizeString = "";if (fileS < 1024){fileSizeString = df.format((double) fileS) + "B";}else if (fileS < 1048576){fileSizeString = df.format((double) fileS / 1024) + "K";}else if (fileS < 1073741824){fileSizeString = df.format((double) fileS / 1048576) + "M";}else{fileSizeString = df.format((double) fileS / 1073741824) + "G";}return fileSizeString;}

31、保存要缓存的数据到私有文件

public void saveDatasInFile(String xmlString, String fileName) {FileOutputStream fos = null;try{fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);fos.write(xmlString.getBytes());fos.flush();}catch(Exception e){e.printStackTrace();}finally{try {fos.close();} catch (Exception e) {}}}

32、读取私有文件缓存的数据

public void readDatasInFile(final String fileName,final readFileCallback callback){  try {  FileInputStream fin = context.openFileInput(fileName);  //获取文件长度  int lenght = fin.available();  byte[] buffer = new byte[lenght];  fin.read(buffer);  //将byte数组转换成指定格式的字符串  String result = new String(buffer,"utf-8");  callback.readFile(result);} catch (Exception e) {  e.printStackTrace();  }  }  public interface readFileCallback{public void readFile(String string);}

33、获取视频封面

public static String getVideoThumbPath(Context context, String path) {String thumbPath = null;Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(path, MediaStore.Video.Thumbnails.FULL_SCREEN_KIND);File file = SDUtils.getCreatFile(context, SDUtils.imgCachePicUrl, System.currentTimeMillis() + ".jpg");FileOutputStream fOut = null;try {fOut = new FileOutputStream(file);bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);fOut.flush();fOut.close();} catch (IOException e) {return null;}thumbPath = file.getAbsolutePath();return thumbPath;}


34、okhttp3打印请求参数(表单提交方式)

private static String bodyToString(final Request request){try {final Request copy = request.newBuilder().build();final Buffer buffer = new Buffer();copy.body().writeTo(buffer);String s = buffer.readUtf8();return URLDecoder.decode(s, "UTF-8");} catch (final IOException e) {return "did not work";
}


持续更新...












































这篇关于把项目中常用的小工具做个总结吧,方便自己以后用到的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/976141

相关文章

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

Qt实现网络数据解析的方法总结

《Qt实现网络数据解析的方法总结》在Qt中解析网络数据通常涉及接收原始字节流,并将其转换为有意义的应用层数据,这篇文章为大家介绍了详细步骤和示例,感兴趣的小伙伴可以了解下... 目录1. 网络数据接收2. 缓冲区管理(处理粘包/拆包)3. 常见数据格式解析3.1 jsON解析3.2 XML解析3.3 自定义

Java中的工具类命名方法

《Java中的工具类命名方法》:本文主要介绍Java中的工具类究竟如何命名,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录Java中的工具类究竟如何命名?先来几个例子几种命名方式的比较到底如何命名 ?总结Java中的工具类究竟如何命名?先来几个例子JD

Python的time模块一些常用功能(各种与时间相关的函数)

《Python的time模块一些常用功能(各种与时间相关的函数)》Python的time模块提供了各种与时间相关的函数,包括获取当前时间、处理时间间隔、执行时间测量等,:本文主要介绍Python的... 目录1. 获取当前时间2. 时间格式化3. 延时执行4. 时间戳运算5. 计算代码执行时间6. 转换为指

SpringBoot项目中报错The field screenShot exceeds its maximum permitted size of 1048576 bytes.的问题及解决

《SpringBoot项目中报错ThefieldscreenShotexceedsitsmaximumpermittedsizeof1048576bytes.的问题及解决》这篇文章... 目录项目场景问题描述原因分析解决方案总结项目场景javascript提示:项目相关背景:项目场景:基于Spring

解决Maven项目idea找不到本地仓库jar包问题以及使用mvn install:install-file

《解决Maven项目idea找不到本地仓库jar包问题以及使用mvninstall:install-file》:本文主要介绍解决Maven项目idea找不到本地仓库jar包问题以及使用mvnin... 目录Maven项目idea找不到本地仓库jar包以及使用mvn install:install-file基

Python正则表达式语法及re模块中的常用函数详解

《Python正则表达式语法及re模块中的常用函数详解》这篇文章主要给大家介绍了关于Python正则表达式语法及re模块中常用函数的相关资料,正则表达式是一种强大的字符串处理工具,可以用于匹配、切分、... 目录概念、作用和步骤语法re模块中的常用函数总结 概念、作用和步骤概念: 本身也是一个字符串,其中

usb接口驱动异常问题常用解决方案

《usb接口驱动异常问题常用解决方案》当遇到USB接口驱动异常时,可以通过多种方法来解决,其中主要就包括重装USB控制器、禁用USB选择性暂停设置、更新或安装新的主板驱动等... usb接口驱动异常怎么办,USB接口驱动异常是常见问题,通常由驱动损坏、系统更新冲突、硬件故障或电源管理设置导致。以下是常用解决

Python实现图片分割的多种方法总结

《Python实现图片分割的多种方法总结》图片分割是图像处理中的一个重要任务,它的目标是将图像划分为多个区域或者对象,本文为大家整理了一些常用的分割方法,大家可以根据需求自行选择... 目录1. 基于传统图像处理的分割方法(1) 使用固定阈值分割图片(2) 自适应阈值分割(3) 使用图像边缘检测分割(4)