当前位置: 代码网 > it编程>App开发>Android > Android封装常用工具类的示例详解

Android封装常用工具类的示例详解

2024年05月15日 Android 我要评论
日志封装类-mylog是对androidlog的封装,封装后 可以设置显示级别/** * log的封装类,方便开启和关闭log */public class mylog { public sta

日志封装类-mylog

是对android log的封装,封装后 可以设置显示级别

/**
 * log的封装类,方便开启和关闭log
 */
public class mylog {
    public static final int verbose = 1;
    public static final int debug = 2;
    public static final int info = 3;
    public static final int warn = 4;
    public static final int error = 5;
    public static final int nothing = 6;
    public static final int level = verbose; //设置显示级别
    public static final string mylog_path_sdcard_dir = "/sdcard/scanzbar/log";// 日志文件在sdcard中的路径
    public static final string my_log_file_name = "log.txt";// 本类输出的日志文件名称


    public static void v(string tag, string msg){
        if(level <= verbose)
            log.v(tag,msg);
    }

    public static void d(string tag, string msg){
        if(level <= debug)
            log.d(tag,msg);
    }

    public static void i(string tag, string msg){
        if(level <= info)
            log.i(tag,msg);
    }

    public static void w(string tag, string msg){
        if(level <= warn)
            log.w(tag,msg);
    }

    public static void e(string tag, string msg){
        if(level <= error)
            log.e(tag,msg);
    }

	//调用该方法,可以将日志写入日志文件
	public static void loge(string tag, string msg){
        if(level <= error) {
            log.e(tag, msg);
            writelogtofile("error",tag,msg);
        }
    }

/**
     * 打开日志文件并写入日志
     * @param mylogtype
     * @param tag
     * @param text
     */
    private static void writelogtofile(string mylogtype, string tag, string text) {// 新建或打开日志文件
        date nowtime = new date();
        string needwritefiel = new simpledateformat(timeutil.sdf3).format(nowtime);
        string needwritemessage = new simpledateformat(timeutil.sdf1).format(nowtime) + " " + mylogtype + " " + tag + " " + text;
        file dirpath = environment.getexternalstoragedirectory();

        file dirsfile = new file(mylog_path_sdcard_dir);
        if (!dirsfile.exists()){
            dirsfile.mkdirs();
        }
        //创建日志文件
        file file = new file(dirsfile.tostring(), needwritefiel +".txt");// mylog_path_sdcard_dir
        if (!file.exists()) {
            try {
                //在指定的文件夹中创建文件
                boolean creatb = file.createnewfile();
                if(!creatb)
                    mylog.e("mylog","创建日志文件失败!");
            } catch (exception e) {
                e.printstacktrace();
            }
        }
        try(filewriter filerwriter = new filewriter(file, true);// 后面这个参数代表是不是要接上文件中原来的数据,不进行覆盖
            bufferedwriter bufwriter = new bufferedwriter(filerwriter)) {
            bufwriter.write(needwritemessage);
            bufwriter.newline();
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }

}

使用使用和正常log使用一样

mylog.e("mylog","123");
mylog.i("mylog","222");
...

线程封装类-localthreadpools

针对asynctask被弃用的替代

/**
 * @description todo(全局使用的线程池)
 */
public class localthreadpools {
    private static int threadnum = 0;
    private static string tag = localthreadpools.class.getsimplename();

    private static executorservice thread_pool_executor;

    /**
     * cpu数量
     */
    private static final int cpu_count = runtime.getruntime().availableprocessors();
    /**
     * 线程池数量
     */
    private static final int core_pool_size = math.max(2, math.min(cpu_count-1,4));
    /**
     * 最大线程数量 = cpu数量*2+1
     */
    private static final int maximum_pool_size = cpu_count * 2+1;
    /**
     * 等待线程存活时间
     */
    private static final int keep_alive_seconds = 60;
    /**
     * 等待线程存活时间的单位
     */
    private static final timeunit unit = timeunit.minutes;
    private static final blockingqueue<runnable> spoolworkqueue = new linkedblockingqueue<>(8);
    /**
     * 线程工厂
     */
    private static final threadfactory sthreadfactory = new threadfactory() {
        private final atomicinteger mcount = new atomicinteger(1);

        public thread newthread(runnable r) {
            threadnum++;
            mylog.e("mylog","线程工厂创建一个线程:"+threadnum+","+mcount.getandincrement());
            return new thread(r, "mangotask #" + mcount.getandincrement());
        }
    };

    private void initthreadpool() {
        mylog.e("mylog","core_pool_size:"+core_pool_size+",maximum_pool_size:"+maximum_pool_size+"," +
                "keep_alive_seconds:"+keep_alive_seconds+",");
        threadpoolexecutor threadpoolexecutor = new threadpoolexecutor(
                core_pool_size, maximum_pool_size, keep_alive_seconds, unit,
                spoolworkqueue, sthreadfactory,new rejectedhandler()){
            @override
            public void execute(runnable command) {
                super.execute(command);
                mylog.e("mylog","-----------activecount="+getactivecount());
                mylog.e("mylog","-----------poolsize="+getpoolsize());
                mylog.e("mylog","-----------queue="+getqueue().size());
                mylog.e("mylog","-----------finish="+getcompletedtaskcount());
            }
        };
        //允许核心线程空闲超时时被回收
        threadpoolexecutor.allowcorethreadtimeout(true);
        thread_pool_executor = threadpoolexecutor;
    }

    private class rejectedhandler implements rejectedexecutionhandler {

        @override
        public void rejectedexecution(runnable r, threadpoolexecutor executor) {
            //可在这里做一些提示用户的操作
            tools.showtoast(mcontext.get(),"当前执行的任务过多,请稍后再试");
        }
    }

    private weakreference<context> mcontext;
    private static localthreadpools instance;
    private localthreadpools(context context){
        mcontext = new weakreference<>(context);
        initthreadpool();
    }
    public static localthreadpools getinstance(context context){
        if (instance == null) {
            instance = new localthreadpools(context);
        }
        return instance;
    }

    public void execute(runnable command){
        thread_pool_executor.execute(command);
    }


    /**
     * 通过interrupt方法尝试停止正在执行的任务,但是不保证真的终止正在执行的任务
     * 停止队列中处于等待的任务的执行
     * 不再接收新的任务
     * @return 等待执行的任务列表
     */
    public static list<runnable> shutdownnow(){
        return thread_pool_executor.shutdownnow();
    }

    /**
     * 停止队列中处于等待的任务
     * 不再接收新的任务
     * 已经执行的任务会继续执行
     * 如果任务已经执行完了没有必要再调用这个方法
     */
    public void shutdown(){
        thread_pool_executor.shutdown();
        spoolworkqueue.clear();
    }

}

使用

localthreadpools.getinstance((testactivity) mview).execute(new runnable() {
    @override
    public void run() {
        //异步操作
    }            
});

自定义进度条-loadprogressbar

自定义进度条

/**
 * 进度条
 */
public class downloadprogressbar extends view {
    private paint paint = new paint(); // 绘制背景灰色线条画笔
    private paint painttext = new paint(); // 绘制下载进度画笔
    private float offset = 0f; // 下载偏移量
    private float maxvalue = 0f; // 进度的总大小
    private float currentvalue = 0f; // 当前进度
    private rect mbound = new rect(); // 获取百分比数字的长宽
    private string percentvalue = "0%"; // 要显示的现在百分比
    private float offsetright = 0f; // 灰色线条距离右边的距离
    private int textsize = sizeutils.sp2px(25); // 百分比的文字大小
    private float offsettop = sizeutils.dp2px(18); // 距离顶部的偏移量


    public downloadprogressbar(context context) {
        this(context, null);
    }

    public downloadprogressbar(context context, @nullable attributeset attrs) {
        this(context, attrs, 0);
    }

    public downloadprogressbar(context context, @nullable attributeset attrs, int defstyleattr) {
        super(context, attrs, defstyleattr);
        gettextwidth();
    }


    @override
    protected void ondraw(canvas canvas) {
        super.ondraw(canvas);
        // 绘制底色
        paint.setcolor(color.parsecolor("#eeeeee"));
        paint.setstrokewidth(sizeutils.dp2px(10));
        canvas.drawline(0, offsettop, getwidth() - offsetright, offsettop, paint);
        // 绘制进度条颜色
        paint.setcolor(color.parsecolor("#ff0000"));
        paint.setstrokewidth(sizeutils.dp2px(11));
        canvas.drawline(0, offsettop, offset, offsettop, paint);
        paint.setcolor(color.parsecolor("#ffffff"));
        paint.setstrokewidth(sizeutils.dp2px(1));
        painttext.setcolor(color.parsecolor("#ffffff"));
        painttext.settextsize(textsize);
        painttext.setantialias(true);
        painttext.gettextbounds(percentvalue, 0, percentvalue.length(), mbound);
        canvas.drawline(offset, offsettop, offset + mbound.width() + sizeutils.dp2px(4), offsettop, paint);
        canvas.drawtext(percentvalue, offset, offsettop + mbound.height() / 2 - sizeutils.dp2px(2), painttext);
    }

    public void setcurrentvalue(float currentvalue) {
        this.currentvalue = currentvalue;
        int value = (int) (currentvalue * 100 / maxvalue);
        if (value < 100 && value > 0) {
            percentvalue = value + "%";
        } else if (value <= 0) {
            percentvalue = "0%";
        } else {
            percentvalue = "100%";
        }
        calc();
        invalidate();
    }


    private void calc() {
        if (currentvalue < maxvalue) {
            offset = (getwidth() - offsetright) * currentvalue / maxvalue;
        } else {
            offset = getwidth() - offsetright;
        }
    }

    /**
     * 设置最大值
     *
     * @param maxvalue
     */
    public void setmaxvalue(int maxvalue) {
        this.maxvalue = maxvalue;
    }

    /**
     * 获取“100%”的宽度
     */
    public void gettextwidth() {
        paint paint = new paint();
        rect rect = new rect();
        paint.settextsize(textsize);
        paint.setantialias(true);
        paint.gettextbounds("100%", 0, "100%".length(), rect);
        offsetright = rect.width() + sizeutils.dp2px(5);;
    }
}

解压缩类-ziputils

解压缩

/**
 * 解压缩zip文件
 */
public class ziputils {

    public ziputils() {
    }

    /**
     * 根据byte数组,生成文件
     */
    public static void getfile(byte[] bfile, string filepath, string filename) {
        bufferedoutputstream bos = null;
        fileoutputstream fos = null;
        file file = null;
        try {
            file dir = new file(filepath);
            if (!dir.exists()) {//判断文件目录是否存在
                dir.mkdirs();
            }
            file = new file(filepath + filename);
            fos = new fileoutputstream(file);
            bos = new bufferedoutputstream(fos);
            bos.write(bfile);
        } catch (exception e) {
            e.printstacktrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (ioexception e1) {
                    e1.printstacktrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (ioexception e1) {
                    e1.printstacktrace();
                }
            }
        }
    }

    //  使用密码解压(图片不加密)
    public static boolean unzipfile1(string zipfilefullname, string filepath, string password) {
        try {
            zipfile zipfile = new zipfile(zipfilefullname);
            // 如果解压需要密码
            if (zipfile.isencrypted()) {
                zipfile.setpassword(password);
            }
            file file = new file(filepath);
            if (!file.getparentfile().exists()) {
                file.getparentfile().mkdirs();
            }
            zipfile.extractall(filepath);//提取所有文件
            return true;
        } catch (exception e) {
            e.printstacktrace();
            return false;
        }
    }

    //  使用密码解压
    public static boolean unzipfile(string zipfilefullname, string filepath, string password) {
        try {
            zipfile zipfile = new zipfile(zipfilefullname);
            // 如果解压需要密码
            if (zipfile.isencrypted()) {
                zipfile.setpassword(password);
            }
            file file = new file(filepath);
            if (!file.getparentfile().exists()) {
                file.getparentfile().mkdirs();
            }
            zipfile.extractall(filepath);//提取所有文件
//            压缩
            zipfolder(filepath, filepath + "01");
//            解压
            ziputils.unzipfolder(filepath + "01", filepath);
            return true;
        } catch (exception e) {
            e.printstacktrace();
            return false;
        }
    }

    /**
     * 解压zip到指定的路径
     *
     * @param zipfilestring zip的名称
     * @param outpathstring 要解压缩路径
     * @throws exception
     */
    public static void unzipfolder(string zipfilestring, string outpathstring)  {
        zipinputstream inzip = null;
        outputstream out = null;
        try{
            inzip = new zipinputstream(new fileinputstream(zipfilestring));
            zipentry zipentry;
            string szname = "";
            list<file> filelist = new arraylist<file>();
            while ((zipentry = inzip.getnextentry()) != null) {
                szname = zipentry.getname();
                if (zipentry.isdirectory()) {
                    //获取部件的文件夹名
                    szname = szname.substring(0, szname.length() - 1);
                    file folder = new file(outpathstring + file.separator + szname);
                    folder.mkdirs();
                } else {
                    file file = new file(outpathstring + file.separator + szname);
                    if (!file.exists()) {
                        filelist.add(file);
                        file.getparentfile().mkdirs();
                        file.createnewfile();
                    }
                    // 获取文件的输出流
//                fileoutputstream out = new fileoutputstream(file);
                    out = aesutil.encrypt(file, aesutil.tokey(myapplication.getinstance().getaeskey().getbytes()));// 加密
                    int len;
                    byte[] buffer = new byte[1024];
                    // 读取(字节)字节到缓冲区
                    while ((len = inzip.read(buffer)) != -1) {
                        // 从缓冲区(0)位置写入(字节)字节
                        out.write(buffer, 0, len);
                        out.flush();
                    }
                    out.close();
                }
            }
            inzip.close();
//        删除目录下多余文件夹
            file dirfile = new file(outpathstring);
            file[] files = dirfile.listfiles();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isdirectory()) {
                    deletedirectory(files[i].getabsolutepath());
                }
            }
        }catch (exception e){
            e.printstacktrace();
        }finally {
            if(inzip != null){
                safeclose(inzip);
            }
            if(out != null){
                safeclose(out);
            }
        }
    }
    public static void safeclose(outputstream fis){
        if(fis != null){
            try{
                fis.close();
            }catch (ioexception e){
                e.printstacktrace();
            }
        }
    }
    public static void safeclose(zipinputstream fis){
        if(fis != null){
            try{
                fis.close();
            }catch (ioexception e){
                e.printstacktrace();
            }
        }
    }

    /**
     * 压缩文件和文件夹
     *
     * @param srcfilestring 要压缩的文件或文件夹
     * @param zipfilestring 解压完成的zip路径
     * @throws exception
     */
    public static void zipfolder(string srcfilestring, string zipfilestring) {
        fileoutputstream fis = null;
        zipoutputstream outzip = null;
        try{
            fis = new fileoutputstream(zipfilestring);
            //创建zip
            outzip = new zipoutputstream(fis);
            //创建文件
            file file = new file(srcfilestring);
            //压缩
            zipfiles(file.getparent() + file.separator, file.getname(), outzip);
            //完成和关闭
            outzip.finish();
            outzip.close();
            fis.close();
        }catch (exception e){
            e.printstacktrace();
        }finally {
            if(fis != null){
                safeclose(fis);
            }
            if(outzip != null){
                safeclose1(outzip);
            }
        }
    }

    public static void safeclose(fileoutputstream fis){
        if(fis != null){
            try {
                fis.close();
            } catch (ioexception e) {
                e.printstacktrace();
            }
        }
    }
    public static void safeclose1(zipoutputstream fis){
        if(fis != null){
            try {
                fis.close();
            } catch (ioexception e) {
                e.printstacktrace();
            }
        }
    }

    /**
     * 压缩文件
     *
     * @param folderstring
     * @param filestring
     * @param zipoutputsteam
     * @throws exception
     */
    private static void zipfiles(string folderstring, string filestring, zipoutputstream zipoutputsteam) {
        fileinputstream inputstream = null;
        try{
            if (zipoutputsteam == null)
                return;
            file file = new file(folderstring + filestring);
            if (file.isfile()) {
                zipentry zipentry = new zipentry(filestring);
                inputstream = new fileinputstream(file);
                zipoutputsteam.putnextentry(zipentry);
                int len;
                byte[] buffer = new byte[4096];
                while ((len = inputstream.read(buffer)) != -1) {
                    zipoutputsteam.write(buffer, 0, len);
                }
                zipoutputsteam.closeentry();
            } else {
                //文件夹
                string filelist[] = file.list();
                //没有子文件和压缩
                if (filelist.length <= 0) {
                    zipentry zipentry = new zipentry(filestring + file.separator);
                    zipoutputsteam.putnextentry(zipentry);
                    zipoutputsteam.closeentry();
                }
                //子文件和递归
                for (int i = 0; i < filelist.length; i++) {
                    zipfiles(folderstring + filestring + "/", filelist[i], zipoutputsteam);
                }
            }
        }catch (exception e){
            e.printstacktrace();
        }finally {
            if(inputstream != null){
                safeclose(inputstream);
            }
        }
    }

    public static bitmap getbitmap(file photofile) {
        inputstream fis = null;
        try {
            fis = aesutil.decrypt(photofile, aesutil.tokey(myapplication.getinstance().getaeskey().getbytes()));
            return bitmapfactory.decodestream(fis);  ///把流转化为bitmap图片
        } catch (filenotfoundexception e) {
            e.printstacktrace();
            mylog.e("mylog", "e1:" + e.getmessage());
            return null;
        } catch (exception e) {
            e.printstacktrace();
            mylog.e("mylog", "e2:" + e.getmessage());
            return null;
        } finally {
            if(fis != null){
                safeclose(fis);
            }
        }
    }

    public static void safeclose(inputstream fis){
        if(fis != null){
            try{
                fis.close();
            }catch (ioexception e){
                e.printstacktrace();
            }
        }
    }

    public static file getphotofile(string nonet, string fileabsolutepath) {
        file file = new file(fileabsolutepath);
        file[] subfile = file.listfiles();
        if (subfile != null) {
            for (int i = 0; i < subfile.length; i++) {
                // 判断是否为文件夹
                /*if (subfile[i].isdirectory()) {
                    getphotofile(idnonet, subfile[i].getabsolutepath());
                } else {*/
                string filename = subfile[i].getname();
                if (!textutils.isempty(filename) && filename.length() >= 13 && nonet != null) {
                    string subfilename = filename.substring(filename.length() - 13, filename.length() - 4);
//                mylog.e("mylog", "subfilename:" + subfilename + "  nonet:" + nonet);
                    if (subfilename.equals(nonet)) {
                        mylog.e("mylog", "filename:" + filename);
                        return subfile[i];
                    }
                }
            }
        }
        return null;
    }

    /**
     * @param zipname  压缩文件的路径
     * @param filepath 被压缩文件的路径
     * @param password 加密
     * @description:压缩以及加密
     * @author: renbo
     * @date: 2021年5月19日 下午3:35:33
     */
    public static void unzippass(string zipname, string filepath, string password) throws zipexception {
        zipfile zipfile = new zipfile(zipname);
        arraylist<file> filestoadd = new arraylist<file>();
        file root = new file(filepath);
        file[] files = root.listfiles();
        for (file file : files) {
            if (file.isdirectory()) {
                filestoadd.add(new file(file.getabsolutepath()));
            } else {
                filestoadd.add(new file(file.getabsolutepath()));
            }
        }
        zipparameters parameters = new zipparameters();
        parameters.setcompressionmethod(zip4jconstants.comp_deflate); // set
        parameters.setcompressionlevel(zip4jconstants.deflate_level_normal);
        parameters.setencryptfiles(true);
        parameters.setencryptionmethod(zip4jconstants.enc_method_aes);
        parameters.setaeskeystrength(zip4jconstants.aes_strength_256);
        // set password
        parameters.setpassword(password);
        zipfile.addfiles(filestoadd, parameters);
    }

    /**
     * 删除单个文件
     *
     * @param filepath 被删除文件的文件名
     * @return 文件删除成功返回true,否则返回false
     */
    public static boolean deletefile(string filepath) {
        file file = new file(filepath);
        if (file.isfile() && file.exists()) {
            return file.delete();
        }
        return false;
    }

    /**
     * 删除文件夹以及目录下的文件
     *
     * @param filepath 被删除目录的文件路径
     * @return 目录删除成功返回true,否则返回false
     */
    public static boolean deletedirectory(string filepath) {
        boolean flag = false;
        //如果filepath不以文件分隔符结尾,自动添加文件分隔符
        if (!filepath.endswith(file.separator)) {
            filepath = filepath + file.separator;
        }
        file dirfile = new file(filepath);
        if (!dirfile.exists() || !dirfile.isdirectory()) {
            return false;
        }
        flag = true;
        file[] files = dirfile.listfiles();
        //遍历删除文件夹下的所有文件(包括子目录)
        for (int i = 0; i < files.length; i++) {
            if (files[i].isfile()) {
                //删除子文件
                flag = deletefile(files[i].getabsolutepath());
                if (!flag) break;
            } else {
                //删除子目录
                flag = deletedirectory(files[i].getabsolutepath());
                if (!flag) break;
            }
        }
        if (!flag) return false;
        //删除当前空目录
        return dirfile.delete();
    }

    /**
     * 根据路径删除指定的目录或文件,无论存在与否
     *
     * @param filepath 要删除的目录或文件
     * @return 删除成功返回 true,否则返回 false。
     */
    public static boolean deletefolder(string filepath) {
        file file = new file(filepath);
        if (!file.exists()) {
            return false;
        } else {
            if (file.isfile()) {
                // 为文件时调用删除文件方法
                return deletefile(filepath);
            } else {
                // 为目录时调用删除目录方法
                return deletedirectory(filepath);
            }
        }
    }

}

