当前位置:   article > 正文

Android之 常用工具类_android 工具类

android 工具类

一 时间格式化

1.1 时间戳按指定格式转化为日期

  1. /**
  2. * 时间戳按指定格式转化为日期(String)
  3. * @param timestamp
  4. * @return
  5. */
  6. public static String convertTimestampDate(Long timestamp) {
  7. Date date = new Date(timestamp);
  8. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
  9. return format.format(date);
  10. }

1.2 日期按指定格式转化为时间戳

  1. /**
  2. * 指定格式时间字符串转时间戳
  3. * @param dateString 2018-11-07 13:42:03,
  4. * @return 1541569323000
  5. */
  6. public static long convertStringToTimestamp(String dateString) {
  7. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:s");
  8. Date date = new Date();
  9. try {
  10. date = dateFormat.parse(dateString);
  11. } catch (ParseException e) {
  12. e.printStackTrace();
  13. }
  14. return date.getTime();
  15. }

  1.3 总时长秒数格式化为n小时n分钟n秒

  1. /**
  2. * 总时长秒数格式化为n小时n分钟n秒
  3. * @param ms
  4. * @return
  5. */
  6. public static String reSetStringTime(long ms) {
  7. int hour = (int) (ms / (1000 * 60 * 60));
  8. int minute = (int) ((ms % (1000 * 60 * 60)) / (1000 * 60));
  9. int second = (int) ((ms % (1000 * 60)) / 1000);
  10. //int millisecond = (int)(ms % 1000);
  11. String hourString = hour < 10 ? "0" + hour : String.valueOf(hour);
  12. String minuteString = minute < 10 ? "0" + minute : String.valueOf(minute);
  13. String secondString = second < 10 ? "0" + second : String.valueOf(second);
  14. return hourString + "小时" + minuteString + "分" + secondString + "秒";
  15. }

  1.4 根据当前日期时间戳获得是星期几

  1. /**
  2. * 根据当前日期时间戳获得是星期几
  3. * time=yyyy-MM-dd
  4. * @return
  5. */
  6. public static String getWeek(String time) {
  7. String Week = "";
  8. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  9. Calendar c = Calendar.getInstance();
  10. try {
  11. c.setTime(format.parse(time));
  12. } catch (ParseException e) {
  13. e.printStackTrace();
  14. }
  15. int wek=c.get(Calendar.DAY_OF_WEEK);
  16. if (wek == 1) {
  17. Week += "星期日";
  18. }
  19. if (wek == 2) {
  20. Week += "星期一";
  21. }
  22. if (wek == 3) {
  23. Week += "星期二";
  24. }
  25. if (wek == 4) {
  26. Week += "星期三";
  27. }
  28. if (wek == 5) {
  29. Week += "星期四";
  30. }
  31. if (wek == 6) {
  32. Week += "星期五";
  33. }
  34. if (wek == 7) {
  35. Week += "星期六";
  36. }
  37. return Week;
  38. }

1.5 时间戳判断是否为今年

  1. /**
  2. * 时间戳判断是否为今年
  3. */
  4. public static boolean isCurrentYear(Long timeStamp) {
  5. Calendar todayCalendar = Calendar.getInstance();
  6. Calendar calendar = Calendar.getInstance();
  7. calendar.setTimeInMillis(timeStamp);
  8. if (calendar.get(Calendar.YEAR) == (todayCalendar.get(Calendar.YEAR))) {
  9. return true;
  10. }
  11. return false;
  12. }

 1.6 时间戳判断是否为今天

  1. /**
  2. * 时间戳判断是否为今天
  3. */
  4. public static boolean isToday(Long timeStamp) {
  5. Calendar todayCalendar = Calendar.getInstance();
  6. Calendar calendar = Calendar.getInstance();
  7. calendar.setTimeInMillis(timeStamp);
  8. if (calendar.get(Calendar.YEAR) == (todayCalendar.get(Calendar.YEAR))) {
  9. int diffDay = todayCalendar.get(Calendar.DAY_OF_YEAR) - calendar.get(Calendar.DAY_OF_YEAR);
  10. return diffDay == 0;
  11. }
  12. return false;
  13. }

二 价格处理,价格格式化

 2.1 价格格式化不含小数

  1. //不含小数
  2. public static String decimal(String number) {
  3. BigDecimal a = new BigDecimal(number);
  4. DecimalFormat df = new DecimalFormat("##0");
  5. return subZeroAndDot(df.format(a));
  6. }

2.2  不五入保留两位小数

  1. //保留两位为位小数
  2. public static String decimalFloatDouble(double number) {
  3. BigDecimal bigDecimal = BigDecimal.valueOf(number).setScale(2,RoundingMode.DOWN);
  4. return subZeroAndDot(bigDecimal.toString());
  5. }

2.3 使用java正则表达式去掉多余的.与0

  1. /**
  2. * 使用java正则表达式去掉多余的.与0
  3. * @param s
  4. * @return
  5. */
  6. public static String subZeroAndDot(String s) {
  7. if (s == null) {
  8. return "";
  9. }
  10. if (s.indexOf(".") > 0) {
  11. s = s.replaceAll("0+?$", "");//去掉多余的0
  12. s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
  13. }
  14. return s;
  15. }

