欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android封裝常用工具類的示例詳解

 更新時(shí)間:2024年03月24日 11:09:21   作者:xianKOG  
這篇文章主要為大家整理了一些Android封裝的常用工具類,包括日志封裝類、線程封裝類、解壓縮類等,文中的示例代碼講解詳細(xì),有需要的可以參考下

日志封裝類-MyLog

是對(duì)android log的封裝,封裝后 可以設(shè)置顯示級(jí)別

/**
 * Log的封裝類,方便開啟和關(guān)閉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; //設(shè)置顯示級(jí)別
    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);
    }

	//調(diào)用該方法,可以將日志寫入日志文件
	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();
        }
        //創(chuàng)建日志文件
        File file = new File(dirsFile.toString(), needWriteFiel +".txt");// MYLOG_PATH_SDCARD_DIR
        if (!file.exists()) {
            try {
                //在指定的文件夾中創(chuàng)建文件
                boolean creatB = file.createNewFile();
                if(!creatB)
                    MyLog.e("mylog","創(chuàng)建日志文件失?。?);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try(FileWriter filerWriter = new FileWriter(file, true);// 后面這個(gè)參數(shù)代表是不是要接上文件中原來的數(shù)據(jù),不進(jìn)行覆蓋
            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

針對(duì)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數(shù)量
     */
    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    /**
     * 線程池?cái)?shù)量
     */
    private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT-1,4));
    /**
     * 最大線程數(shù)量 = CPU數(shù)量*2+1
     */
    private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2+1;
    /**
     * 等待線程存活時(shí)間
     */
    private static final int KEEP_ALIVE_SECONDS = 60;
    /**
     * 等待線程存活時(shí)間的單位
     */
    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","線程工廠創(chuàng)建一個(gè)線程:"+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());
            }
        };
        //允許核心線程空閑超時(shí)時(shí)被回收
        threadPoolExecutor.allowCoreThreadTimeOut(true);
        THREAD_POOL_EXECUTOR = threadPoolExecutor;
    }

    private class RejectedHandler implements RejectedExecutionHandler {

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            //可在這里做一些提示用戶的操作
            Tools.showToast(mContext.get(),"當(dāng)前執(zhí)行的任務(wù)過多,請(qǐng)稍后再試");
        }
    }

    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方法嘗試停止正在執(zhí)行的任務(wù),但是不保證真的終止正在執(zhí)行的任務(wù)
     * 停止隊(duì)列中處于等待的任務(wù)的執(zhí)行
     * 不再接收新的任務(wù)
     * @return 等待執(zhí)行的任務(wù)列表
     */
    public static List<Runnable> shutdownNow(){
        return THREAD_POOL_EXECUTOR.shutdownNow();
    }

    /**
     * 停止隊(duì)列中處于等待的任務(wù)
     * 不再接收新的任務(wù)
     * 已經(jīng)執(zhí)行的任務(wù)會(huì)繼續(xù)執(zhí)行
     * 如果任務(wù)已經(jīng)執(zhí)行完了沒有必要再調(diào)用這個(gè)方法
     */
    public void shutDown(){
        THREAD_POOL_EXECUTOR.shutdown();
        sPoolWorkQueue.clear();
    }

}

使用

LocalThreadPools.getInstance((TestActivity) mView).execute(new Runnable() {
    @Override
    public void run() {
        //異步操作
    }            
});

自定義進(jìn)度條-LoadProgressbar

自定義進(jìn)度條

/**
 * 進(jìn)度條
 */
public class DownLoadProgressbar extends View {
    private Paint paint = new Paint(); // 繪制背景灰色線條畫筆
    private Paint paintText = new Paint(); // 繪制下載進(jìn)度畫筆
    private float offset = 0f; // 下載偏移量
    private float maxvalue = 0f; // 進(jìn)度的總大小
    private float currentValue = 0f; // 當(dāng)前進(jìn)度
    private Rect mBound = new Rect(); // 獲取百分比數(shù)字的長寬
    private String percentValue = "0%"; // 要顯示的現(xiàn)在百分比
    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);
        // 繪制進(jìn)度條顏色
        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;
        }
    }

    /**
     * 設(shè)置最大值
     *
     * @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() {
    }

    /**
     * 根據(jù)byte數(shù)組,生成文件
     */
    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];
                    // 讀?。ㄗ止?jié))字節(jié)到緩沖區(qū)
                    while ((len = inZip.read(buffer)) != -1) {
                        // 從緩沖區(qū)(0)位置寫入(字節(jié))字節(jié)
                        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);
            //創(chuàng)建ZIP
            outZip = new ZipOutputStream(fis);
            //創(chuàng)建文件
            File file = new File(srcFileString);
            //壓縮
            ZipFiles(file.getParent() + File.separator, file.getName(), outZip);
            //完成和關(guān)閉
            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);  ///把流轉(zhuǎn)化為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);
    }

    /**
     * 刪除單個(gè)文件
     *
     * @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不以文件分隔符結(jié)尾,自動(dòng)添加文件分隔符
        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;
        //刪除當(dāng)前空目錄
        return dirFile.delete();
    }

    /**
     * 根據(jù)路徑刪除指定的目錄或文件,無論存在與否
     *
     * @param filePath 要?jiǎng)h除的目錄或文件
     * @return 刪除成功返回 true,否則返回 false。
     */
    public static boolean DeleteFolder(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return false;
        } else {
            if (file.isFile()) {
                // 為文件時(shí)調(diào)用刪除文件方法
                return deleteFile(filePath);
            } else {
                // 為目錄時(shí)調(diào)用刪除目錄方法
                return deleteDirectory(filePath);
            }
        }
    }

}