本地数据库类-mysqlitehelper

android 创建本地数据库

/**
 * 数据库帮助类
 */
public class mysqlitehelper extends sqliteopenhelper {
    private static string initsqlfile = environment.getexternalstoragedirectory().getabsolutepath();
    private static string realpath = initsqlfile+ file.separator+"xxxx"; //需要创建的路径
    private static string realfile = realpath + file.separator +"xxxx.db"; //需要创建的文件
    private static mysqlitehelper db;
    private static final int datebase_version = 1;  //定义版本号
    public static string getrealpath(){
        return realpath;
    }
    public static string getrealfile(){
        return realfile;
    }
    public static void closedb(){
        db.close();
    }

    //自定义构造方法,简化自动生成的构造方法,path 是主要指定创建db文件的路径
    public mysqlitehelper(context context){
        this(context,realfile,null,datebase_version);
        mylog.e("mylog","文件路径:"+realfile);
    }

    //实现接口必须实现的构造方法
    public mysqlitehelper(context context, string name, sqlitedatabase.cursorfactory factory, int version){
        super(context, name, factory, version);
    }

    @override
    public void oncreate(sqlitedatabase sqlitedatabase) {
        //第一次创建数据库时,才会调用
        mylog.e("mylog","创建数据库");
        sqlitedatabase.execsql(tablea.creat_table(tablea.table_name())); //创建表
        sqlitedatabase.execsql(tableb.creat_table(tableb.table_name())); //创建表
    }