2.4 精准加减乘除计算

  1. /**
  2. * 加法
  3. */
  4. public static String add(String parms1, String param2) {
  5. return new BigDecimal(parms1).add(new BigDecimal(param2)).toString();
  6. }
  7. /**
  8. * 减法
  9. */
  10. public static String subtract(String parms1, String param2) {
  11. return new BigDecimal(parms1).subtract(new BigDecimal(param2)).toString();
  12. }
  13. /**
  14. * 乘法
  15. */
  16. public static String multiply(String parms1, String param2) {
  17. return new BigDecimal(parms1).multiply(new BigDecimal(param2)).toString();
  18. }
  19. /**
  20. * 除法
  21. * digit:小数位数,经尝试最大17位,超过17位无效,保险起见可设20位
  22. * roundType:四舍五入或者向下取整
  23. */
  24. public static String divide(String parms1, String param2) {
  25. return new BigDecimal(parms1).divide(new BigDecimal(param2), 20, BigDecimal.ROUND_DOWN).toString();
  26. }

2.5 销量格式化,大于10000显示1万+

  1. /**
  2. * 销售量格式化
  3. * 销量小于万位:展示实际数量
  4. * 销量大于万位:取万位和千位保留一位小数 无四舍五入等规则 例如1.2+万 2.3+万
  5. * 销量大于10w :直接显示10万+
  6. */
  7. public static String saleFormat(int number){
  8. if(number>10*10000){
  9. // 1w+ 格式化
  10. return "10万+";
  11. }else if(number>10000){
  12. return String.format(Locale.getDefault(), "%.1f+万", number / 10000f);
  13. }else {
  14. return String.valueOf(number);
  15. }
  16. }

三 单位间的相互转换

3.1  dp与px单位的相互转换

  1. /**
  2. * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
  3. */
  4. public static int dip2px(Context context, float dpValue) {
  5. final float scale = context.getResources().getDisplayMetrics().density;
  6. return (int) (dpValue * scale + 0.5f);
  7. }
  8. /**
  9. * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
  10. */
  11. public static int px2dip(Context context, float pxValue) {
  12. final float scale = context.getResources().getDisplayMetrics().density;
  13. return (int) (pxValue / scale + 0.5f);
  14. }

3.2 获取状态栏高度

  1. /**
  2. * 状态栏高度
  3. */
  4. public static int getStatusBarHeight(Activity activity) {
  5. int resourceId = activity.getResources().getIdentifier("status_bar_height", "dimen", "android");
  6. return activity.getResources().getDimensionPixelSize(resourceId);
  7. }

3.3 获取屏幕宽高

  1. /**
  2. * 返回屏幕的宽度
  3. */
  4. public static int getScreenWidth(Activity activity) {
  5. DisplayMetrics displayMetrics = new DisplayMetrics();
  6. activity.getWindowManager().getDefaultDisplay().getRealMetrics(displayMetrics);
  7. return displayMetrics.widthPixels;
  8. }
  9. /**
  10. * 返回包括虚拟键在内的总的屏幕高度
  11. * 即使虚拟按键显示着,也会加上虚拟按键的高度
  12. */
  13. public static int getScreenHeight(Activity activity) {
  14. DisplayMetrics displayMetrics = new DisplayMetrics();
  15. activity.getWindowManager().getDefaultDisplay().getRealMetrics(displayMetrics);
  16. return displayMetrics.heightPixels;
  17. }

3.4 毫米转为指定分辨率的像素

  1. /**
  2. * 像素=毫米x分辨率
  3. * dip,像素/英寸单位,1英寸=2.54厘米=25.4毫米
  4. * metrics.xdpi * (1.0f/25.4f) 代表分辨率x1.0fx1英寸 就是所需的dip(25.4f毫米级表示1英寸)
  5. * (300f / 25.4f) 一英寸上有300像素,一毫米上有 (300f / 25.4f)像素
  6. * value 毫米值
  7. *
  8. * dipValue 分辨率 默认96 ,可以更改为400或者300
  9. */
  10. public float applyDimension(float value) {
  11. return value * dipValue * (1f / 25.4f);
  12. }

四 文件操作

4.1 创建文件

  1. /**
  2. * 创建一个文件
  3. * path 路径
  4. */
  5. public static void creatFile(String path) {
  6. File file = new File(path);
  7. file.createNewFile();
  8. }

4.2 创建文件夹

  1. /**
  2. * 创建一个文件夹.
  3. * path 路径
  4. */
  5. public static void createDirectory(String path) {
  6. File file = new File(path);
  7. file.mkdir();
  8. }

4.3 判断文件或者文件夹是否存在

  1. /**
  2. * 判断文件或者文件夹是否存在
  3. */
  4. public static boolean isExists(String path) {
  5. File file = new File(path);
  6. return file.exists();
  7. }

4.4 获取文件或者文件夹大小

  1. /**
  2. * 获取文件或者文件夹大小.
  3. */
  4. public static long getFileAllSize(String path) {
  5. File file = new File(path);
  6. if (file.exists()) {
  7. if (file.isDirectory()) {
  8. File[] childrens = file.listFiles();
  9. long size = 0;
  10. for (File f : childrens) {
  11. size += getFileAllSize(f.getPath());
  12. }
  13. return size;
  14. } else {
  15. return file.length();
  16. }
  17. } else {
  18. return 0;
  19. }
  20. }

4.5 获取文件的名字,不包含后缀

  1. /**
  2. * 获取文件的名字
  3. * 不包含后缀
  4. */
  5. public static String getFileName(String url) {
  6. int start = url.lastIndexOf("/");
  7. int end = url.lastIndexOf(".");
  8. if (start != -1 && end != -1) {
  9. return url.substring(start + 1, end);
  10. } else {
  11. return null;
  12. }
  13. }

