MyUtils 工具类

这段代码展示了Android中一个名为MyUtils的实用工具类,包含各种静态方法,如删除缓存文件、字符串处理、JSON操作、权限检查、启动浏览器、文件转Base64编码、图片操作等。这个类用于提高应用程序的日常开发效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

import android.app.Activity;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.content.ContextCompat;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hebky.oa.iit.base.Constant;
import com.hebky.oa.iit.base.MyApplication;
import com.hebky.oa.iit.ui.acty.XwggImageActivity;

import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.crypto.Cipher;

import Decoder.BASE64Encoder;
import cn.mvp.mlibs.encryption.AESUtils;
import cn.mvp.mlibs.utils.FileUtils;
import cn.mvp.mlibs.utils.StringUtil;

public class MyUtils {


    /**
     * 删除缓存文件
     */
    public static void deleteCacheFiles() {
        deleteAllFiles(Constant.APP_CACHE_PATH);
    }


    public static String[] getListValToArr(List<Map<String, String>> lists, String key) {
        if (lists != null && lists.size() > 0) {
            String[] array = new String[lists.size()];
            for (int i = 0; i < lists.size(); i++) {
                array[i] = lists.get(i).get(key);
            }
            return array;
        }
        return new String[0];
    }

    public static String[] getJsonArrValToArr(JSONArray lists, String key) {
        if (lists == null) {
            return new String[0];
        }
        String[] strArr = new String[lists.size()];
        for (int i = 0; i < lists.size(); i++) {
            if (lists.get(i) instanceof JSONObject) {
                strArr[i] = lists.getJSONObject(i).getString(key);
            } else {
                strArr[i] = lists.getString(i);
            }
        }
        return strArr;
    }

    /**
     * 默认是空字符串
     */
    public static String getIntValueStr(Object arg) {
        if (arg == null) {
            return StringUtils.EMPTY;
        }
        return getIntValue(arg.toString()) + StringUtils.EMPTY;
    }

    /**
     * 默认是0
     */
    public static int getIntValue(Object arg) {
        if (arg == null) {
            return 0;
        }
        return getIntValue(arg.toString());
    }

    /**
     * 默认是0
     */
    public static int getIntValue(String arg) {
        if (arg != null) {
            return Integer.parseInt(arg);
        }
        return 0;
    }

    /**
     * 将文件转成base64 字符串
     *
     * @param file 文件路径
     * @return *
     */
    public static String encodeBase64File(File file) {
        try {
            return new BASE64Encoder().encode(FileUtils.readFile(file.getPath()));
        } catch (IOException e) {
            XLog.printExceptionInfo(e);
            return null;
        }
    }