本地?cái)?shù)據(jù)庫類-MySQLiteHelper

Android 創(chuàng)建本地?cái)?shù)據(jù)庫

/**
 * 數(shù)據(jù)庫幫助類
 */
public class MySQLiteHelper extends SQLiteOpenHelper {
    private static String initSqlFile = Environment.getExternalStorageDirectory().getAbsolutePath();
    private static String REALPATH = initSqlFile+ File.separator+"XXXX"; //需要?jiǎng)?chuàng)建的路徑
    private static String REALFILE = REALPATH + File.separator +"xxxx.db"; //需要?jiǎng)?chuàng)建的文件
    private static MySQLiteHelper db;
    private static final int DATEBASE_VERSION = 1;  //定義版本號(hào)
    public static String getRealPath(){
        return REALPATH;
    }
    public static String getRealFile(){
        return REALFILE;
    }
    public static void CloseDB(){
        db.close();
    }

    //自定義構(gòu)造方法,簡化自動(dòng)生成的構(gòu)造方法,path 是主要指定創(chuàng)建db文件的路徑
    public MySQLiteHelper(Context context){
        this(context,REALFILE,null,DATEBASE_VERSION);
        MyLog.e("mylog","文件路徑:"+REALFILE);
    }

    //實(shí)現(xiàn)接口必須實(shí)現(xiàn)的構(gòu)造方法
    public MySQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version){
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        //第一次創(chuàng)建數(shù)據(jù)庫時(shí),才會(huì)調(diào)用
        MyLog.e("mylog","創(chuàng)建數(shù)據(jù)庫");
        sqLiteDatabase.execSQL(TableA.CREAT_TABLE(TableA.TABLE_NAME())); //創(chuàng)建表
        sqLiteDatabase.execSQL(TableB.CREAT_TABLE(TableB.TABLE_NAME())); //創(chuàng)建表
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    }
}

TableA對(duì)于的類

/**
 * 對(duì)應(yīng)數(shù)據(jù)表的類
 */
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

對(duì)訪問webservice 接口的請(qǐng)求封裝

引入的包

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) {
        //創(chuàng)建SoapSerializationEnvelope 對(duì)象,同時(shí)指定soap版本號(hào)
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER10);
        envelope.bodyOut = request;//由于是發(fā)送請(qǐng)求,所以是設(shè)置bodyOut
        envelope.dotNet = false;//由于是.net開發(fā)的webservice
        envelope.setOutputSoapObject(request);

        HttpTransportSE httpTransportSE = new HttpTransportSE(getURl(), 400000);
        try {
            httpTransportSE.call(null, envelope);//調(diào)用
        } catch (IOException e) {
            e.printStackTrace();
            return "{\"error\":\"" + e.getMessage() + "\"}";
        } catch (XmlPullParserException e) {
            e.printStackTrace();
            return "{\"error\":\"" + e.getMessage() + "\"}";
        }

        // 獲取返回的數(shù)據(jù)
        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="個(gè)人中心"
        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="行李補(bǔ)錄"
        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("航班設(shè)置");
        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);
    }

網(wǎng)絡(luò)請(qǐng)求框架-OkGo

引入包

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

工具類

1、TrustAllCerts

此類用于繞過https驗(yàn)證

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
 * 質(zhì)量、速度、廉價(jià),選擇其中兩個(gè) --- 匿名
 */

//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
 * 質(zhì)量、速度、廉價(jià),選擇其中兩個(gè) --- 匿名
 */
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); //最簡單的配置 什么都不需要寫 全部使用默認(rèn)參數(shù)
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
//可以使用OkGo內(nèi)置的log攔截器打印log,如果你覺得不好用,也可以自己寫個(gè),這個(gè)沒有限制。
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
//log打印級(jí)別
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
//log顏色級(jí)別
        loggingInterceptor.setColorLevel(Level.ALL);
        builder.addInterceptor(loggingInterceptor);
        //全局的讀取超時(shí)時(shí)間
        builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
//全局的寫入超時(shí)時(shí)間
        builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
//全局的連接超時(shí)時(shí)間
        builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
        /*
     *  connectTimeout:指客戶端和服務(wù)器 建立通道 的時(shí)間
        writeTimeout:客戶端把數(shù)據(jù)寫出去需要的時(shí)間
        readTimeout:客戶端等待服務(wù)器返回?cái)?shù)據(jù)的時(shí)間
        * */
        //使用內(nèi)存保持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","過濾器出錯(cuò)!");
        }
        OkGo.getInstance().init(application)//必須調(diào)用初始化
                .setOkHttpClient(builder.build())  //建議設(shè)置OkHttpClient,不設(shè)置將使用默認(rèn)的
                .setRetryCount(1); //超時(shí)重連,本身1次,我這邊設(shè)置1次,總共2次訪問
    }

    public static OkHttpClient initOkhttp(){
        OkHttpClient client = new OkHttpClient.Builder()
                .sslSocketFactory(TrustAllCerts.createSSLSocketFactory())
                .hostnameVerifier(new TrustAllCerts.TrustAllHostnameVerifier())
                .build();
        return client;
    }
}