4.6 获取文件的名字,包含后缀

  1. /**
  2. * 获取文件的名字
  3. * 保留文件名及后缀
  4. */
  5. public static String getFileNameWithSuffix(String pathandname) {
  6. int start = pathandname.lastIndexOf("/");
  7. if (start != -1) {
  8. return pathandname.substring(start + 1);
  9. } else {
  10. return null;
  11. }
  12. }

4.7 重命名文件

  1. /**
  2. * 重命名文件.
  3. */
  4. public static boolean renameFile(String resFilePath, String newFilePath) {
  5. File resFile = new File(resFilePath);
  6. File newFile = new File(newFilePath);
  7. return resFile.renameTo(newFile);
  8. }

4.8 读取文件内容到字符串

  1. /**
  2. * 读取文件内容到字符串
  3. * @param strFilePath
  4. * @return
  5. */
  6. public static String ReadTxtFile(String strFilePath) {
  7. StringBuffer stringBuffer = new StringBuffer();
  8. try {
  9. //打开文件
  10. File file = new File(strFilePath);
  11. //如果path是传递过来的参数,可以做一个非目录的判断
  12. if (!file.exists()) {
  13. file.createNewFile();
  14. }
  15. InputStream instream = new FileInputStream(file);
  16. if (instream != null) {
  17. InputStreamReader inputreader = null;
  18. inputreader = new InputStreamReader(instream, "utf-8");
  19. BufferedReader buffreader = new BufferedReader(inputreader);
  20. String line;
  21. //分行读取
  22. while ((line = buffreader.readLine()) != null) {
  23. stringBuffer.append(line + "\n");
  24. }
  25. instream.close();
  26. }
  27. } catch (Exception e) {
  28. }
  29. return stringBuffer.toString();
  30. }

4.9 保存字符串到文件

  1. /**
  2. * 保存字符串到文件.
  3. */
  4. public static String saveFilePlt(Context mContext,String content, String fileName) {
  5. try {
  6. String dir = mContext.getExternalFilesDir("").getAbsolutePath()
  7. + File.separator + "lensun";
  8. (new File(dir)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
  9. File fs = new File(dir,fileName+".plt");
  10. FileOutputStream os = new FileOutputStream(fs);
  11. os.write(content.getBytes());
  12. os.flush();
  13. os.close();
  14. return fs.getAbsolutePath();
  15. } catch (IOException e) {
  16. e.printStackTrace();
  17. }
  18. return null;
  19. }

4.10 压缩并保存Bitmap

  1. /**
  2. * 压缩并保存Bitmap
  3. * @param context
  4. * @param bitmap
  5. * @return
  6. */
  7. public static File saveToImage(Context context, Bitmap bitmap) {
  8. FileOutputStream fos;
  9. try {
  10. // SD卡根目录
  11. File dir = context.getExternalFilesDir("lensun");
  12. if (!dir.exists()) {
  13. dir.mkdirs();
  14. }
  15. File picFile = new File(dir, "fengmian" + ".jpg");
  16. if(picFile.isFile()&&picFile.exists()){
  17. picFile.delete();
  18. }
  19. fos = new FileOutputStream(picFile);
  20. ByteArrayOutputStream imageByteArray = new ByteArrayOutputStream();
  21. bitmap.compress(Bitmap.CompressFormat.JPEG, 80, imageByteArray);
  22. byte[] imageData = imageByteArray.toByteArray();
  23. fos.write(imageData);
  24. fos.flush();
  25. fos.close();
  26. bitmap.recycle();
  27. return picFile;
  28. } catch (Exception e) {
  29. e.printStackTrace();
  30. }
  31. return null;
  32. }

4.11 压缩并保存指定分辨率的Bitmap

  1. /**
  2. * 不压缩,改变jpg分辨,保存图片
  3. * @param bitmap
  4. * @return
  5. */
  6. public File saveToImage(Bitmap bitmap) {
  7. FileOutputStream fos;
  8. try {
  9. // SD卡根目录
  10. File dir = context.getExternalFilesDir("print");
  11. if (!dir.exists()) {
  12. dir.mkdirs();
  13. }
  14. File picFile = new File(dir, type + "_" + System.currentTimeMillis() + ".jpg");
  15. fos = new FileOutputStream(picFile);
  16. ByteArrayOutputStream imageByteArray = new ByteArrayOutputStream();
  17. bitmap.compress(Bitmap.CompressFormat.JPEG, 100, imageByteArray);
  18. byte[] imageData = imageByteArray.toByteArray();
  19. //300 will be the dpi of the bitmap
  20. setDpi(imageData, dipValue);
  21. fos.write(imageData);
  22. fos.flush();
  23. fos.close();
  24. bitmap.recycle();
  25. return picFile;
  26. } catch (Exception e) {
  27. e.printStackTrace();
  28. }
  29. return null;
  30. }
  31. //设置图片分辨率
  32. public void setDpi(byte[] imageData, int dpi) {
  33. imageData[13] = 1;
  34. imageData[14] = (byte) (dpi >> 8);
  35. imageData[15] = (byte) (dpi & 0xff);
  36. imageData[16] = (byte) (dpi >> 8);
  37. imageData[17] = (byte) (dpi & 0xff);
  38. }

4.12 获取视频第一帧封面

  1. /**
  2. * 获取视频第一帧封面
  3. * @param filePath
  4. * @param kind
  5. * @return
  6. */
  7. public static Bitmap createVideoThumbnail(String filePath, int kind) {
  8. Bitmap bitmap = null;
  9. MediaMetadataRetriever retriever = new MediaMetadataRetriever();
  10. try {
  11. if (filePath.startsWith("http://")
  12. || filePath.startsWith("https://")
  13. || filePath.startsWith("widevine://")) {
  14. retriever.setDataSource(filePath, new Hashtable<String, String>());
  15. } else {
  16. retriever.setDataSource(filePath);
  17. }
  18. bitmap = retriever.getFrameAtTime(0, MediaMetadataRetriever.OPTION_CLOSEST_SYNC); //retriever.getFrameAtTime(-1);
  19. } catch (IllegalArgumentException ex) {
  20. // Assume this is a corrupt video file
  21. ex.printStackTrace();
  22. } catch (RuntimeException ex) {
  23. // Assume this is a corrupt video file.
  24. ex.printStackTrace();
  25. } finally {
  26. try {
  27. retriever.release();
  28. } catch (RuntimeException ex) {
  29. // Ignore failures while cleaning up.
  30. ex.printStackTrace();
  31. }
  32. }
  33. if (bitmap == null) {
  34. return null;
  35. }
  36. if (kind == MediaStore.Images.Thumbnails.MINI_KIND) {//压缩图片 开始处
  37. // Scale down the bitmap if it's too large.
  38. int width = bitmap.getWidth();
  39. int height = bitmap.getHeight();
  40. int max = Math.max(width, height);
  41. if (max > 512) {
  42. float scale = 512f / max;
  43. int w = Math.round(scale * width);
  44. int h = Math.round(scale * height);
  45. bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true);
  46. }//压缩图片 结束处
  47. }
  48. return bitmap;
  49. }

