Android&Java工具类(1)

这篇博客主要记录了Android开发中的一些常用工具类,包括广播管理、文件操作、HTTP请求以及线程池管理。作者计划逐步上传更多工具类代码,以供开发者参考和使用。

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

工具类记录

广播管理工具类:通过直接调用该类来启动关闭服务

public class BroadcastManager {
    private static final String TAG = BroadcastManager.class.getSimpleName();


    public static void sendStartService(Context context, String packageName, String appName) {
        Intent intent = new Intent("startService");
        intent.putExtra("packageName", packageName);
        intent.putExtra("appName", appName);
        context.sendBroadcast(intent);
    }

    public static void sendStopService(Context context, String packageName, String appName) {
        Intent intent = new Intent("stopService");
        intent.putExtra("packageName", packageName);
        intent.putExtra("appName", appName);
        context.sendBroadcast(intent);
    }
}

文件工具类:

/**
 * Created by 李文烙 on 2017/7/11.
 */

public class FilesUtils {
    private static File root;
    public static final int SIZETYPE_B = 1;//获取文件大小单位为B的double值
    public static final int SIZETYPE_KB = 2;//获取文件大小单位为KB的double值
    public static final int SIZETYPE_MB = 3;//获取文件大小单位为MB的double值
    public static final int SIZETYPE_GB = 4;//获取文件大小单位为GB的double值

    public File getRoot() {
        return root;
    }