    @override
    public void onupgrade(sqlitedatabase sqlitedatabase, int i, int i1) {
    }
}

tablea对于的类

/**
 * 对应数据表的类
 */
public class tablea {
    public static  string table_name(){
        return "table_a";
    }
    public static final string id = "id"; //id
    public static final string s1= "s1";//字段s1
    public static final string s1= "s2";//字段s2
    public static final string s1= "s3";//字段s3
    public static final string s1= "s4";//字段s4
    public static final string s1= "s5";//字段s5
    public static final string s1= "s6";//字段s6

    public static string creat_table(string tablename){
        return new stringbuffer().
                append("create table if not exists ").append(tablename).
                append("(").
                append(id).append(" integer primary key autoincrement,").
                append(s1).append(" text,").
                append(s2).append(" text,").
                append(s3).append(" text,").
         		append(s4).append(" text,").
         		append(s5).append(" text,").
                append(s6).append(" text").
                append(");").tostring();
    }
}

访问webservice封装-httputils

对访问webservice 接口的请求封装

引入的包

implementation files('libs\\ksoap2-android-assembly-3.3.0-jar-with-dependencies.jar')

代码

import org.ksoap2.serialization.soapobject;
import org.ksoap2.serialization.soapserializationenvelope;
import org.ksoap2.transport.httptransportse;
import org.xmlpull.v1.xmlpullparserexception;
import java.io.ioexception;
import java.util.base64;