五 手机或者应用信息

5.1 获取应用版本号

  1. /**
  2. * 获取版本号
  3. *
  4. * @return 当前应用的版本号
  5. */
  6. public static int getVersionCode(Context context) {
  7. try {
  8. PackageManager manager = context.getPackageManager();
  9. PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
  10. int versionCode = info.versionCode;
  11. return versionCode;
  12. } catch (Exception e) {
  13. e.printStackTrace();
  14. return 0;
  15. }
  16. }

5.2 获取应用版本名字

  1. /**
  2. * 获取版本名字
  3. *
  4. * @return 当前应用的版本号
  5. */
  6. public static String getVersion(Context context) {
  7. try {
  8. PackageManager manager = context.getPackageManager();
  9. PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
  10. String version = info.versionName;
  11. return version;
  12. } catch (Exception e) {
  13. e.printStackTrace();
  14. return "0.0";
  15. }
  16. }

5.3 获取应用名字

  1. /**
  2. * 获取apk的名称
  3. * @param context 上下文
  4. * @return String
  5. */
  6. public static String getAppName(Context context) {
  7. try {
  8. PackageManager e = context.getPackageManager();
  9. PackageInfo packageInfo = e.getPackageInfo(context.getPackageName(), 0);
  10. int labelRes = packageInfo.applicationInfo.labelRes;
  11. return context.getResources().getString(labelRes);
  12. } catch (NameNotFoundException var4) {
  13. var4.printStackTrace();
  14. return "unKnown";
  15. }
  16. }

5.4 获取应用图标

  1. /**
  2. * 获取应用图标
  3. * @param context
  4. * @param packageName
  5. * @return
  6. */
  7. public static Drawable getAppIcon(Context context, String packageName) {
  8. PackageManager pm = context.getPackageManager();
  9. Drawable appIcon = null;
  10. try {
  11. ApplicationInfo applicationInfo = pm.getApplicationInfo(packageName, 0);
  12. appIcon = applicationInfo.loadIcon(pm);
  13. } catch (PackageManager.NameNotFoundException e) {
  14. e.printStackTrace();
  15. }
  16. return appIcon;
  17. }

5.5 获取应用root权限

  1. /**
  2. * 获得root权限
  3. * @param context
  4. * @return
  5. */
  6. public static boolean getRootPermission(Context context) {
  7. String packageCodePath = context.getPackageCodePath();
  8. Process process = null;
  9. DataOutputStream os = null;
  10. try {
  11. String cmd = "chmod 777 " + packageCodePath;
  12. process = Runtime.getRuntime().exec("su");
  13. os = new DataOutputStream(process.getOutputStream());
  14. os.writeBytes(cmd + "\n");
  15. os.writeBytes("exit\n");
  16. os.flush();
  17. process.waitFor();
  18. } catch (Exception e) {
  19. return false;
  20. } finally {
  21. try {
  22. if (os != null) {
  23. os.close();
  24. }
  25. process.destroy();
  26. } catch (Exception e) {
  27. e.printStackTrace();
  28. }
  29. }
  30. return true;
  31. }

5.6 判断某个服务是否运行

  1. /**
  2. * 服务是否在运行
  3. * @param context
  4. * @param className
  5. * @return
  6. */
  7. public static boolean isServiceRunning(Context context, String className) {
  8. boolean isRunning = false;
  9. ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
  10. List<RunningServiceInfo> servicesList = activityManager.getRunningServices(Integer.MAX_VALUE);
  11. for (RunningServiceInfo si : servicesList) {
  12. if (className.equals(si.service.getClassName())) {
  13. isRunning = true;
  14. }
  15. }
  16. return isRunning;
  17. }