    /**
     * 启动浏览器
     *
     * @param context     上下文
     * @param uri         地址
     * @param requestCode 请求码
     */
    public static void statrtBrowsable(Context context, String uri, int requestCode) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_BROWSABLE);
        if (context instanceof Activity) {
            ((Activity) context).startActivityForResult(intent, requestCode);
        }
    }

    /**
     * 有权限: PackageManager.PERMISSION_GRANTED
     * 无权限: PackageManager.PERMISSION_DENIED
     *
     * @param context    上下文
     * @param permission Manifest.permission.WRITE_EXTERNAL_STORAGE
     * @return 检查是否包含某项权限
     */
    public static boolean isHasPermission(Context context, String permission) {
        return ContextCompat.checkSelfPermission(context.getApplicationContext(), permission) == PackageManager.PERMISSION_GRANTED;
    }

    public static boolean isImg(String fileSuffix) {
        return fileSuffix != null && (
                StringUtils.equals(fileSuffix.toLowerCase(), "png")
                        || StringUtils.equals(fileSuffix, "jpg")
                        || StringUtils.equals(fileSuffix.toLowerCase(), "jpeg")
                        || StringUtils.equals(fileSuffix.toLowerCase(), "gif")
                        || StringUtils.equals(fileSuffix.toLowerCase(), "jpeg")
                        || StringUtils.equals(fileSuffix.toLowerCase(), "bmp"));
    }

    public static void openImage(Context context, String filePath) throws IOException {
        if (context == null || filePath == null) {
            throw new IOException("路径参数不能为空");
        }
        File response = new File(filePath);
        String fileSuffix = FileUtils.getFileSuffix(response.getPath());

        if (StringUtils.equals(fileSuffix.toLowerCase(), "png")
                || StringUtils.equals(fileSuffix.toLowerCase(), "jpg")
                || StringUtils.equals(fileSuffix.toLowerCase(), "jpeg")
                || StringUtils.equals(fileSuffix.toLowerCase(), "gif")
                || StringUtils.equals(fileSuffix.toLowerCase(), "jpeg")
                || StringUtils.equals(fileSuffix.toLowerCase(), "bmp")) {
            XwggImageActivity.openActivity(context, filePath, new String[]{filePath});
        }
    }

    /**
     * 字符串转list
     */
    public static List<String> strSplitToList(String str, String regex) {
        List<String> list = new ArrayList<>();
        if (str != null) {
            if (str.contains(regex)) {
                Collections.addAll(list, str.split(regex));
            } else {
                list.add(str);
            }
        }
        return list;
    }

    /**
     * @param args map数据
     * @return String[0]:key值,逗号分割 String[1]:value值,逗号分割
     */
    public String[] getMapToString(Map<String, String> args) {
        String[] strings = new String[2];
        StringBuilder keys = new StringBuilder();
        StringBuilder values = new StringBuilder();
        if (args != null && args.size() > 0) {
            for (Map.Entry<String, String> entry : args.entrySet()) {
                keys.append(",").append(entry.getKey());
                values.append(",").append(entry.getValue());
            }
            if (keys.length() > 0) {
                strings[0] = keys.deleteCharAt(0).toString();
                strings[1] = values.deleteCharAt(0).toString();
            }
        }
        return strings;
    }


    /**
     * @param str 要操作的字符串
     * @return 删除前后逗号及双连逗号(", , ")的字符串
     */
    public static String deltetComma(String str) {
        if (StringUtils.contains(str, ",,")) {
            str = str.replace(",,", ",");
        }
        if (StringUtils.startsWith(str, ",")) {
            return deltetComma(StringUtils.substring(str, 1));
        } else if (StringUtils.endsWith(str, ",")) {
            return deltetComma(StringUtils.substring(str, 0, str.length() - 1));
        }
        return str;
    }

    /**
     * @param msg 错误信息
     * @return 返回信息是否为连接失败
     */
    public static String getErrorMesage(String msg, String customTipMsg) {
        return StringUtils.equals(Constant.CONNECTION_NET_FAILURE, msg) && !StringUtil.isEmpty(customTipMsg) ? customTipMsg : msg;
    }

    /**
     * ps:CommonUtils.deltetBefore2After(",,,我是,示例,,,",",")
     *
     * @param str  要操作的字符串
     * @param str1 要删除的特定字符串
     * @return 删除前后特定的字符串
     */
    public static String deltetBefore2After(String str, String str1) {
        if (StringUtils.startsWith(str, str1)) {
            return deltetComma(StringUtils.substring(str, 1));
        } else if (StringUtils.endsWith(str, str1)) {
            return deltetComma(StringUtils.substring(str, 0, str.length() - 1));
        }
        return str;
    }

    // 上次点击时间
    private static long lastClickTime = 0L;

    /**
     * @return 按钮是否可以点击
     */
    public static boolean btnIsClick() {
        // 两次点击间隔时间(毫秒)
        return btnIsClick(1500);
    }

    /**
     * @param fastClickDelayTime 两次点击间隔时间(毫秒)
     * @return 按钮是否可以点击
     */
    public static boolean btnIsClick(int fastClickDelayTime) {
        // 两次点击间隔时间(毫秒)
        if (System.currentTimeMillis() - lastClickTime >= fastClickDelayTime) {
            lastClickTime = System.currentTimeMillis();
            return false;
        }
        return true;
    }


    /*--------------------------------文件相关--------------------------------*/

    /**
     * 删除缓存文件
     */
    public static void deleteCacheTmpFiles() {
        deleteAllFiles(Constant.APP_CACHE_TMP_PATH);
    }

    public boolean isServiceRunning(Context mContext, String className) {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(30);
        if (!(serviceList.size() > 0)) {
            return false;
        }
        for (int i = 0; i < serviceList.size(); i++) {
            if (serviceList.get(i).service.getClassName().equals(className)) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }


    /**
     * 删除该路径下所有文件
     */
    public static void deleteAllFiles(String path) {
        File root = new File(path);
        File[] files = root.listFiles();
        if (files != null) {
            for (File f : files) {
                /* 判断是否为文件夹*/
                if (f.isDirectory()) {
                    deleteAllFiles(f.getPath());
                    try {
                        f.delete();
                    } catch (Exception e) {
                        XLog.printExceptionInfo(e);
                    }
                } else {
                    /*判断是否存在*/
                    if (f.exists()) {
//                        deleteAllFiles(f.getPath());
                        try {
                            f.delete();
                        } catch (Exception e) {
                            XLog.printExceptionInfo(e);
                        }
                    }
                }
            }
        }
    }

    public static String getPrivateInfo() {
        try {
            String privateFile = MyApplication.getContext().getFilesDir().getPath() + File.separator + ".myPrivate.txt";
            if (FileUtils.isFileExist(privateFile)) {
                return AESUtils.des(new String(FileUtils.readFile(privateFile)), "mPrivate_key", Cipher.DECRYPT_MODE);
            }
        } catch (Exception e) {
            XLog.printExceptionInfo(e);
        }
        return null;
    }

    public static String getPrivateInfo(String key) {
        String privateInfo = getPrivateInfo();
        if (privateInfo != null) {
            return JSONObject.parseObject(privateInfo).getString(key);
        }
        return "";
    }

    public static void setPrivateInfo(String key, String value) {
        String privateFile = MyApplication.getContext().getFilesDir().getPath() + File.separator + ".myPrivate.txt";
        try {
            JSONObject privateInfo;
            String privateInfoStr = getPrivateInfo();
            if (privateInfoStr != null && !StringUtil.isBlank(privateInfoStr)) {
                privateInfo = JSONObject.parseObject(privateInfoStr);
            } else {
                privateInfo = new JSONObject();
            }
            privateInfo.put(key, value);
            String mPrivate = AESUtils.des(privateInfo.toJSONString(), "mPrivate_key", Cipher.ENCRYPT_MODE);
            FileUtils.writeFile(privateFile, mPrivate);
        } catch (Exception e) {
            FileUtils.deleteFile(privateFile);
            XLog.printExceptionInfo(e);
        }
    }

    /**
     * 解除广播注册
     */
    public static void unRegisterReceiver(Context context, BroadcastReceiver receiver) {
        if (context != null && receiver != null) {
            context.unregisterReceiver(receiver);
        }
    }

    /**
     * @param arg    字符串参数
     * @param tipMsg 提示信息
     */
    public static void checkBlank(String arg, String tipMsg) throws IOException {
        if (arg == null || arg.trim().length() == 0) {
            throw new IOException(tipMsg);
        }
    }

    public static void checkSame(String arg0, String arg1, String tipMsg) throws IOException {
        if (org.apache.commons.lang3.StringUtils.equals(arg0, arg1)) {
            throw new IOException(tipMsg);
        }
    }

    /**
     * 阿里公网:223.5.5.5
     *
     * @return 判断单个应用是个可以联网, 原理:ping网络
     */
    public static boolean isNetworkOnline() {

        Runtime runtime = Runtime.getRuntime();
        Process ipProcess = null;
        try {
            ipProcess = runtime.exec("ping -c 5 -w 4 223.5.5.5");
            InputStream input = ipProcess.getInputStream();

            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuffer stringBuffer = new StringBuffer();
            String content = "";
            while ((content = in.readLine()) != null) {
                stringBuffer.append(content);
            }

            int exitValue = ipProcess.waitFor();
            if (exitValue == 0) {
                //WiFi连接,网络正常
                return true;
            } else {
                if (stringBuffer.indexOf("100% packet loss") != -1) {
                    XLog.showArgsInfo("网络丢包严重,判断为网络未连接");
                    return false;
                } else {
                    XLog.showArgsInfo("网络未丢包,判断为网络连接");
                    return true;
                }
            }
        } catch (IOException | InterruptedException e) {
            XLog.printExceptionInfo(e);
        } finally {
            if (ipProcess != null) {
                ipProcess.destroy();
            }
            runtime.gc();
        }
        return false;
    }

    /*将字符串转成ASCII的java方法*/
    public static String stringToAscii(String value) {
        StringBuilder sbu = new StringBuilder();
        char[] chars = value.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (i != chars.length - 1) {
                sbu.append((int) chars[i]).append(",");
            } else {
                sbu.append((int) chars[i]);
            }
        }
        return sbu.toString();
    }

    /*将ASCII转成字符串的java方法*/
    private static String asciiToString(String value) {

        StringBuilder sbu = new StringBuilder();
        String[] chars = value.split(",");
        for (String aChar : chars) {
            sbu.append((char) Integer.parseInt(aChar));
        }
        return sbu.toString();
    }

    /**
     * 获取文本框文字,提取其中的换行符ascii码(10)并替换为<br/>
     * 回车符</r>ascii码(13)
     *
     * @param strContent 编辑框内的文本
     * @return 修改后的文本
     */
    public static String conversion(String strContent) {
        if (strContent != null && strContent.length() > 0) {
            StringBuilder stringBuilder = new StringBuilder();
            for (char c : strContent.toCharArray()) {
                String ascciic = stringToAscii(String.valueOf(c));
                if ("10".equals(ascciic)) {
                    stringBuilder.append("<br/>");
                } else if ("13".equals(ascciic)) {
                    stringBuilder.append("");
                } else if ("8364".equals(ascciic)) {
                    stringBuilder.append("&#8364");
                } else {
                    stringBuilder.append(c);
                }
            }
            return stringBuilder.toString();
        }

        /*以下的方法也可以思路不同*/
//        if (string != null && string.length() > 0) {
//            StringBuilder stringBuilder = new StringBuilder();
//            String asccii = stringToAscii(string);
//            XLog.showArgsInfo("asccii码值" + asccii);
//            String[] split = asccii.split(",");
//            for (String str : split) {
//                if (str.equals("10")) {
//                    stringBuilder.append("<br/>");
//                } else {
//                    stringBuilder.append(asciiToString(str));
//                }
//            }
//            return stringBuilder.toString();
//        }
        return strContent;
    }