public class httputils {
    private static final string servicenamesapce = "http://webservice.cps.xxx.com/";
    private static myapplication myapplication = myapplication.getinstance();
    private httputils() {
    }

    //    登录
    public static string login(string methodname, string username, string password,string pingid) {
        soapobject request = new soapobject(servicenamesapce, methodname);
        request.addproperty("username", jiami(username));
        request.addproperty("password", jiami(password));
        request.addproperty("pingid",jiami(pingid));
        request.addproperty("pingidly",null);
        return scop(request);
    }
 
    private static string scop(soapobject request) {
        //创建soapserializationenvelope 对象,同时指定soap版本号
        soapserializationenvelope envelope = new soapserializationenvelope(soapserializationenvelope.ver10);
        envelope.bodyout = request;//由于是发送请求,所以是设置bodyout
        envelope.dotnet = false;//由于是.net开发的webservice
        envelope.setoutputsoapobject(request);

        httptransportse httptransportse = new httptransportse(geturl(), 400000);
        try {
            httptransportse.call(null, envelope);//调用
        } catch (ioexception e) {
            e.printstacktrace();
            return "{\"error\":\"" + e.getmessage() + "\"}";
        } catch (xmlpullparserexception e) {
            e.printstacktrace();
            return "{\"error\":\"" + e.getmessage() + "\"}";
        }

        // 获取返回的数据
        soapobject object = (soapobject) envelope.bodyin;
        return object.getproperty(0).tostring();
    }