5.7 获取手机品牌,固件等系统信息

  1. /**
  2. * 手机信息
  3. * 需要 <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
  4. *
  5. * @return
  6. */
  7. public static String printSystemInfo() {
  8. Date date = new Date(System.currentTimeMillis());
  9. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  10. String time = dateFormat.format(date);
  11. StringBuilder sb = new StringBuilder();
  12. sb.append("_______ 系统信息 ").append(time).append(" ______________");
  13. sb.append("\nID :").append(Build.ID); // Either a changelist number, or a label like "M4-rc20".
  14. sb.append("\nBRAND :").append(Build.BRAND); //品牌名 如 Xiaomi
  15. sb.append("\nMODEL :").append(Build.MODEL); //手机型号
  16. sb.append("\nRELEASE :").append(Build.VERSION.RELEASE); //frimware版本(系统版本) 如:2.1-update1
  17. sb.append("\nSDK :").append(Build.VERSION.SDK); //sdk版本号
  18. sb.append("\n_______ OTHER _______");
  19. sb.append("\nBOARD :").append(Build.BOARD); //基板名 如 MSM8974
  20. sb.append("\nPRODUCT :").append(Build.PRODUCT); //The name of the overall product.
  21. sb.append("\nDEVICE :").append(Build.DEVICE); //品牌型号名,如小米4对应cancro
  22. sb.append("\nFINGERPRINT :").append(Build.FINGERPRINT); //包含制造商,设备名,系统版本等诸多信息 如 Xiaomi/cancro_wc_lte/cancro:6.0.1/MMB29M/V8.1.3.0.MXDCNDI:user/release-keys
  23. sb.append("\nHOST :").append(Build.HOST); // 如 c3-miui-ota-bd43
  24. sb.append("\nTAGS :").append(Build.TAGS); //Comma-separated tags describing the build, like "unsigned,debug".
  25. sb.append("\nTYPE :").append(Build.TYPE); //The type of build, like "user" or "eng".
  26. sb.append("\nTIME :").append(Build.TIME); //当前时间,毫秒值
  27. sb.append("\nINCREMENTAL :").append(Build.VERSION.INCREMENTAL);
  28. sb.append("\n_______ CUPCAKE-3 _______");
  29. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {
  30. sb.append("\nDISPLAY :").append(Build.DISPLAY); // 如 MMB29M
  31. }
  32. sb.append("\n_______ DONUT-4 _______");
  33. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.DONUT) {
  34. sb.append("\nSDK_INT :").append(Build.VERSION.SDK_INT);
  35. sb.append("\nMANUFACTURER :").append(Build.MANUFACTURER); // The manufacturer of the product/hardware. 如 Xiaomi
  36. sb.append("\nBOOTLOADER :").append(Build.BOOTLOADER); //The system bootloader version number. 如
  37. sb.append("\nCPU_ABI :").append(Build.CPU_ABI); // 如 armeabi-v7a
  38. sb.append("\nCPU_ABI2 :").append(Build.CPU_ABI2); // 如 armeabi
  39. sb.append("\nHARDWARE :").append(Build.HARDWARE); // The name of the hardware (from the kernel command line or /proc). 如 qcom
  40. sb.append("\nUNKNOWN :").append(Build.UNKNOWN); // Value used for when a build property is unknown.
  41. sb.append("\nCODENAME :").append(Build.VERSION.CODENAME);
  42. }
  43. sb.append("\n_______ GINGERBREAD-9 _______");
  44. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
  45. sb.append("\nSERIAL :").append(Build.SERIAL); // A hardware serial number, if available. 如 abcdefgh
  46. }
  47. return sb.toString();
  48. }

5.8 获取IP地址

  1. /**
  2. * 获得IP地址,分为两种情况,一是wifi下,二是移动网络下,得到的ip地址是不一样的
  3. * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  4. */
  5. public static String getIPAddress(Context context) {
  6. NetworkInfo info = ((ConnectivityManager) context
  7. .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
  8. if (info != null && info.isConnected()) {
  9. if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
  10. try {
  11. for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
  12. NetworkInterface intf = en.nextElement();
  13. for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
  14. InetAddress inetAddress = enumIpAddr.nextElement();
  15. if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
  16. return inetAddress.getHostAddress();
  17. }
  18. }
  19. }
  20. } catch (SocketException e) {
  21. e.printStackTrace();
  22. }
  23. } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
  24. WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
  25. WifiInfo wifiInfo = wifiManager.getConnectionInfo();
  26. //调用方法将int转换为地址字符串
  27. String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
  28. return ipAddress;
  29. }
  30. } else {
  31. //当前无网络连接,请在设置中打开网络
  32. }
  33. return null;
  34. }
  35. /**
  36. * 将得到的int类型的IP转换为String类型
  37. *
  38. * @param ip
  39. * @return
  40. */
  41. private static String intIP2StringIP(int ip) {
  42. return (ip & 0xFF) + "." +
  43. ((ip >> 8) & 0xFF) + "." +
  44. ((ip >> 16) & 0xFF) + "." +
  45. (ip >> 24 & 0xFF);
  46. }

5.9 判断是否鸿蒙系统

  1. /**
  2. * 是否为鸿蒙系统
  3. * @return true为鸿蒙系统
  4. */
  5. public static boolean isHarmonyOs() {
  6. try {
  7. Class<?> buildExClass = Class.forName("com.huawei.system.BuildEx");
  8. Object osBrand = buildExClass.getMethod("getOsBrand").invoke(buildExClass);
  9. return "Harmony".equalsIgnoreCase(osBrand.toString());
  10. } catch (Throwable x) {
  11. return false;
  12. }
  13. }