    public void setRoot(String path) {

        this.root = new File(path);
    }
    public static double getFileOrFilesSize(String filePath, int sizeType){
        File file=new File(filePath);
        long blockSize=0;
        try {
            if(file.isDirectory()){
                blockSize = getFileSizes(file);
            }else{
                blockSize = getFileSize(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("获取文件大小","获取失败!");
        }
        return FormetFileSize(blockSize, sizeType);
    }
    /**
     * 调用此方法自动计算指定文件或指定文件夹的大小
     * @param filePath 文件路径
     * @return 计算好的带B、KB、MB、GB的字符串
     */
    public static String getAutoFileOrFilesSize(String filePath){
        File file=new File(filePath);
        long blockSize=0;
        try {
            if(file.isDirectory()){
                blockSize = getFileSizes(file);
            }else{
                blockSize = getFileSize(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("获取文件大小","获取失败!");
        }
        return FormetFileSize(blockSize);
    }
    /**
     * 获取指定文件大小
     * @param file
     * @return
     * @throws Exception
     */
    private static long getFileSize(File file) throws Exception
    {
        long size = 0;
        if (file.exists()){
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
        }
        else{
            file.createNewFile();
            Log.e("获取文件大小","文件不存在!");
        }
        return size;
    }

    /**
     * 获取指定文件夹
     * @param f
     * @return
     * @throws Exception
     */
    private static long getFileSizes(File f) throws Exception
    {
        long size = 0;
        File flist[] = f.listFiles();
        for (int i = 0; i < flist.length; i++){
            if (flist[i].isDirectory()){
                size = size + getFileSizes(flist[i]);
            }
            else{
                size =size + getFileSize(flist[i]);
            }
        }
        return size;
    }
    /**
     * 转换文件大小
     * @param fileS
     * @return
     */
    private static String FormetFileSize(long fileS)
    {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize="0B";
        if(fileS==0){
            return wrongSize;
        }
        if (fileS < 1024){
            fileSizeString = df.format((double) fileS) + "B";
        }
        else if (fileS < 1048576){
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        }
        else if (fileS < 1073741824){
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        }
        else{
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        return fileSizeString;
    }
    /**
     * 转换文件大小,指定转换的类型
     * @param fileS
     * @param sizeType
     * @return
     */
    private static double FormetFileSize(long fileS,int sizeType)
    {
        DecimalFormat df = new DecimalFormat("#.00");
        double fileSizeLong = 0;
        switch (sizeType) {
            case SIZETYPE_B:
                fileSizeLong= Double.valueOf(df.format((double) fileS));
                break;
            case SIZETYPE_KB:
                fileSizeLong= Double.valueOf(df.format((double) fileS / 1024));
                break;
            case SIZETYPE_MB:
                fileSizeLong= Double.valueOf(df.format((double) fileS / 1048576));
                break;
            case SIZETYPE_GB:
                fileSizeLong= Double.valueOf(df.format((double) fileS / 1073741824));
                break;
            default:
                break;
        }
        return fileSizeLong;
    }
    public   void deleteFiles(){
        deleteAllFiles(root);
    }
    private static void deleteAllFiles(File root) {
        File files[] = root.listFiles();
        if (files != null)
            for (File f : files) {
                if (f.isDirectory()) { // 判断是否为文件夹
                    System.out.print(f.toString());
                    deleteAllFiles(f);
                    System.out.print("删除!");
                    try {
                        f.delete();
                    } catch (Exception e) {
                    }
                } else {
                    if (f.exists()) { // 判断是否存在
                        deleteAllFiles(f);
                        try {
                            f.delete();
                        } catch (Exception e) {
                        }
                    }
                }
            }
    }
}

HTTP工具类:


/**
 * Title:HTTP工具类<br/>
 * Description: <br/>
 * Company:hiveview.com <br/>
 * Author:李文烙<br/>
 * Date:Jun 9, 2017<br/>
 */
public class HttpClientUtils {

    /**
     * 发送HTTP POST请求
     * 
     * @param url
     *            请求地址
     * @param params
     *            请求参数(键值对)
     * @return
     */
    public static String doPost(String url, Map<String, Object> params) {
        byte[] body = HttpClientUtils.doPostAsByte(url, params);
        if (body == null) {
            return "";
        }
        String _body = "";
        try {
            _body = new String(body, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return _body;
    }

    /**
     * 发送HTTP POST请求
     * 
     * @param url
     *            请求地址
     * @param params
     *            请求参数(键值对)
     * @return
     */
    public static byte[] doPostAsByte(String url, Map<String, Object> params) {
        try {
            // 获取连接
            URL _url = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) _url.openConnection();
            // 设置属性
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setAllowUserInteraction(true);
            connection.setConnectTimeout(20000);// 等待服务端连接4秒钟后超时
            connection.setReadTimeout(20000);// 等待服务端响应4秒钟后超时
            // 输出参数
            OutputStream outputStream = connection.getOutputStream();
            byte[] _params = HttpClientUtils.toByteArray(params);
            outputStream.write(_params);
            outputStream.flush();
            outputStream.close();
            // if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // 读取返回值
            InputStream inputStream = connection.getInputStream();
            return HttpClientUtils.readToArray(inputStream);
            // }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 发送HTTP POST请求
     * 
     * @param url
     *            请求地址
     * @param params
     *            请求参数(键值对)
     * @return
     */
    public static byte[] doPostAsByte(String url, String params) {
        try {
            // 获取连接
            URL _url = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) _url.openConnection();
            // 设置属性
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setAllowUserInteraction(true);
            connection.setConnectTimeout(20000);// 等待服务端连接4秒钟后超时
            connection.setReadTimeout(20000);// 等待服务端响应4秒钟后超时
            // 输出参数
            OutputStream outputStream = connection.getOutputStream();
            byte[] _params = params.getBytes();
            outputStream.write(_params);
            outputStream.flush();
            outputStream.close();
            // if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // 读取返回值
            InputStream inputStream = connection.getInputStream();
            return HttpClientUtils.readToArray(inputStream);
            // }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 发送HTTP GET请求
     * 
     * @param url
     * @param params
     * @return
     */
    public static String doGet(String url, Map<String, Object> params) {
        if (url == null || "".equals(url) || params == null) {
            return "URL/Param Error";
        }
        String queryString = HttpClientUtils.toQueryString(params);
        int endIndex = url.indexOf("?");
        if (endIndex != -1) {
            url = url.substring(0, endIndex) + "?" + queryString;
        } else {
            url = url + "?" + queryString;
        }
        return HttpClientUtils.doGet(url);
    }

    /**
     * 发送HTTP GET请求
     * 
     * @param url
     *            请求地址
     * @return
     */
    public static String doGet(String url) {
        byte[] body = HttpClientUtils.doGetAsByte(url);
        String _body = "";
        try {
            _body = new String(body, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return _body;
    }

    /**
     * 发送HTTP GET请求
     * 
     * @param url
     *            请求地址
     * @param params
     *            请求参数(键值对)
     * @return
     */
    public static byte[] doGetAsByte(String url, Map<String, Object> params) {
        String queryString = HttpClientUtils.toQueryString(params);
        int endIndex = url.indexOf("?");
        if (endIndex != -1) {
            url = url.substring(0, endIndex) + "?" + queryString;
        } else {
            url = url + "?" + queryString;
        }
        return HttpClientUtils.doGetAsByte(url);
    }

    /**
     * 发送HTTP GET请求
     * 
     * @param url
     *            请求地址
     * @return
     */
    public static byte[] doGetAsByte(String url) {
        try {
            // 获取连接
            URL _url = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) _url.openConnection();
            // 设置属性
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(20000);// 等待服务端连接4秒钟后超时
            connection.setReadTimeout(20000);// 等待服务端响应4秒钟后超时
            connection.connect();
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                // 读取返回值
                InputStream inputStream = connection.getInputStream();
                return HttpClientUtils.readToArray(inputStream);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 读取返回值,以字节数组方式返回
     * 
     * @param inputStream
     * @return
     */
    private static byte[] readToArray(InputStream inputStream) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            byte[] buffer = new byte[1024];
            int length = 0;
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return outputStream.toByteArray();
    }

    /**
     * Map转byte[]
     * 
     * @param params
     * @return
     */
    private static byte[] toByteArray(Map<String, Object> params) {
        return HttpClientUtils.toQueryString(params).getBytes();
    }

    /**
     * 转成键值对字符串
     * 
     * @param params
     * @return
     */
    public static String toQueryString(Map<String, Object> params) {
        StringBuffer buffer = new StringBuffer();
        Iterator<String> iterator = params.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            Object val = params.get(key);
            buffer.append("&").append(key).append("=").append(val);
        }
        return buffer.substring(1);
    }

    /**
     * @Title: doPostString
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @param @param url
     * @param @param params
     * @param @return 设定文件
     * @return String 返回类型
     * @throws
     */
    public static String doPostString(String url, String params) {
        byte[] body = HttpClientUtils.doPostAsByte(url, params);
        if (body == null) {
            return "";
        }
        String _body = "";
        try {
            _body = new String(body, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return _body;
    }

}

线程池工具类:

public class ThreadManager {
    private static final String TAG = ThreadManager.class.getSimpleName();
    public static final String DEFAULT_SINGLE_POOL_NAME = "DEFAULT_SINGLE_POOL_NAME";

    private static ThreadPoolProxy mLongPool = null;
    private static Object mLongLock = new Object();

    private static ThreadPoolProxy mShortPool = null;
    private static Object mShortLock = new Object();

    private static ThreadPoolProxy mDownloadPool = null;
    private static Object mDownloadLock = new Object();

    private static Map<String, ThreadPoolProxy> mMap = new HashMap<String, ThreadPoolProxy>();
    private static Object mSingleLock = new Object();

    /**
     * 获取下载线程
     */
    public static ThreadPoolProxy getDownloadPool() {
        synchronized (mDownloadLock) {
            if (mDownloadPool == null) {
                mDownloadPool = new ThreadPoolProxy(1, 1, 5L);
            }
            return mDownloadPool;
        }
    }

    /**
     * 获取一个用于执行长耗时任务的线程池,避免和短耗时任务处在同一个队列而阻塞了重要的短耗时任务,通常用来联网操作
     */
    public static ThreadPoolProxy getLongPool() {
        synchronized (mLongLock) {
            if (mLongPool == null) {
                mLongPool = new ThreadPoolProxy(5, 5, 5L);
            }
            return mLongPool;
        }
    }

    /**
     * 获取一个用于执行短耗时任务的线程池,避免因为和耗时长的任务处在同一个队列而长时间得不到执行,通常用来执行本地的IO/SQL
     */
    public static ThreadPoolProxy getShortPool() {
        synchronized (mShortLock) {
            if (mShortPool == null) {
                mShortPool = new ThreadPoolProxy(5, 5, 5L);
            }
            return mShortPool;
        }
    }

    /**
     * 获取一个单线程池,所有任务将会被按照加入的顺序执行,免除了同步开销的问题
     */
    public static ThreadPoolProxy getSinglePool() {
        return getSinglePool(DEFAULT_SINGLE_POOL_NAME);
    }

    /**
     * 获取一个单线程池,所有任务将会被按照加入的顺序执行,免除了同步开销的问题
     */
    public static ThreadPoolProxy getSinglePool(String name) {
        synchronized (mSingleLock) {
            ThreadPoolProxy singlePool = mMap.get(name);
            if (singlePool == null) {
                singlePool = new ThreadPoolProxy(1, 1, 5L);
                mMap.put(name, singlePool);
            }
            return singlePool;
        }
    }

    public static class ThreadPoolProxy {

        private ThreadPoolExecutor mPool;
        private int mCorePoolSize;
        private int mMaximumPoolSize;
        private long mKeepAliveTime;

        private ThreadPoolProxy(int corePoolSize, int maximumPoolSize, long keepAliveTime) {
            mCorePoolSize = corePoolSize;
            mMaximumPoolSize = maximumPoolSize;
            mKeepAliveTime = keepAliveTime;
        }

        /**
         * 执行任务,当线程池处于关闭,将会重新创建新的线程池
         */
        public synchronized void execute(Runnable run) {
            if (run == null) {
                return;
            }
            if (mPool == null || mPool.isShutdown()) {
                //参数说明
                //当线程池中的线程小于mCorePoolSize,直接创建新的线程加入线程池执行任务
                //当线程池中的线程数目等于mCorePoolSize,将会把任务放入任务队列BlockingQueue中
                //当BlockingQueue中的任务放满了,将会创建新的线程去执行,
                //但是当总线程数大于mMaximumPoolSize时,将会抛出异常,交给RejectedExecutionHandler处理
                //mKeepAliveTime是线程执行完任务后,且队列中没有可以执行的任务,存活的时间,后面的参数是时间单位
                //ThreadFactory是每次创建新的线程工厂
                mPool = new ThreadPoolExecutor(mCorePoolSize, mMaximumPoolSize, mKeepAliveTime, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), Executors.defaultThreadFactory(), new AbortPolicy());
            }
            mPool.execute(run);
        }

        /**
         * 取消线程池中某个还未执行的任务
         */
        public synchronized void cancel(Runnable run) {
            if (mPool != null && (!mPool.isShutdown() || mPool.isTerminating())) {
                mPool.getQueue().remove(run);
            }
        }

        /**
         * 取消线程池中某个还未执行的任务
         */
        public synchronized boolean contains(Runnable run) {
            if (mPool != null && (!mPool.isShutdown() || mPool.isTerminating())) {
                return mPool.getQueue().contains(run);
            } else {
                return false;
            }
        }

        /**
         * 立刻关闭线程池,并且正在执行的任务也将会被中断
         */
        public void stop() {
            if (mPool != null && (!mPool.isShutdown() || mPool.isTerminating())) {
                mPool.shutdownNow();
            }
        }

        /**
         * 平缓关闭单任务线程池,但是会确保所有已经加入的任务都将会被执行完毕才关闭
         */
        public synchronized void shutdown() {
            if (mPool != null && (!mPool.isShutdown() || mPool.isTerminating())) {
                mPool.shutdownNow();
            }
        }
    }
}

暂时先保存这些工具类,接下来会多上传一些工具类的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值