    public static string jiami(string str) { //加密
        return aesutil.aesencrypt(str, myapplication.getinstance().getaeskey());
    }
    public static string jiemi(string str){ //解密
        return aesutil.aesdecrypt(str,myapplication.getinstance().getaeskey());
    }
    public static string geturl(){
        return myapplication.getip()+myapplication.getip_suffix();
    }
}

toolbar封装类-materialtoolbar

布局文件

<com.google.android.material.appbar.materialtoolbar
        android:theme="@style/themeoverlay.appcompat.dark.actionbar"
        android:id="@+id/titlebar"
        android:background="@color/primary1"
        style="@style/widget.materialcomponents.toolbar.surface"
        app:layout_constrainttop_totopof="parent"
        app:layout_constraintleft_toleftof="parent"
        app:layout_constraintright_torightof="parent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:navigationicon="@mipmap/back"
        app:title="xxxx"
        app:titletextcolor="@color/white"
        app:titlecentered="true"
        app:titletextappearance="@style/text18wb"
        app:subtitle="xxxx年xx月xx日 星期x"
        app:subtitletextcolor="@color/white"
        app:subtitlecentered="true"
        app:subtitletextappearance="@style/text12w"
        app:menu="@menu/scan_menu"/>

配置文件

1、input_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <!--showasaction的值always一直显示,ifroom如果有地方就显示,没有则隐藏,never一直隐藏-->
    <item android:id="@+id/owner"
        android:title="个人中心"
        android:icon="@mipmap/owner1"
        app:showasaction="always"/>