5.10 获取鸿蒙系统版本号

  1. /**
  2. * 获取鸿蒙系统版本号
  3. * @return 版本号
  4. */
  5. public static String getHarmonyVersion() {
  6. return getProp("hw_sc.build.platform.version", "");
  7. }
  8. /**
  9. * 获取属性
  10. * @param property
  11. * @param defaultValue
  12. * @return
  13. */
  14. private static String getProp(String property, String defaultValue) {
  15. try {
  16. Class spClz = Class.forName("android.os.SystemProperties");
  17. Method method = spClz.getDeclaredMethod("get", String.class);
  18. String value = (String) method.invoke(spClz, property);
  19. if (TextUtils.isEmpty(value)) {
  20. return defaultValue;
  21. }
  22. return value;
  23. } catch (Throwable e) {
  24. e.printStackTrace();
  25. }
  26. return defaultValue;
  27. }
  28. /**
  29. * 获得鸿蒙系统版本号(含小版本号,实际上同Android的android.os.Build.DISPLAY)
  30. * @return 版本号
  31. */
  32. public static String getHarmonyDisplayVersion() {
  33. return android.os.Build.DISPLAY;
  34. }

六 地图导航工具类

6.1 主流卫星地图坐标系分类

  • WGS84 :地理坐标系统,Google Earth和中国外的Google Map使用,另外,目前基本上所有定位空间位置的设备都使用这种坐标系统,例如手机的GPS系统。
  • GCJ-02:投影坐标系统,也就是我们平常所说的火星坐标系,Google Map中国、高德和腾讯好像使用,这个是中国自己在WGS84基础上加密而成,目的显而易见。
  • BD09:投影坐标系统,百度地图使用,在GCJ-02基础上二次加密而成。

6.2 检测程序是否安装

  1. /**
  2. * 检测程序是否安装
  3. *
  4. * @param packageName
  5. * @return
  6. */
  7. public boolean isInstalled(String packageName) {
  8. PackageManager manager = mContext.getPackageManager();
  9. //获取所有已安装程序的包信息
  10. List<PackageInfo> installedPackages = manager.getInstalledPackages(0);
  11. if (installedPackages != null) {
  12. for (PackageInfo info : installedPackages) {
  13. if (info.packageName.equals(packageName))
  14. return true;
  15. }
  16. }
  17. return false;
  18. }

6.3  跳转到百度地图

  1. /**
  2. * 跳转百度地图
  3. */
  4. public void goToBaiduMap() {
  5. if (!isInstalled("com.baidu.BaiduMap")) {//是否安装百度
  6. ToastHelp.showToast("请安装百度地图客户端");
  7. return;
  8. }
  9. double mlat = Double.parseDouble(latString);
  10. double mLon = Double.parseDouble(lngString);
  11. //高德坐标转换
  12. double[] locationArray = map_tx2bd(mlat, mLon);
  13. mlat = locationArray[0];
  14. mLon = locationArray[1];
  15. //导航
  16. Intent intent = new Intent();
  17. StringBuffer stringBuffer = new StringBuffer("baidumap://map/direction?destination=");
  18. // stringBuffer.append("latlng:").append("39.98871").append(",").append("116.43234")
  19. stringBuffer.append("latlng:").append(mlat).append(",").append(mLon)
  20. .append("|name:").append(Address)
  21. .append("&mode=").append("driving")
  22. .append("&coord_type=").append("bd09ll")
  23. .append("&mode=").append("driving")
  24. .append("&src=").append("com.baidu.BaiduMap");
  25. Log.e(TAG, "goToBaiduMap: " + stringBuffer.toString());
  26. // String url="baidumap://map/direction?destination=西直门|&coord_type=bd09ll&mode=transit&sy=3&index=0&target=1&src="+mContext.getPackageName();
  27. intent.setData(Uri.parse(stringBuffer.toString()));
  28. mContext.startActivity(intent); // 启动调用
  29. }

 6.4  跳转到高德地图

  1. /**
  2. * 跳转高德地图
  3. */
  4. public void goToGaodeMap() {
  5. if (!isInstalled("com.autonavi.minimap")) {//是否安装高德
  6. ToastHelp.showToast("请安装高德地图客户端");
  7. return;
  8. }
  9. double mlat = Double.parseDouble(latString);
  10. double mLon = Double.parseDouble(lngString);
  11. StringBuffer stringBuffer = new StringBuffer("amapuri://route/plan/?");
  12. stringBuffer.append("&dlat=").append(mlat)
  13. .append("&dlon=").append(mLon)
  14. .append("&dname=" + Address)
  15. .append("&dev=").append(0)
  16. .append("&t=").append(0);
  17. Intent intent = new Intent("android.intent.action.VIEW", Uri.parse(stringBuffer.toString()));
  18. intent.setPackage("com.autonavi.minimap");
  19. mContext.startActivity(intent);
  20. }

 6.5 跳转到腾讯地图

  1. /**
  2. * 跳转腾讯地图
  3. */
  4. public void goToTencentMap() {
  5. if (!isInstalled("com.tencent.map")) {//是否安装腾讯
  6. ToastHelp.showToast("请安装腾讯地图客户端");
  7. return;
  8. }
  9. double mlat = Double.parseDouble(latString);
  10. double mLon = Double.parseDouble(lngString);
  11. StringBuffer stringBuffer = new StringBuffer("qqmap://map/routeplan?type=drive")
  12. .append("&tocoord=").append(mlat).append(",").append(mLon).append("&to=" + Address);
  13. Intent intent = new Intent("android.intent.action.VIEW", Uri.parse(stringBuffer.toString()));
  14. mContext.startActivity(intent);
  15. }

