赞
踩
一 时间格式化
1.1 时间戳按指定格式转化为日期
- /**
- * 时间戳按指定格式转化为日期(String)
- * @param timestamp
- * @return
- */
- public static String convertTimestampDate(Long timestamp) {
- Date date = new Date(timestamp);
- SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
- return format.format(date);
- }
1.2 日期按指定格式转化为时间戳
- /**
- * 指定格式时间字符串转时间戳
- * @param dateString 2018-11-07 13:42:03,
- * @return 1541569323000
- */
- public static long convertStringToTimestamp(String dateString) {
-
- SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:s");
- Date date = new Date();
- try {
- date = dateFormat.parse(dateString);
- } catch (ParseException e) {
- e.printStackTrace();
- }
- return date.getTime();
- }
1.3 总时长秒数格式化为n小时n分钟n秒
- /**
- * 总时长秒数格式化为n小时n分钟n秒
- * @param ms
- * @return
- */
- public static String reSetStringTime(long ms) {
- int hour = (int) (ms / (1000 * 60 * 60));
- int minute = (int) ((ms % (1000 * 60 * 60)) / (1000 * 60));
- int second = (int) ((ms % (1000 * 60)) / 1000);
- //int millisecond = (int)(ms % 1000);
-
- String hourString = hour < 10 ? "0" + hour : String.valueOf(hour);
- String minuteString = minute < 10 ? "0" + minute : String.valueOf(minute);
- String secondString = second < 10 ? "0" + second : String.valueOf(second);
- return hourString + "小时" + minuteString + "分" + secondString + "秒";
- }
1.4 根据当前日期时间戳获得是星期几
- /**
- * 根据当前日期时间戳获得是星期几
- * time=yyyy-MM-dd
- * @return
- */
- public static String getWeek(String time) {
- String Week = "";
- SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
- Calendar c = Calendar.getInstance();
- try {
- c.setTime(format.parse(time));
- } catch (ParseException e) {
- e.printStackTrace();
- }
-
- int wek=c.get(Calendar.DAY_OF_WEEK);
-
- if (wek == 1) {
- Week += "星期日";
- }
- if (wek == 2) {
- Week += "星期一";
- }
- if (wek == 3) {
- Week += "星期二";
- }
- if (wek == 4) {
- Week += "星期三";
- }
- if (wek == 5) {
- Week += "星期四";
- }
- if (wek == 6) {
- Week += "星期五";
- }
- if (wek == 7) {
- Week += "星期六";
- }
- return Week;
- }
1.5 时间戳判断是否为今年
- /**
- * 时间戳判断是否为今年
- */
- public static boolean isCurrentYear(Long timeStamp) {
- Calendar todayCalendar = Calendar.getInstance();
- Calendar calendar = Calendar.getInstance();
- calendar.setTimeInMillis(timeStamp);
- if (calendar.get(Calendar.YEAR) == (todayCalendar.get(Calendar.YEAR))) {
- return true;
- }
- return false;
- }
1.6 时间戳判断是否为今天
- /**
- * 时间戳判断是否为今天
- */
- public static boolean isToday(Long timeStamp) {
- Calendar todayCalendar = Calendar.getInstance();
- Calendar calendar = Calendar.getInstance();
- calendar.setTimeInMillis(timeStamp);
- if (calendar.get(Calendar.YEAR) == (todayCalendar.get(Calendar.YEAR))) {
- int diffDay = todayCalendar.get(Calendar.DAY_OF_YEAR) - calendar.get(Calendar.DAY_OF_YEAR);
- return diffDay == 0;
- }
- return false;
- }
二 价格处理,价格格式化
2.1 价格格式化不含小数
- //不含小数
- public static String decimal(String number) {
- BigDecimal a = new BigDecimal(number);
- DecimalFormat df = new DecimalFormat("##0");
- return subZeroAndDot(df.format(a));
- }
2.2 不五入保留两位小数
- //保留两位为位小数
- public static String decimalFloatDouble(double number) {
- BigDecimal bigDecimal = BigDecimal.valueOf(number).setScale(2,RoundingMode.DOWN);
- return subZeroAndDot(bigDecimal.toString());
- }
2.3 使用java正则表达式去掉多余的.与0
- /**
- * 使用java正则表达式去掉多余的.与0
- * @param s
- * @return
- */
- public static String subZeroAndDot(String s) {
- if (s == null) {
- return "";
- }
- if (s.indexOf(".") > 0) {
- s = s.replaceAll("0+?$", "");//去掉多余的0
- s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
- }
- return s;
- }
2.4 精准加减乘除计算
- /**
- * 加法
- */
- public static String add(String parms1, String param2) {
- return new BigDecimal(parms1).add(new BigDecimal(param2)).toString();
- }
-
- /**
- * 减法
- */
- public static String subtract(String parms1, String param2) {
- return new BigDecimal(parms1).subtract(new BigDecimal(param2)).toString();
- }
-
- /**
- * 乘法
- */
- public static String multiply(String parms1, String param2) {
- return new BigDecimal(parms1).multiply(new BigDecimal(param2)).toString();
- }
-
-
-
- /**
- * 除法
- * digit:小数位数,经尝试最大17位,超过17位无效,保险起见可设20位
- * roundType:四舍五入或者向下取整
- */
- public static String divide(String parms1, String param2) {
- return new BigDecimal(parms1).divide(new BigDecimal(param2), 20, BigDecimal.ROUND_DOWN).toString();
- }
2.5 销量格式化,大于10000显示1万+
- /**
- * 销售量格式化
- * 销量小于万位:展示实际数量
- * 销量大于万位:取万位和千位保留一位小数 无四舍五入等规则 例如1.2+万 2.3+万
- * 销量大于10w :直接显示10万+
- */
- public static String saleFormat(int number){
- if(number>10*10000){
- // 1w+ 格式化
- return "10万+";
- }else if(number>10000){
- return String.format(Locale.getDefault(), "%.1f+万", number / 10000f);
- }else {
- return String.valueOf(number);
- }
- }
三 单位间的相互转换
3.1 dp与px单位的相互转换
- /**
- * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
- */
- public static int dip2px(Context context, float dpValue) {
- final float scale = context.getResources().getDisplayMetrics().density;
- return (int) (dpValue * scale + 0.5f);
- }
-
- /**
- * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
- */
- public static int px2dip(Context context, float pxValue) {
- final float scale = context.getResources().getDisplayMetrics().density;
- return (int) (pxValue / scale + 0.5f);
- }
3.2 获取状态栏高度
- /**
- * 状态栏高度
- */
- public static int getStatusBarHeight(Activity activity) {
- int resourceId = activity.getResources().getIdentifier("status_bar_height", "dimen", "android");
- return activity.getResources().getDimensionPixelSize(resourceId);
- }
3.3 获取屏幕宽高
- /**
- * 返回屏幕的宽度
- */
- public static int getScreenWidth(Activity activity) {
- DisplayMetrics displayMetrics = new DisplayMetrics();
- activity.getWindowManager().getDefaultDisplay().getRealMetrics(displayMetrics);
- return displayMetrics.widthPixels;
- }
-
- /**
- * 返回包括虚拟键在内的总的屏幕高度
- * 即使虚拟按键显示着,也会加上虚拟按键的高度
- */
- public static int getScreenHeight(Activity activity) {
- DisplayMetrics displayMetrics = new DisplayMetrics();
- activity.getWindowManager().getDefaultDisplay().getRealMetrics(displayMetrics);
- return displayMetrics.heightPixels;
- }
3.4 毫米转为指定分辨率的像素
- /**
- * 像素=毫米x分辨率
- * dip,像素/英寸单位,1英寸=2.54厘米=25.4毫米
- * metrics.xdpi * (1.0f/25.4f) 代表分辨率x1.0fx1英寸 就是所需的dip(25.4f毫米级表示1英寸)
- * (300f / 25.4f) 一英寸上有300像素,一毫米上有 (300f / 25.4f)像素
- * value 毫米值
- *
- * dipValue 分辨率 默认96 ,可以更改为400或者300
- */
- public float applyDimension(float value) {
- return value * dipValue * (1f / 25.4f);
- }
四 文件操作
4.1 创建文件
- /**
- * 创建一个文件
- * path 路径
- */
- public static void creatFile(String path) {
- File file = new File(path);
- file.createNewFile();
- }
4.2 创建文件夹
- /**
- * 创建一个文件夹.
- * path 路径
- */
- public static void createDirectory(String path) {
- File file = new File(path);
- file.mkdir();
- }
4.3 判断文件或者文件夹是否存在
- /**
- * 判断文件或者文件夹是否存在
- */
- public static boolean isExists(String path) {
- File file = new File(path);
- return file.exists();
- }
4.4 获取文件或者文件夹大小
- /**
- * 获取文件或者文件夹大小.
- */
- public static long getFileAllSize(String path) {
- File file = new File(path);
- if (file.exists()) {
- if (file.isDirectory()) {
- File[] childrens = file.listFiles();
- long size = 0;
- for (File f : childrens) {
- size += getFileAllSize(f.getPath());
- }
- return size;
- } else {
- return file.length();
- }
- } else {
- return 0;
- }
- }
4.5 获取文件的名字,不包含后缀
- /**
- * 获取文件的名字
- * 不包含后缀
- */
- public static String getFileName(String url) {
- int start = url.lastIndexOf("/");
- int end = url.lastIndexOf(".");
- if (start != -1 && end != -1) {
- return url.substring(start + 1, end);
- } else {
- return null;
- }
- }
4.6 获取文件的名字,包含后缀
- /**
- * 获取文件的名字
- * 保留文件名及后缀
- */
- public static String getFileNameWithSuffix(String pathandname) {
- int start = pathandname.lastIndexOf("/");
- if (start != -1) {
- return pathandname.substring(start + 1);
- } else {
- return null;
- }
- }
4.7 重命名文件
- /**
- * 重命名文件.
- */
- public static boolean renameFile(String resFilePath, String newFilePath) {
- File resFile = new File(resFilePath);
- File newFile = new File(newFilePath);
- return resFile.renameTo(newFile);
- }
4.8 读取文件内容到字符串
- /**
- * 读取文件内容到字符串
- * @param strFilePath
- * @return
- */
- public static String ReadTxtFile(String strFilePath) {
- StringBuffer stringBuffer = new StringBuffer();
- try {
- //打开文件
- File file = new File(strFilePath);
- //如果path是传递过来的参数,可以做一个非目录的判断
- if (!file.exists()) {
- file.createNewFile();
- }
- InputStream instream = new FileInputStream(file);
- if (instream != null) {
- InputStreamReader inputreader = null;
-
- inputreader = new InputStreamReader(instream, "utf-8");
-
- BufferedReader buffreader = new BufferedReader(inputreader);
- String line;
- //分行读取
- while ((line = buffreader.readLine()) != null) {
- stringBuffer.append(line + "\n");
- }
- instream.close();
- }
- } catch (Exception e) {
- }
- return stringBuffer.toString();
- }
4.9 保存字符串到文件
- /**
- * 保存字符串到文件.
- */
- public static String saveFilePlt(Context mContext,String content, String fileName) {
- try {
- String dir = mContext.getExternalFilesDir("").getAbsolutePath()
- + File.separator + "lensun";
- (new File(dir)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
- File fs = new File(dir,fileName+".plt");
- FileOutputStream os = new FileOutputStream(fs);
- os.write(content.getBytes());
- os.flush();
- os.close();
- return fs.getAbsolutePath();
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- return null;
- }
4.10 压缩并保存Bitmap
- /**
- * 压缩并保存Bitmap
- * @param context
- * @param bitmap
- * @return
- */
- public static File saveToImage(Context context, Bitmap bitmap) {
- FileOutputStream fos;
- try {
- // SD卡根目录
- File dir = context.getExternalFilesDir("lensun");
- if (!dir.exists()) {
- dir.mkdirs();
- }
- File picFile = new File(dir, "fengmian" + ".jpg");
- if(picFile.isFile()&&picFile.exists()){
- picFile.delete();
- }
- fos = new FileOutputStream(picFile);
- ByteArrayOutputStream imageByteArray = new ByteArrayOutputStream();
- bitmap.compress(Bitmap.CompressFormat.JPEG, 80, imageByteArray);
-
- byte[] imageData = imageByteArray.toByteArray();
-
- fos.write(imageData);
- fos.flush();
- fos.close();
- bitmap.recycle();
- return picFile;
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
4.11 压缩并保存指定分辨率的Bitmap
- /**
- * 不压缩,改变jpg分辨,保存图片
- * @param bitmap
- * @return
- */
- public File saveToImage(Bitmap bitmap) {
- FileOutputStream fos;
- try {
- // SD卡根目录
- File dir = context.getExternalFilesDir("print");
- if (!dir.exists()) {
- dir.mkdirs();
- }
- File picFile = new File(dir, type + "_" + System.currentTimeMillis() + ".jpg");
- fos = new FileOutputStream(picFile);
- ByteArrayOutputStream imageByteArray = new ByteArrayOutputStream();
- bitmap.compress(Bitmap.CompressFormat.JPEG, 100, imageByteArray);
-
- byte[] imageData = imageByteArray.toByteArray();
-
- //300 will be the dpi of the bitmap
- setDpi(imageData, dipValue);
-
- fos.write(imageData);
- fos.flush();
- fos.close();
- bitmap.recycle();
- return picFile;
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
-
- //设置图片分辨率
- public void setDpi(byte[] imageData, int dpi) {
- imageData[13] = 1;
- imageData[14] = (byte) (dpi >> 8);
- imageData[15] = (byte) (dpi & 0xff);
- imageData[16] = (byte) (dpi >> 8);
- imageData[17] = (byte) (dpi & 0xff);
- }
4.12 获取视频第一帧封面
- /**
- * 获取视频第一帧封面
- * @param filePath
- * @param kind
- * @return
- */
- public static Bitmap createVideoThumbnail(String filePath, int kind) {
- Bitmap bitmap = null;
- MediaMetadataRetriever retriever = new MediaMetadataRetriever();
- try {
- if (filePath.startsWith("http://")
- || filePath.startsWith("https://")
- || filePath.startsWith("widevine://")) {
- retriever.setDataSource(filePath, new Hashtable<String, String>());
- } else {
- retriever.setDataSource(filePath);
- }
- bitmap = retriever.getFrameAtTime(0, MediaMetadataRetriever.OPTION_CLOSEST_SYNC); //retriever.getFrameAtTime(-1);
- } catch (IllegalArgumentException ex) {
- // Assume this is a corrupt video file
- ex.printStackTrace();
- } catch (RuntimeException ex) {
- // Assume this is a corrupt video file.
- ex.printStackTrace();
- } finally {
- try {
- retriever.release();
- } catch (RuntimeException ex) {
- // Ignore failures while cleaning up.
- ex.printStackTrace();
- }
- }
-
- if (bitmap == null) {
- return null;
- }
-
- if (kind == MediaStore.Images.Thumbnails.MINI_KIND) {//压缩图片 开始处
- // Scale down the bitmap if it's too large.
- int width = bitmap.getWidth();
- int height = bitmap.getHeight();
- int max = Math.max(width, height);
- if (max > 512) {
- float scale = 512f / max;
- int w = Math.round(scale * width);
- int h = Math.round(scale * height);
- bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true);
- }//压缩图片 结束处
- }
- return bitmap;
- }
五 手机或者应用信息
5.1 获取应用版本号
- /**
- * 获取版本号
- *
- * @return 当前应用的版本号
- */
- public static int getVersionCode(Context context) {
- try {
- PackageManager manager = context.getPackageManager();
- PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
- int versionCode = info.versionCode;
- return versionCode;
- } catch (Exception e) {
- e.printStackTrace();
- return 0;
- }
- }
5.2 获取应用版本名字
- /**
- * 获取版本名字
- *
- * @return 当前应用的版本号
- */
- public static String getVersion(Context context) {
- try {
- PackageManager manager = context.getPackageManager();
- PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
- String version = info.versionName;
- return version;
- } catch (Exception e) {
- e.printStackTrace();
- return "0.0";
- }
- }
5.3 获取应用名字
- /**
- * 获取apk的名称
- * @param context 上下文
- * @return String
- */
- public static String getAppName(Context context) {
- try {
- PackageManager e = context.getPackageManager();
- PackageInfo packageInfo = e.getPackageInfo(context.getPackageName(), 0);
- int labelRes = packageInfo.applicationInfo.labelRes;
- return context.getResources().getString(labelRes);
- } catch (NameNotFoundException var4) {
- var4.printStackTrace();
- return "unKnown";
- }
- }
5.4 获取应用图标
- /**
- * 获取应用图标
- * @param context
- * @param packageName
- * @return
- */
- public static Drawable getAppIcon(Context context, String packageName) {
- PackageManager pm = context.getPackageManager();
- Drawable appIcon = null;
- try {
- ApplicationInfo applicationInfo = pm.getApplicationInfo(packageName, 0);
- appIcon = applicationInfo.loadIcon(pm);
- } catch (PackageManager.NameNotFoundException e) {
- e.printStackTrace();
- }
- return appIcon;
- }
5.5 获取应用root权限
- /**
- * 获得root权限
- * @param context
- * @return
- */
- public static boolean getRootPermission(Context context) {
- String packageCodePath = context.getPackageCodePath();
- Process process = null;
- DataOutputStream os = null;
- try {
- String cmd = "chmod 777 " + packageCodePath;
- process = Runtime.getRuntime().exec("su");
- os = new DataOutputStream(process.getOutputStream());
- os.writeBytes(cmd + "\n");
- os.writeBytes("exit\n");
- os.flush();
- process.waitFor();
- } catch (Exception e) {
- return false;
- } finally {
- try {
- if (os != null) {
- os.close();
- }
- process.destroy();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- return true;
- }
5.6 判断某个服务是否运行
- /**
- * 服务是否在运行
- * @param context
- * @param className
- * @return
- */
- public static boolean isServiceRunning(Context context, String className) {
- boolean isRunning = false;
- ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
- List<RunningServiceInfo> servicesList = activityManager.getRunningServices(Integer.MAX_VALUE);
- for (RunningServiceInfo si : servicesList) {
- if (className.equals(si.service.getClassName())) {
- isRunning = true;
- }
- }
- return isRunning;
- }
5.7 获取手机品牌,固件等系统信息
- /**
- * 手机信息
- * 需要 <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
- *
- * @return
- */
- public static String printSystemInfo() {
- Date date = new Date(System.currentTimeMillis());
- SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- String time = dateFormat.format(date);
- StringBuilder sb = new StringBuilder();
- sb.append("_______ 系统信息 ").append(time).append(" ______________");
- sb.append("\nID :").append(Build.ID); // Either a changelist number, or a label like "M4-rc20".
- sb.append("\nBRAND :").append(Build.BRAND); //品牌名 如 Xiaomi
- sb.append("\nMODEL :").append(Build.MODEL); //手机型号
- sb.append("\nRELEASE :").append(Build.VERSION.RELEASE); //frimware版本(系统版本) 如:2.1-update1
- sb.append("\nSDK :").append(Build.VERSION.SDK); //sdk版本号
-
- sb.append("\n_______ OTHER _______");
- sb.append("\nBOARD :").append(Build.BOARD); //基板名 如 MSM8974
- sb.append("\nPRODUCT :").append(Build.PRODUCT); //The name of the overall product.
- sb.append("\nDEVICE :").append(Build.DEVICE); //品牌型号名,如小米4对应cancro
- sb.append("\nFINGERPRINT :").append(Build.FINGERPRINT); //包含制造商,设备名,系统版本等诸多信息 如 Xiaomi/cancro_wc_lte/cancro:6.0.1/MMB29M/V8.1.3.0.MXDCNDI:user/release-keys
- sb.append("\nHOST :").append(Build.HOST); // 如 c3-miui-ota-bd43
- sb.append("\nTAGS :").append(Build.TAGS); //Comma-separated tags describing the build, like "unsigned,debug".
- sb.append("\nTYPE :").append(Build.TYPE); //The type of build, like "user" or "eng".
- sb.append("\nTIME :").append(Build.TIME); //当前时间,毫秒值
- sb.append("\nINCREMENTAL :").append(Build.VERSION.INCREMENTAL);
-
- sb.append("\n_______ CUPCAKE-3 _______");
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {
- sb.append("\nDISPLAY :").append(Build.DISPLAY); // 如 MMB29M
- }
-
- sb.append("\n_______ DONUT-4 _______");
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.DONUT) {
- sb.append("\nSDK_INT :").append(Build.VERSION.SDK_INT);
- sb.append("\nMANUFACTURER :").append(Build.MANUFACTURER); // The manufacturer of the product/hardware. 如 Xiaomi
- sb.append("\nBOOTLOADER :").append(Build.BOOTLOADER); //The system bootloader version number. 如
- sb.append("\nCPU_ABI :").append(Build.CPU_ABI); // 如 armeabi-v7a
- sb.append("\nCPU_ABI2 :").append(Build.CPU_ABI2); // 如 armeabi
- sb.append("\nHARDWARE :").append(Build.HARDWARE); // The name of the hardware (from the kernel command line or /proc). 如 qcom
- sb.append("\nUNKNOWN :").append(Build.UNKNOWN); // Value used for when a build property is unknown.
- sb.append("\nCODENAME :").append(Build.VERSION.CODENAME);
- }
-
- sb.append("\n_______ GINGERBREAD-9 _______");
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
- sb.append("\nSERIAL :").append(Build.SERIAL); // A hardware serial number, if available. 如 abcdefgh
- }
- return sb.toString();
- }
5.8 获取IP地址
- /**
- * 获得IP地址,分为两种情况,一是wifi下,二是移动网络下,得到的ip地址是不一样的
- * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
- */
- public static String getIPAddress(Context context) {
- NetworkInfo info = ((ConnectivityManager) context
- .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
- if (info != null && info.isConnected()) {
- if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
- try {
- for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
- NetworkInterface intf = en.nextElement();
- for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
- InetAddress inetAddress = enumIpAddr.nextElement();
- if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
- return inetAddress.getHostAddress();
- }
- }
- }
- } catch (SocketException e) {
- e.printStackTrace();
- }
-
- } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
- WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
- WifiInfo wifiInfo = wifiManager.getConnectionInfo();
- //调用方法将int转换为地址字符串
- String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
- return ipAddress;
- }
- } else {
- //当前无网络连接,请在设置中打开网络
- }
- return null;
- }
-
- /**
- * 将得到的int类型的IP转换为String类型
- *
- * @param ip
- * @return
- */
- private static String intIP2StringIP(int ip) {
- return (ip & 0xFF) + "." +
- ((ip >> 8) & 0xFF) + "." +
- ((ip >> 16) & 0xFF) + "." +
- (ip >> 24 & 0xFF);
- }
5.9 判断是否鸿蒙系统
- /**
- * 是否为鸿蒙系统
- * @return true为鸿蒙系统
- */
- public static boolean isHarmonyOs() {
- try {
- Class<?> buildExClass = Class.forName("com.huawei.system.BuildEx");
- Object osBrand = buildExClass.getMethod("getOsBrand").invoke(buildExClass);
- return "Harmony".equalsIgnoreCase(osBrand.toString());
- } catch (Throwable x) {
- return false;
- }
- }
5.10 获取鸿蒙系统版本号
- /**
- * 获取鸿蒙系统版本号
- * @return 版本号
- */
- public static String getHarmonyVersion() {
- return getProp("hw_sc.build.platform.version", "");
- }
-
- /**
- * 获取属性
- * @param property
- * @param defaultValue
- * @return
- */
- private static String getProp(String property, String defaultValue) {
- try {
- Class spClz = Class.forName("android.os.SystemProperties");
- Method method = spClz.getDeclaredMethod("get", String.class);
- String value = (String) method.invoke(spClz, property);
- if (TextUtils.isEmpty(value)) {
- return defaultValue;
- }
- return value;
- } catch (Throwable e) {
- e.printStackTrace();
- }
- return defaultValue;
- }
-
- /**
- * 获得鸿蒙系统版本号(含小版本号,实际上同Android的android.os.Build.DISPLAY)
- * @return 版本号
- */
- public static String getHarmonyDisplayVersion() {
- return android.os.Build.DISPLAY;
- }
六 地图导航工具类
6.1 主流卫星地图坐标系分类
- WGS84 :地理坐标系统,Google Earth和中国外的Google Map使用,另外,目前基本上所有定位空间位置的设备都使用这种坐标系统,例如手机的GPS系统。
- GCJ-02:投影坐标系统,也就是我们平常所说的火星坐标系,Google Map中国、高德和腾讯好像使用,这个是中国自己在WGS84基础上加密而成,目的显而易见。
- BD09:投影坐标系统,百度地图使用,在GCJ-02基础上二次加密而成。
6.2 检测程序是否安装
- /**
- * 检测程序是否安装
- *
- * @param packageName
- * @return
- */
- public boolean isInstalled(String packageName) {
- PackageManager manager = mContext.getPackageManager();
- //获取所有已安装程序的包信息
- List<PackageInfo> installedPackages = manager.getInstalledPackages(0);
- if (installedPackages != null) {
- for (PackageInfo info : installedPackages) {
- if (info.packageName.equals(packageName))
- return true;
- }
- }
- return false;
- }
6.3 跳转到百度地图
- /**
- * 跳转百度地图
- */
- public void goToBaiduMap() {
- if (!isInstalled("com.baidu.BaiduMap")) {//是否安装百度
- ToastHelp.showToast("请安装百度地图客户端");
- return;
- }
- double mlat = Double.parseDouble(latString);
- double mLon = Double.parseDouble(lngString);
- //高德坐标转换
- double[] locationArray = map_tx2bd(mlat, mLon);
- mlat = locationArray[0];
- mLon = locationArray[1];
-
- //导航
- Intent intent = new Intent();
- StringBuffer stringBuffer = new StringBuffer("baidumap://map/direction?destination=");
- // stringBuffer.append("latlng:").append("39.98871").append(",").append("116.43234")
- stringBuffer.append("latlng:").append(mlat).append(",").append(mLon)
- .append("|name:").append(Address)
- .append("&mode=").append("driving")
- .append("&coord_type=").append("bd09ll")
- .append("&mode=").append("driving")
- .append("&src=").append("com.baidu.BaiduMap");
- Log.e(TAG, "goToBaiduMap: " + stringBuffer.toString());
- // String url="baidumap://map/direction?destination=西直门|&coord_type=bd09ll&mode=transit&sy=3&index=0&target=1&src="+mContext.getPackageName();
- intent.setData(Uri.parse(stringBuffer.toString()));
- mContext.startActivity(intent); // 启动调用
- }
6.4 跳转到高德地图
- /**
- * 跳转高德地图
- */
- public void goToGaodeMap() {
- if (!isInstalled("com.autonavi.minimap")) {//是否安装高德
- ToastHelp.showToast("请安装高德地图客户端");
- return;
- }
- double mlat = Double.parseDouble(latString);
- double mLon = Double.parseDouble(lngString);
- StringBuffer stringBuffer = new StringBuffer("amapuri://route/plan/?");
- stringBuffer.append("&dlat=").append(mlat)
- .append("&dlon=").append(mLon)
- .append("&dname=" + Address)
- .append("&dev=").append(0)
- .append("&t=").append(0);
- Intent intent = new Intent("android.intent.action.VIEW", Uri.parse(stringBuffer.toString()));
- intent.setPackage("com.autonavi.minimap");
- mContext.startActivity(intent);
- }
6.5 跳转到腾讯地图
- /**
- * 跳转腾讯地图
- */
- public void goToTencentMap() {
- if (!isInstalled("com.tencent.map")) {//是否安装腾讯
- ToastHelp.showToast("请安装腾讯地图客户端");
- return;
- }
- double mlat = Double.parseDouble(latString);
- double mLon = Double.parseDouble(lngString);
- StringBuffer stringBuffer = new StringBuffer("qqmap://map/routeplan?type=drive")
- .append("&tocoord=").append(mlat).append(",").append(mLon).append("&to=" + Address);
- Intent intent = new Intent("android.intent.action.VIEW", Uri.parse(stringBuffer.toString()));
- mContext.startActivity(intent);
- }
6.6 坐标转换,腾讯地图转换成百度地图坐标
- /**
- * 坐标转换,腾讯地图转换成百度地图坐标
- *
- * @param lat 腾讯纬度
- * @param lon 腾讯经度
- * @return 返回结果:经度,纬度
- */
- public static double[] map_tx2bd(double lat, double lon) {
- double bd_lat;
- double bd_lon;
- double x_pi = 3.14159265358979324;
- double x = lon, y = lat;
- double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
- double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
- bd_lon = z * Math.cos(theta) + 0.0065;
- bd_lat = z * Math.sin(theta) + 0.006;
-
- System.out.println("bd_lat:" + bd_lat);
- System.out.println("bd_lon:" + bd_lon);
-
- return new double[]{bd_lat, bd_lon};
- }
七,加密解密算法
7.1 AES加密解密
- public class AESUitls {
- /*
- * 加密用的Key 可以用26个字母和数字组成 使用AES-128-CBC加密模式,key需要为16位。
- */
- private static final String CipherMode = "AES/CBC/PKCS7Padding";
- private static final String SecretKey = LogInterceptor.SECRETKEY;
- private static final String SecretIV = LogInterceptor.SECRETIV;
- private static final Integer IVSize = 16;
-
- private static final String EncryptAlg = "AES";
-
- private static final String Encode = "UTF-8";
-
-
- private static final String Key_Encode = "UTF-8";
-
- /**
- * 创建密钥
- *
- * @return
- */
- private static SecretKeySpec createKey() {
- try {
- byte[] data = SecretKey.getBytes(Encode);
- return new SecretKeySpec(data, EncryptAlg);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
-
- /**
- * 创建16位向量: 不够则用0填充
- *
- * @return
- */
- private static IvParameterSpec createIV() {
- byte[] data = null;
- try {
- data = SecretIV.getBytes(Encode);
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- return new IvParameterSpec(data);
- }
-
- /**
- * 加密:有向量16位,结果转base64
- *
- * @param context
- * @return
- */
- public static String encrypt(String context) {
- try {
- byte[] content = context.getBytes(Encode);
- SecretKeySpec key = createKey();
- Cipher cipher = Cipher.getInstance(CipherMode);
- cipher.init(Cipher.ENCRYPT_MODE, key, createIV());
- byte[] data = cipher.doFinal(content);
- String result = Base64.encodeToString(data, Base64.NO_WRAP);
- return result;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
-
- /**
- * 解密
- *
- * @param context
- * @return
- */
- public static String decrypt(String context) {
- try {
- byte[] data = Base64.decode(context, Base64.DEFAULT);
- SecretKeySpec key = createKey();
- Cipher cipher = Cipher.getInstance(CipherMode);
- cipher.init(Cipher.DECRYPT_MODE, key, createIV());
- byte[] content = cipher.doFinal(data);
- String result = new String(content, Encode);
- return result;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
-
-
- }
八 富文本使用
8.1 类似于金额格式化效果 , ¥100.20显示为 ¥小字体,100大字体,20小字体
- /**
- *
- * @param values ¥100.20
- * @param textsize
- * @param smallsize
- * @param isBold
- * @return
- */
- public static SpannableString changTVsize(String values, int textsize, int smallsize, boolean isBold) {
- String value = subZeroAndDot(values);
- SpannableString spannableString = new SpannableString(value);
- AbsoluteSizeSpan sizeSpan01 = new AbsoluteSizeSpan(textsize, true);
- AbsoluteSizeSpan sizeSpan03 = new AbsoluteSizeSpan(smallsize, true);
- AbsoluteSizeSpan sizeSpan02 = new AbsoluteSizeSpan(smallsize, true);
- if (value.contains(".")) {
- spannableString.setSpan(sizeSpan02, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
- spannableString.setSpan(sizeSpan03, value.indexOf("."), value.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
- spannableString.setSpan(sizeSpan01, 1, value.indexOf("."), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
- } else {
- spannableString.setSpan(sizeSpan03, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
- spannableString.setSpan(sizeSpan01, 1, value.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
- }
-
- if (isBold) {
- spannableString.setSpan(new StyleSpan(Typeface.BOLD), 0, value.length(),
- Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
- }
-
- return spannableString;
-
- }
8.2 查找匹配标红效果
- SpannableStringBuilder stringBuilder = new SpannableStringBuilder(deliveryTime);
- //发货时间字体红色
- Matcher matcherPerson = Pattern.compile(deliveryTimeFormat).matcher(stringBuilder);
- while (matcherPerson.find()) {
- ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#E02020"));
- stringBuilder.setSpan(colorSpan, matcherPerson.start(), matcherPerson.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
- }
8.3 文字不同颜色富文本拼接效果 ForegroundColorSpan,AbsoluteSizeSpan
- SpannableString spannableString = new SpannableString("根据监管政策要求");
- spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#333333")), 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
- spannableString.setSpan(new AbsoluteSizeSpan(13, true), 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
-
- SpannableString spannableString2 = new SpannableString("单笔订单不能超过5000元。\n");
- spannableString2.setSpan(new ForegroundColorSpan(Color.parseColor("#ed291b")), 0, spannableString2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
- spannableString2.setSpan(new AbsoluteSizeSpan(13, true), 0, spannableString2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
-
- SpannableString spannableString3 = new SpannableString("中国海关规定");
- spannableString3.setSpan(new ForegroundColorSpan(Color.parseColor("#333333")), 0, spannableString3.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
- spannableString3.setSpan(new AbsoluteSizeSpan(13, true), 0, spannableString3.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
-
- SpannableString spannableString4 = new SpannableString("每人每年海淘商品限额26000元人民币,");
- spannableString4.setSpan(new ForegroundColorSpan(Color.parseColor("#ed291b")), 0, spannableString4.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
- spannableString4.setSpan(new AbsoluteSizeSpan(13, true), 0, spannableString4.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
-
- SpannableString spannableString5 = new SpannableString("如超出此限额会导致清关失败,请注意个人额度情况,您可以进入【跨境电子商务个人额度查询】网站进行查询。");
- spannableString5.setSpan(new ForegroundColorSpan(Color.parseColor("#333333")), 0, spannableString5.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
- spannableString5.setSpan(new AbsoluteSizeSpan(13, true), 0, spannableString5.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
-
-
- SpannableStringBuilder spannableStringBuilder=new SpannableStringBuilder();
- spannableStringBuilder.append(spannableString).append(spannableString2).append(spannableString3).append(spannableString4).append(spannableString5);
- mBinding.tvContent.setText(spannableStringBuilder);
8.4 图片富文本效果 ImageSpan
- private SpannableStringBuilder getContent(String title,String content){
- SpannableString spannableString = new SpannableString(title+"\n");
- spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#333333")), 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
- spannableString.setSpan(new AbsoluteSizeSpan(14, true), 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
-
-
- SpannableString spannableImage = new SpannableString("间距2\n");
- Drawable drawable=getResources().getDrawable(R.drawable.space_hight_2);
- drawable.setBounds(0,0, ScreenUtils.getScreenWidth(this), (int) ScreenUtils.dp2px(this,2f));
- ImageSpan imageSpan=new ImageSpan(drawable,ImageSpan.ALIGN_BASELINE);
- spannableImage.setSpan(imageSpan,0, spannableImage.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
-
-
- SpannableString spannableString2 = new SpannableString(content+"\n");
- spannableString2.setSpan(new ForegroundColorSpan(Color.parseColor("#999999")), 0, spannableString2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
- spannableString2.setSpan(new AbsoluteSizeSpan(12, true), 0, spannableString2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
-
-
- SpannableString spannableImage2 = new SpannableString("间距7\n");
- Drawable drawable2=getResources().getDrawable(R.drawable.space_hight_2);
- drawable2.setBounds(0,0,ScreenUtils.getScreenWidth(this), (int) ScreenUtils.dp2px(this,7f));
- ImageSpan imageSpan2=new ImageSpan(drawable2,ImageSpan.ALIGN_BASELINE);
- spannableImage2.setSpan(imageSpan2,0, spannableImage2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
-
- SpannableStringBuilder spannableStringBuilder=new SpannableStringBuilder();
- spannableStringBuilder.append(spannableString).append(spannableImage).append(spannableString2).append(spannableImage2);
-
- return spannableStringBuilder;
- }
8.5 用Html.fromHtml简单变色
- String str1 = "抱歉,没有找到商品,为您推荐<font color = '#333333'>" + "“" + dataDTO.correctWord + "”" + "</font>的搜索结果";
- CharSequence charSequence;
- if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
- charSequence = Html.fromHtml(str1, Html.FROM_HTML_MODE_LEGACY);
- } else {
- charSequence = Html.fromHtml(str1);
- }
- tvNoData.setText(charSequence);
九 Webview加载文本,统一设置样式,间距
- public static String getHtmlData(String bodyHTML) {
- String head = "<head>" +
- "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " +
- "<style>div,p,img{max-width: 100%; width: 100% !important; height: auto !important;}" +
- "body {" +
- "margin-right:8px;" +//限定网页中的文字右边距为15px(可根据实际需要进行行管屏幕适配操作)
- "margin-left:8px;" +//限定网页中的文字左边距为15px(可根据实际需要进行行管屏幕适配操作)
- "margin-top:8px;" +//限定网页中的文字上边距为15px(可根据实际需要进行行管屏幕适配操作)
- "font-size:16px;" +//限定网页中文字的大小为40px,请务必根据各种屏幕分辨率进行适配更改
- "word-wrap:break-word;" +//允许自动换行(汉字网页应该不需要这一属性,这个用来强制英文单词换行,类似于word/wps中的西文换行)
- "}" +
- "p { margin: 0; }" +
- "</style>" +
- "</head>";
-
-
- return "<html>" + head + "<body>" + bodyHTML + "</body><ml>";
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。