</menu>

2、scan_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <!--showasaction的值always一直显示,ifroom如果有地方就显示,没有则隐藏,never一直隐藏-->
    <item android:id="@+id/clean"
        android:title="一键清空"
        android:icon="@mipmap/clean1"
        app:showasaction="ifroom"/>
    <item
        android:id="@+id/input"
        android:title="行李补录"
        android:icon="@mipmap/shoudong"
        app:showasaction="ifroom"/>

<!--    <item-->
<!--        android:id="@+id/setting"-->
<!--        android:title="setting"-->
<!--        android:icon="@mipmap/ic_launcher"-->
<!--        app:showasaction="never"/>-->
</menu>

初始化

private void inittoolbar(){
        flightinputbinding.titlebar.settitle("航班设置");
        flightinputbinding.titlebar.setsubtitle(myapplication.getdate_week());
        setsupportactionbar(flightinputbinding.titlebar);
    }

布局与按钮事件

	@override
    public boolean oncreateoptionsmenu(menu menu) {
        getmenuinflater().inflate(r.menu.input_menu, menu);
        return super.oncreateoptionsmenu(menu);
    }
    @override
    public boolean onoptionsitemselected(@nonnull menuitem item) {
        int id = item.getitemid();
        if(id == android.r.id.home){
            dialog.showfinishdialog(this, "确定要退出app么?",
                    () -> myapplication.finishallactivity());
        }else if(id == r.id.owner){
            intent i = new intent(flightinputactivity.this,infomationactivity.class);
            startactivityforresult(i,2001);
        }
        return super.onoptionsitemselected(item);
    }

网络请求框架-okgo

引入包

implementation 'com.lzy.net:okgo:3.0.4'

工具类

1、trustallcerts

此类用于绕过https验证