6.6 坐标转换,腾讯地图转换成百度地图坐标

  1. /**
  2. * 坐标转换,腾讯地图转换成百度地图坐标
  3. *
  4. * @param lat 腾讯纬度
  5. * @param lon 腾讯经度
  6. * @return 返回结果:经度,纬度
  7. */
  8. public static double[] map_tx2bd(double lat, double lon) {
  9. double bd_lat;
  10. double bd_lon;
  11. double x_pi = 3.14159265358979324;
  12. double x = lon, y = lat;
  13. double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
  14. double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
  15. bd_lon = z * Math.cos(theta) + 0.0065;
  16. bd_lat = z * Math.sin(theta) + 0.006;
  17. System.out.println("bd_lat:" + bd_lat);
  18. System.out.println("bd_lon:" + bd_lon);
  19. return new double[]{bd_lat, bd_lon};
  20. }

七,加密解密算法

7.1 AES加密解密

  1. public class AESUitls {
  2. /*
  3. * 加密用的Key 可以用26个字母和数字组成 使用AES-128-CBC加密模式,key需要为16位。
  4. */
  5. private static final String CipherMode = "AES/CBC/PKCS7Padding";
  6. private static final String SecretKey = LogInterceptor.SECRETKEY;
  7. private static final String SecretIV = LogInterceptor.SECRETIV;
  8. private static final Integer IVSize = 16;
  9. private static final String EncryptAlg = "AES";
  10. private static final String Encode = "UTF-8";
  11. private static final String Key_Encode = "UTF-8";
  12. /**
  13. * 创建密钥
  14. *
  15. * @return
  16. */
  17. private static SecretKeySpec createKey() {
  18. try {
  19. byte[] data = SecretKey.getBytes(Encode);
  20. return new SecretKeySpec(data, EncryptAlg);
  21. } catch (Exception e) {
  22. e.printStackTrace();
  23. }
  24. return null;
  25. }
  26. /**
  27. * 创建16位向量: 不够则用0填充
  28. *
  29. * @return
  30. */
  31. private static IvParameterSpec createIV() {
  32. byte[] data = null;
  33. try {
  34. data = SecretIV.getBytes(Encode);
  35. } catch (UnsupportedEncodingException e) {
  36. e.printStackTrace();
  37. }
  38. return new IvParameterSpec(data);
  39. }
  40. /**
  41. * 加密:有向量16位,结果转base64
  42. *
  43. * @param context
  44. * @return
  45. */
  46. public static String encrypt(String context) {
  47. try {
  48. byte[] content = context.getBytes(Encode);
  49. SecretKeySpec key = createKey();
  50. Cipher cipher = Cipher.getInstance(CipherMode);
  51. cipher.init(Cipher.ENCRYPT_MODE, key, createIV());
  52. byte[] data = cipher.doFinal(content);
  53. String result = Base64.encodeToString(data, Base64.NO_WRAP);
  54. return result;
  55. } catch (Exception e) {
  56. e.printStackTrace();
  57. }
  58. return null;
  59. }
  60. /**
  61. * 解密
  62. *
  63. * @param context
  64. * @return
  65. */
  66. public static String decrypt(String context) {
  67. try {
  68. byte[] data = Base64.decode(context, Base64.DEFAULT);
  69. SecretKeySpec key = createKey();
  70. Cipher cipher = Cipher.getInstance(CipherMode);
  71. cipher.init(Cipher.DECRYPT_MODE, key, createIV());
  72. byte[] content = cipher.doFinal(data);
  73. String result = new String(content, Encode);
  74. return result;
  75. } catch (Exception e) {
  76. e.printStackTrace();
  77. }
  78. return null;
  79. }
  80. }

八 富文本使用