//    /**
//     * 事务和信访正文只有doc和pdf两种格式,其他如下
//     * 因为手机上没有新建公文,所有该方法用不到,留存
//     *
//     * @param tableName  表名
//     * @param fileSuffix 文件后缀
//     * @return 是否符合规范
//     */
//    public static boolean isMainBodyFileSuffix(String tableName, String fileSuffix) {
//        if (fileSuffix == null) return false;
//        String provisionsFileSuffix;
//        if (StringUtils.equals(tableName, "d_Laiwen") ||
//                StringUtils.equals(tableName, "d_qkbS") ||
//                StringUtils.equals(tableName, "d_dzgwfs") ||
//                StringUtils.equals(tableName, "d_jiaoban")) {
//            provisionsFileSuffix = "doc";
//        } else {
//            provisionsFileSuffix = "doc,pdf,jpg,jpeg,jfif,gif,png";
//        }
//        return StringUtils.contains(provisionsFileSuffix, fileSuffix.toLowerCase());
//    }

    /**
     * @param fileSuffix 文件后缀
     * @return 是否符合规范
     */
    public static boolean isAttchFileSuffix(String fileSuffix) {
        if (fileSuffix == null) return false;
        String provisionsFileSuffix = "doc,xls,pdf,jpg,jpeg,gif,png,zip,rar,ppt,pptx";
        return StringUtils.contains(provisionsFileSuffix, fileSuffix.toLowerCase());
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值