package com.kaiya.mvp.npm_ar.utils;
import java.security.securerandom;
import java.security.cert.certificateexception;
import java.security.cert.x509certificate;

import javax.net.ssl.hostnameverifier;
import javax.net.ssl.sslcontext;
import javax.net.ssl.sslsession;
import javax.net.ssl.sslsocketfactory;
import javax.net.ssl.trustmanager;
import javax.net.ssl.x509trustmanager;

/**
 * created by gang.qin
 * date:2024/3/19 15:05
 * 质量、速度、廉价,选择其中两个 --- 匿名
 */

//public class trustallcerts implements x509trustmanager {
//    @override
//    public void checkclienttrusted(x509certificate[] chain, string authtype) {}
//
//    @override
//    public void checkservertrusted(x509certificate[] chain, string authtype) {}
//
//    @override
//    public x509certificate[] getacceptedissuers() {return new x509certificate[0];}
//}

public class trustallcerts implements x509trustmanager {
    @override
    public void checkclienttrusted(x509certificate[] chain, string authtype) throws certificateexception {
    }

    @override
    public void checkservertrusted(x509certificate[] chain, string authtype) throws certificateexception {

        if (chain == null) {
            throw new illegalargumentexception("  check server x509certificates is null");
        }
    }

    @override
    public x509certificate[] getacceptedissuers() {
        return new x509certificate[0];
    }


    public static sslsocketfactory createsslsocketfactory() {
        sslsocketfactory ssffactory = null;

        try {
            sslcontext sc = sslcontext.getinstance("tls");
            sc.init(null, new trustmanager[]{new trustallcerts()}, new securerandom());

            ssffactory = sc.getsocketfactory();
        } catch (exception e) {
        }

        return ssffactory;
    }

    public static class trustallhostnameverifier implements hostnameverifier {
        @override
        public boolean verify(string hostname, sslsession session) {
            return true;
        }
    }


}

2、封装

package com.kaiya.mvp.npm_ar.utils;

import android.app.application;
import android.content.context;
import android.transition.transitionmanager;

import com.lzy.okgo.okgo;
import com.lzy.okgo.cookie.cookiejarimpl;
import com.lzy.okgo.cookie.store.memorycookiestore;
import com.lzy.okgo.interceptor.httplogginginterceptor;

import java.security.keymanagementexception;
import java.security.nosuchalgorithmexception;
import java.security.securerandom;
import java.security.cert.certificateexception;
import java.security.cert.x509certificate;
import java.util.concurrent.timeunit;
import java.util.logging.level;

import javax.net.ssl.hostnameverifier;
import javax.net.ssl.sslcontext;
import javax.net.ssl.sslsession;
import javax.net.ssl.trustmanager;
import javax.net.ssl.x509trustmanager;

import okhttp3.okhttpclient;

/**
 * created by gang.qin
 * date:2024/3/20 15:41
 * 质量、速度、廉价,选择其中两个 --- 匿名
 */
public class okgoutils {
    public static x509trustmanager xtm;
    public static sslcontext sslcontext;
    public static void initokgo(application application){
        xtm = new x509trustmanager() {
            @override
            public void checkclienttrusted(x509certificate[] x509certificates, string s) throws certificateexception {

            }

            @override
            public void checkservertrusted(x509certificate[] x509certificates, string s) throws certificateexception {

            }

            @override
            public x509certificate[] getacceptedissuers() {
                return new x509certificate[0];
            }
        };
        try {
            sslcontext = sslcontext.getinstance("ssl");

            sslcontext.init(null, new trustmanager[]{xtm}, new securerandom());

        } catch (nosuchalgorithmexception e) {
            e.printstacktrace();
        } catch (keymanagementexception e) {
            e.printstacktrace();
        }
        hostnameverifier do_not_verify = (hostname, session) -> true;
        //        okgo.getinstance().init(this); //最简单的配置 什么都不需要写 全部使用默认参数
        okhttpclient.builder builder = new okhttpclient.builder();
//可以使用okgo内置的log拦截器打印log,如果你觉得不好用,也可以自己写个,这个没有限制。
        httplogginginterceptor logginginterceptor = new httplogginginterceptor("okgo");
//log打印级别
        logginginterceptor.setprintlevel(httplogginginterceptor.level.body);
//log颜色级别
        logginginterceptor.setcolorlevel(level.all);
        builder.addinterceptor(logginginterceptor);
        //全局的读取超时时间
        builder.readtimeout(okgo.default_milliseconds, timeunit.milliseconds);
//全局的写入超时时间
        builder.writetimeout(okgo.default_milliseconds, timeunit.milliseconds);
//全局的连接超时时间
        builder.connecttimeout(okgo.default_milliseconds, timeunit.milliseconds);
        /*
     *  connecttimeout:指客户端和服务器 建立通道 的时间
        writetimeout:客户端把数据写出去需要的时间
        readtimeout:客户端等待服务器返回数据的时间
        * */
        //使用内存保持cookie,app退出后,cookie消失
        builder.cookiejar(new cookiejarimpl(new memorycookiestore()));
        if(sslcontext != null){
            builder.sslsocketfactory(sslcontext.getsocketfactory(),xtm)
                    .hostnameverifier(do_not_verify)
                    .build();
        }else{
            mylog.e("mylog","过滤器出错!");
        }
        okgo.getinstance().init(application)//必须调用初始化
                .setokhttpclient(builder.build())  //建议设置okhttpclient,不设置将使用默认的
                .setretrycount(1); //超时重连,本身1次,我这边设置1次,总共2次访问
    }