8.1 类似于金额格式化效果 , ¥100.20显示为 ¥小字体,100大字体,20小字体

  1. /**
  2. *
  3. * @param values ¥100.20
  4. * @param textsize
  5. * @param smallsize
  6. * @param isBold
  7. * @return
  8. */
  9. public static SpannableString changTVsize(String values, int textsize, int smallsize, boolean isBold) {
  10. String value = subZeroAndDot(values);
  11. SpannableString spannableString = new SpannableString(value);
  12. AbsoluteSizeSpan sizeSpan01 = new AbsoluteSizeSpan(textsize, true);
  13. AbsoluteSizeSpan sizeSpan03 = new AbsoluteSizeSpan(smallsize, true);
  14. AbsoluteSizeSpan sizeSpan02 = new AbsoluteSizeSpan(smallsize, true);
  15. if (value.contains(".")) {
  16. spannableString.setSpan(sizeSpan02, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  17. spannableString.setSpan(sizeSpan03, value.indexOf("."), value.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  18. spannableString.setSpan(sizeSpan01, 1, value.indexOf("."), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  19. } else {
  20. spannableString.setSpan(sizeSpan03, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  21. spannableString.setSpan(sizeSpan01, 1, value.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  22. }
  23. if (isBold) {
  24. spannableString.setSpan(new StyleSpan(Typeface.BOLD), 0, value.length(),
  25. Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  26. }
  27. return spannableString;
  28. }

8.2 查找匹配标红效果

  1. SpannableStringBuilder stringBuilder = new SpannableStringBuilder(deliveryTime);
  2. //发货时间字体红色
  3. Matcher matcherPerson = Pattern.compile(deliveryTimeFormat).matcher(stringBuilder);
  4. while (matcherPerson.find()) {
  5. ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#E02020"));
  6. stringBuilder.setSpan(colorSpan, matcherPerson.start(), matcherPerson.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  7. }

8.3 文字不同颜色富文本拼接效果 ForegroundColorSpan,AbsoluteSizeSpan

  1. SpannableString spannableString = new SpannableString("根据监管政策要求");
  2. spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#333333")), 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  3. spannableString.setSpan(new AbsoluteSizeSpan(13, true), 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  4. SpannableString spannableString2 = new SpannableString("单笔订单不能超过5000元。\n");
  5. spannableString2.setSpan(new ForegroundColorSpan(Color.parseColor("#ed291b")), 0, spannableString2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  6. spannableString2.setSpan(new AbsoluteSizeSpan(13, true), 0, spannableString2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  7. SpannableString spannableString3 = new SpannableString("中国海关规定");
  8. spannableString3.setSpan(new ForegroundColorSpan(Color.parseColor("#333333")), 0, spannableString3.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  9. spannableString3.setSpan(new AbsoluteSizeSpan(13, true), 0, spannableString3.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  10. SpannableString spannableString4 = new SpannableString("每人每年海淘商品限额26000元人民币,");
  11. spannableString4.setSpan(new ForegroundColorSpan(Color.parseColor("#ed291b")), 0, spannableString4.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  12. spannableString4.setSpan(new AbsoluteSizeSpan(13, true), 0, spannableString4.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  13. SpannableString spannableString5 = new SpannableString("如超出此限额会导致清关失败,请注意个人额度情况,您可以进入【跨境电子商务个人额度查询】网站进行查询。");
  14. spannableString5.setSpan(new ForegroundColorSpan(Color.parseColor("#333333")), 0, spannableString5.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  15. spannableString5.setSpan(new AbsoluteSizeSpan(13, true), 0, spannableString5.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  16. SpannableStringBuilder spannableStringBuilder=new SpannableStringBuilder();
  17. spannableStringBuilder.append(spannableString).append(spannableString2).append(spannableString3).append(spannableString4).append(spannableString5);
  18. mBinding.tvContent.setText(spannableStringBuilder);

8.4 图片富文本效果 ImageSpan 

  1. private SpannableStringBuilder getContent(String title,String content){
  2. SpannableString spannableString = new SpannableString(title+"\n");
  3. spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#333333")), 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  4. spannableString.setSpan(new AbsoluteSizeSpan(14, true), 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  5. SpannableString spannableImage = new SpannableString("间距2\n");
  6. Drawable drawable=getResources().getDrawable(R.drawable.space_hight_2);
  7. drawable.setBounds(0,0, ScreenUtils.getScreenWidth(this), (int) ScreenUtils.dp2px(this,2f));
  8. ImageSpan imageSpan=new ImageSpan(drawable,ImageSpan.ALIGN_BASELINE);
  9. spannableImage.setSpan(imageSpan,0, spannableImage.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  10. SpannableString spannableString2 = new SpannableString(content+"\n");
  11. spannableString2.setSpan(new ForegroundColorSpan(Color.parseColor("#999999")), 0, spannableString2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  12. spannableString2.setSpan(new AbsoluteSizeSpan(12, true), 0, spannableString2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  13. SpannableString spannableImage2 = new SpannableString("间距7\n");
  14. Drawable drawable2=getResources().getDrawable(R.drawable.space_hight_2);
  15. drawable2.setBounds(0,0,ScreenUtils.getScreenWidth(this), (int) ScreenUtils.dp2px(this,7f));
  16. ImageSpan imageSpan2=new ImageSpan(drawable2,ImageSpan.ALIGN_BASELINE);
  17. spannableImage2.setSpan(imageSpan2,0, spannableImage2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  18. SpannableStringBuilder spannableStringBuilder=new SpannableStringBuilder();
  19. spannableStringBuilder.append(spannableString).append(spannableImage).append(spannableString2).append(spannableImage2);
  20. return spannableStringBuilder;
  21. }

8.5 用Html.fromHtml简单变色

  1. String str1 = "抱歉,没有找到商品,为您推荐<font color = '#333333'>" + "“" + dataDTO.correctWord + "”" + "</font>的搜索结果";
  2. CharSequence charSequence;
  3. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
  4. charSequence = Html.fromHtml(str1, Html.FROM_HTML_MODE_LEGACY);
  5. } else {
  6. charSequence = Html.fromHtml(str1);
  7. }
  8. tvNoData.setText(charSequence);

九 Webview加载文本,统一设置样式,间距

  1. public static String getHtmlData(String bodyHTML) {
  2. String head = "<head>" +
  3. "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " +
  4. "<style>div,p,img{max-width: 100%; width: 100% !important; height: auto !important;}" +
  5. "body {" +
  6. "margin-right:8px;" +//限定网页中的文字右边距为15px(可根据实际需要进行行管屏幕适配操作)
  7. "margin-left:8px;" +//限定网页中的文字左边距为15px(可根据实际需要进行行管屏幕适配操作)
  8. "margin-top:8px;" +//限定网页中的文字上边距为15px(可根据实际需要进行行管屏幕适配操作)
  9. "font-size:16px;" +//限定网页中文字的大小为40px,请务必根据各种屏幕分辨率进行适配更改
  10. "word-wrap:break-word;" +//允许自动换行(汉字网页应该不需要这一属性,这个用来强制英文单词换行,类似于word/wps中的西文换行)
  11. "}" +
  12. "p { margin: 0; }" +
  13. "</style>" +
  14. "</head>";
  15. return "<html>" + head + "<body>" + bodyHTML + "</body><ml>";
  16. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/255547?site
推荐阅读
相关标签
  

闽ICP备14008679号