POST請(qǐng)求

        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,"下載出錯(cuò)!");

                    }

                    @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,"");
                    }
                });

網(wǎng)絡(luò)請(qǐng)求框架-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();
        }
    }

調(diào)用

GetList list = new GetList(flightDate,flightNo,sourceAirport, myApplication.getAppIp()); //參數(shù)類
//list.toString() 為 類轉(zhuǎn)json字符串
String response = okhttp(GET_LIST,list.toString());

下載

/**
     *
     * @param uploadUrl 下載路徑
     * @param saveFilePath 保存路徑
     * @param saveName 保存文件名 ,如 XXX.apk
     * @param progress 回調(diào)函數(shù),獲取下載進(jìn)度
     */
    public void downloadApk(String uploadUrl,String saveFilePath,String saveName,Progress progress) {
        // 創(chuàng)建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封裝常用工具類的示例詳解的詳細(xì)內(nèi)容,更多關(guān)于Android工具類的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Android支付寶支付封裝代碼

    Android支付寶支付封裝代碼

    這篇文章主要介紹了Android支付寶支付封裝代碼,Android支付的時(shí)候肯定會(huì)使用支付寶進(jìn)行支付,封裝可以簡化操作步驟,感興趣的小伙伴們可以參考一下
    2015-12-12
  • Android自定義Dialog實(shí)現(xiàn)通用圓角對(duì)話框

    Android自定義Dialog實(shí)現(xiàn)通用圓角對(duì)話框

    這篇文章主要為大家詳細(xì)介紹了Android自定義Dialog實(shí)現(xiàn)通用圓角對(duì)話框,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-11-11
  • android流式布局onLayout()方法詳解

    android流式布局onLayout()方法詳解

    這篇文章主要為大家詳細(xì)介紹了android流式布局的onLayout()方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-06-06
  • Android RecyclerView實(shí)現(xiàn)下拉刷新和上拉加載

    Android RecyclerView實(shí)現(xiàn)下拉刷新和上拉加載

    這篇文章主要介紹了Android RecyclerView實(shí)現(xiàn)下拉刷新和上拉加載的相關(guān)資料,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2016-05-05
  • Android布局控件DrawerLayout實(shí)現(xiàn)完美側(cè)滑效果

    Android布局控件DrawerLayout實(shí)現(xiàn)完美側(cè)滑效果

    這篇文章主要為大家詳細(xì)介紹了Android布局控件DrawerLayout實(shí)現(xiàn)完美側(cè)滑效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-08-08
  • Android 組件Gallery和GridView示例講解

    Android 組件Gallery和GridView示例講解

    本文主要講解Android 組件Gallery和GridView,這里詳細(xì)介紹組件Gallery和GridView的知識(shí)要點(diǎn),并附示例代碼和實(shí)現(xiàn)效果圖,有興趣的小伙伴可以參考下
    2016-08-08
  • Android開發(fā) -- 控件的顯示與隱藏 setVisibility View.VISIBLE View.INVISIBLE View.GONE

    Android開發(fā) -- 控件的顯示與隱藏 setVisibility View.VISIBLE View.INVISI

    本文簡單介紹在Android開發(fā)中控件的顯示與隱藏幾種常見的屬性,給大家一個(gè)參考,希望對(duì)大家學(xué)習(xí)有所幫助。
    2016-06-06
  • 基于將Android工程做成jar包和資源文件的解決方法

    基于將Android工程做成jar包和資源文件的解決方法

    有時(shí)候,我們希望將我們的Android工程提供給第三方開發(fā)者使用。這個(gè)時(shí)候,最普遍的做法,就是提供一個(gè)jar包和一堆資源文件,第三方開發(fā)者可以將資源文件拷貝到Android工程的相應(yīng)目錄下,同時(shí)引用我們提供的jar包,就可以使用我們提供的相應(yīng)API了
    2013-05-05
  • Flutter音樂播放插件audioplayers使用步驟詳解

    Flutter音樂播放插件audioplayers使用步驟詳解

    audioplayers是一個(gè)可以支持同時(shí)播放多個(gè)音頻文件的Flutter的插件,可以播放多個(gè)同時(shí)的音頻文件,這篇文章主要介紹了audioplayers的使用步驟,感興趣想要詳細(xì)了解可以參考下文
    2023-05-05
  • Flutter的鍵值存儲(chǔ)數(shù)據(jù)庫使用示例詳解

    Flutter的鍵值存儲(chǔ)數(shù)據(jù)庫使用示例詳解

    這篇文章主要為大家介紹了Flutter的鍵值存儲(chǔ)數(shù)據(jù)庫使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-08-08

最新評(píng)論