    public static okhttpclient initokhttp(){
        okhttpclient client = new okhttpclient.builder()
                .sslsocketfactory(trustallcerts.createsslsocketfactory())
                .hostnameverifier(new trustallcerts.trustallhostnameverifier())
                .build();
        return client;
    }
}

post请求

        private static void okgopost(string method, hashmap<string,string> hashmap, okgocallback callback){
        okgo.<string>post(getip()+method)
                .params(hashmap)
                .execute(new stringcallback() {
                    @override
                    public void onsuccess(response<string> response) {
                        callback.callback(response.body());
                    }
                });
    }

下载

     okgo.<file>get(uploadurl)
                .tag(this)
                //.headers("header1", "headervalue1")//
                //.params("param1", "paramvalue1")//
                .execute(new filecallback(
                        savefilepath,
                        savename
                ) {
                    @override
                    public void onstart(com.lzy.okgo.request.base.request<file, ? extends com.lzy.okgo.request.base.request> request) {
                        super.onstart(request);
                        mylog.e("mylog","开始下载");
                    }

                    @override
                    public void onsuccess(com.lzy.okgo.model.response<file> response) {
                        progress.getprogress(100,"success");
                    }

                    @override
                    public void onerror(com.lzy.okgo.model.response<file> response) {
                        super.onerror(response);
                        progress.getprogress(-1,"下载出错!");

                    }

                    @override
                    public void downloadprogress(com.lzy.okgo.model.progress pp) {
                        super.downloadprogress(pp);
                        int ppi = (int)(pp.fraction * 100);
                        mylog.e("mylog","progress:"+ppi);
                        progress.getprogress(ppi,"");
                    }
                });

网络请求框架-okhttp

引入包

implementation 'com.squareup.okhttp3:okhttp:4.10.0'

封装

trustallcerts类 在okgo中 。

 private static string okhttp(string method , string json){
        mylog.e("mylog-url",getip()+method);
                okhttpclient client = new okhttpclient.builder()
                .sslsocketfactory(trustallcerts.createsslsocketfactory()) //绕过https
                .hostnameverifier(new trustallcerts.trustallhostnameverifier()) //绕过https
                .build();
        requestbody body = requestbody.create(json, json);
        request request = new request.builder()
                .url( getip()+method )
                .post(body)
                .build();
        try{
            response response = client.newcall(request).execute();
            return objects.requirenonnull(response.body()).string();
        }catch (exception e){
            mylog.e("mylog","error:\r\n"+e.getmessage());
            return "error:\r\n"+e.getmessage();
        }
    }

调用

getlist list = new getlist(flightdate,flightno,sourceairport, myapplication.getappip()); //参数类
//list.tostring() 为 类转json字符串
string response = okhttp(get_list,list.tostring());

下载

/**
     *
     * @param uploadurl 下载路径
     * @param savefilepath 保存路径
     * @param savename 保存文件名 ,如 xxx.apk
     * @param progress 回调函数,获取下载进度
     */
    public void downloadapk(string uploadurl,string savefilepath,string savename,progress progress) {
        // 创建okhttpclient并配置自定义的trustmanager
        okhttpclient client = new okhttpclient.builder()
                .sslsocketfactory(trustallcerts.createsslsocketfactory())
                .hostnameverifier(new trustallcerts.trustallhostnameverifier())
                .build();
        request request = new request.builder()
                .url(uploadurl)
                .build();
        call call = client.newcall(request);
        call.enqueue(new callback() {
            @override
            public void onfailure(@notnull call call, @notnull ioexception e) {
                progress.getprogress(-1,e.getmessage());
            }

            @override
            public void onresponse(@notnull call call, @notnull response response) throws ioexception {
                //3824043
                long filemax = response.body().contentlength();
                inputstream inputstream = objects.requirenonnull(response.body()).bytestream();
                file target = new file(savefilepath,savename);
                fileoutputstream fileoutputstream = new fileoutputstream(target);

                try {
                    byte[] buffer = new byte[2048];
                    int len;
                    while ((len = inputstream.read(buffer)) != -1) {
                        fileoutputstream.write(buffer, 0, len);
                        int p =  (int) ((target.length() * 100) / filemax);
                        progress.getprogress(p,"");
                    }
                    fileoutputstream.flush();
                } catch (ioexception e) {
                    e.printstacktrace();
                }
            }
        });

    }

以上就是android封装常用工具类的示例详解的详细内容,更多关于android工具类的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com