Android 封装的工具类

文章目录

      • 日志封装类-MyLog
      • 线程封装类-LocalThreadPools
      • 自定义进度条-LoadProgressbar
      • 解压缩类-ZipUtils
      • 本地数据库类-MySQLiteHelper
      • 访问webservice封装-HttpUtils
      • Toolbar封装类-MaterialToolbar
      • 网络请求框架-OkGo
      • 网络请求框架-OkHttp

日志封装类-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_DIRif (!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()){@Overridepublic 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 {@Overridepublic 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() {@Overridepublic 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();}@Overrideprotected 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);//创建ZIPoutZip = 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); // setparameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);parameters.setEncryptFiles(true);parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);// Set passwordparameters.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);}@Overridepublic void onCreate(SQLiteDatabase sqLiteDatabase) {//第一次创建数据库时,才会调用MyLog.e("mylog","创建数据库");sqLiteDatabase.execSQL(TableA.CREAT_TABLE(TableA.TABLE_NAME())); //创建表sqLiteDatabase.execSQL(TableB.CREAT_TABLE(TableB.TABLE_NAME())); //创建表}@Overridepublic 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"; //IDpublic static final String s1= "s1";//字段s1public static final String s1= "s2";//字段s2public static final String s1= "s3";//字段s3public static final String s1= "s4";//字段s4public static final String s1= "s5";//字段s5public static final String s1= "s6";//字段s6public 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;//由于是发送请求,所以是设置bodyOutenvelope.dotNet = false;//由于是.net开发的webserviceenvelope.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.MaterialToolbarandroid: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"/><itemandroid: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);}

布局与按钮事件

	@Overridepublic boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.input_menu, menu);return super.onCreateOptionsMenu(menu);}@Overridepublic 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 {@Overridepublic void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}@Overridepublic void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {if (chain == null) {throw new IllegalArgumentException("  Check Server x509Certificates is null");}}@Overridepublic 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 {@Overridepublic 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() {@Overridepublic void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}@Overridepublic void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}@Overridepublic 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() {@Overridepublic 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) {@Overridepublic void onStart(com.lzy.okgo.request.base.Request<File, ? extends com.lzy.okgo.request.base.Request> request) {super.onStart(request);MyLog.e("mylog","开始下载");}@Overridepublic void onSuccess(com.lzy.okgo.model.Response<File> response) {progress.getProgress(100,"success");}@Overridepublic void onError(com.lzy.okgo.model.Response<File> response) {super.onError(response);progress.getProgress(-1,"下载出错!");}@Overridepublic 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并配置自定义的TrustManagerOkHttpClient 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() {@Overridepublic void onFailure(@NotNull Call call, @NotNull IOException e) {progress.getProgress(-1,e.getMessage());}@Overridepublic void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {//3824043long 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();}}});}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/764458.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

罗格朗逸景PLUS IOT智能系统发布,为您提供更智能的生活体验!

罗格朗全新推出的逸景PLUS IOT智能系统现已正式上市,采用纤薄纯平的设计,功能丰富全面,支持灯光/温度/场景控制、背景音乐等多种功能,整合罗格朗IOT2.0系统,集成可视对讲,为用户打造更舒适、安全的智能生活。 罗格朗智能家居 罗格朗是全球电气与智能建筑系统专家,创立于1865年…

【3D reconstruction 学习笔记 第二部】

三维重建 3D reconstruction 4. 三维重建与极几何三角化&#xff08;线性解法&#xff09;三角化&#xff08;非线性解法&#xff09;多视图几何极几何极几何约束基础矩阵估计 5. 双目立体视觉重建6. 多视图重建7. SFM 系统设计8. SLAM系统设计 4. 三维重建与极几何 三角化&…

复试专业前沿问题问答合集8-3——RNN、Hadoop、GPT大语言模型

复试专业前沿问题问答合集8-3——RNN、Hadoop、GPT大语言模型 深度学习中的的RNN、Hadoop、GPT大语言模型的原理关系问答: GPT(Generative Pre-trained Transformer)和RNN(Recurrent Neural Network)是两种在自然语言处理(NLP)领域广泛使用的深度学习模型。它们在处理…

Orbit 使用指南 08 | 登记注册环境 | Isaac Sim | Omniverse

如是我闻&#xff1a; 在上一个指南中&#xff0c;我们学习了如何创建一个自定义的车杆环境。我们通过导入环境类及其配置类来手动创建了一个环境实例 # create environment configurationenv_cfg CartpoleEnvCfg()env_cfg.scene.num_envs args_cli.num_envs# setup RL envir…

在 Linux/Ubuntu/Debian 上安装 SQL Server 2019

Microsoft 为 Linux 发行版&#xff08;包括 Ubuntu&#xff09;提供 SQL Server。 以下是有关如何执行此操作的基本指南&#xff1a; 注册 Microsoft Ubuntu 存储库并添加公共存储库 GPG 密钥&#xff1a; sudo wget -qO- https://packages.microsoft.com/keys/microsoft.as…

SQL经典面试题

这里写目录标题 1 背概念2 学例子 1 背概念 1 事务 事务是最小的不可在分的工作单元&#xff0c;事务的操作要么同时成功,要么同时失败。 ACID: 原子性、一致性、隔离性、持久性 2 约束 主键约束&#xff1b;外键约束&#xff08;少用&#xff0c;会增加程序的耦合性&#xff…

【Golang星辰图】洞悉Go语言数据交换秘籍:遍历常用序列化策略和技术选型

Go语言中的序列化技术大盘点&#xff1a;解析内建格式与主流第三方库 前言: 随着现代软件开发中的数据交互需求不断增加&#xff0c;有效地进行数据编码与序列化已成为一项关键任务。各种不同的数据格式与序列化库不仅影响着程序性能&#xff0c;也直接影响到系统的互操作性和…

jeect-boot queryFieldBySql接口RCE漏洞(CVE-2023-4450)复现

jeect-boot积木报表由于未授权的 API /jmreport/queryFieldBySql 使用了 freemarker 解析 SQL 语句从而导致了 RCE 漏洞的产生。 1.漏洞级别 高危 2.漏洞搜索 fofa app"Jeecg-Boot 企业级快速开发平台"3.影响范围 JimuReport < 1.6.14.漏洞复现 这个漏洞的…

C/C++代码性能优化——编程实践

1. 编程实践 在一些关键的地方&#xff0c;相应的编程技巧能够给性能带来重大提升。 1.1. 参数传递 传递非基本类型时&#xff0c;使用引用或指针&#xff0c;这样可以避免传递过程中发生拷贝。参数根据是否需要返回&#xff0c;相应加上const修饰&#xff0c;代码更安全&am…

Redis 不再 “开源”,未来采用 SSPLv1 和 RSALv2 许可证

昨日&#xff0c;Redis 官方宣布了一项重要变更&#xff1a;他们将修改开源协议&#xff0c;未来所有版本将采用 “源代码可用” 的许可证。 具体来说&#xff0c;Redis 不再使用 BSD 3-Clause 开源协议进行分发。从 Redis 7.4 版本开始&#xff0c;Redis 将采用 SSPLv1 和 RSA…

dockers compose up 报no configuration file provided: not found

如果docker-compose文件不在当前路径的下一级&#xff1a; PS D:\code\GoLandProject\oneProject> docker compose up no configuration file provided: not found需要指定配置文件路径: PS D:\code\GoLandProject\oneProject> docker compose -f script/docker-compos…

如何运行vue项目

1. DOS 管理员模式进入项目目录 cd /d 路径 2、 删除 “node_modules”文件夹 和 package-lock.json &#xff0c; “node_modules”是vue项目的依赖包,package-lock.json记录了整个node_moudles文件夹的树状结构 del /s/f/q node_modules del /s/f/q package-lock.js…

css知识总结

1. 说一下CSS的盒模型。 在HTML页面中所有的元素都可以看成是一个盒子。 盒子的组成&#xff1a;内容content、内边距padding、边框border、外边距margin。 盒模型的类型&#xff1a; 标准盒模型&#xff1a;width contentIE盒模型&#xff08;怪异盒模型&#xff09;&#…

【WPF应用7】 基本控件-Grid 布局的详解与示例

引言 WPF&#xff08;Windows Presentation Foundation&#xff09;是.NET框架的一部分&#xff0c;它提供了一个用于创建桌面应用程序用户界面的框架。在WPF中&#xff0c;Grid布局是一个非常强大的布局工具&#xff0c;它允许开发者创建复杂的、响应迅速的用户界面布局。Grid…

增强现实:MATLAB在3D数学建模的关键作用

引言 MATLAB简介&#xff1a; MathWorks公司开发的MATLAB&#xff08;矩阵实验室&#xff09;是一个高性能的数值计算环境和第四代编程语言。它专门设计用于工程师和科学家进行算法开发、数据可视化、数据分析以及数值计算。MATLAB集成了一个编程环境&#xff0c;支持矩阵运算…

初学php反序列化

php中&#xff0c;序列化和反序列化是相对的两个过程&#xff0c;序列化是把变量或对象转化成字符串的过程 反序列化是把字符串转换为变量过着对象的过程 在php的反序列化中&#xff0c;存在类&#xff0c;当类被以特定的方式就会触发魔术方法&#xff0c;在实行序列化的过程…

设计模式(行为型设计模式——状态模式)

设计模式&#xff08;行为型设计模式——状态模式&#xff09; 状态模式 基本定义 对有状态的对象&#xff0c;把复杂的“判断逻辑”提取到不同的状态对象中&#xff0c;允许状态对象在其内部状态发生改变时改变其行为。 模式结构 Context&#xff08;环境类&#xff09;&…

复试专业前沿问题问答合集8-1——CNN、Transformer、TensorFlow、GPT

复试专业前沿问题问答合集8-1——CNN、Transformer、TensorFlow、GPT 深度学习中的CNN、Transformer、TensorFlow、GPT大语言模型的原理关系问答: Transformer与ChatGPT的关系 Transformer 是一种基于自注意力机制的深度学习模型,最初在论文《Attention is All You Need》…

CSS的使用与方法

什么是CSS CSS是层叠样式表。它是一种用于描述网页或者文档外观和样式的标记语言。 层级样式表&#xff1a;就是给HTML标签加样式的。 如果说HTML是个游戏英雄 、那么CSS就是游戏皮肤。 【一】注释语法 /* 注释 */ 【二】CSS的语法结构 选择符 {样式属性: 样式属性值;样…

深度学习新篇章:PyTorch在遥感地物分类的革命性应用

我国高分辨率对地观测系统重大专项已全面启动&#xff0c;高空间、高光谱、高时间分辨率和宽地面覆盖于一体的全球天空地一体化立体对地观测网逐步形成&#xff0c;将成为保障国家安全的基础性和战略性资源。未来10年全球每天获取的观测数据将超过10PB&#xff0c;遥感大数据时…