当前位置: 首页 > news >正文

企业网站素材图片小程序注册推广

企业网站素材图片,小程序注册推广,涪城网站建设,网站歌曲代码文章目录 日志封装类-MyLog线程封装类-LocalThreadPools自定义进度条-LoadProgressbar解压缩类-ZipUtils本地数据库类-MySQLiteHelper访问webservice封装-HttpUtilsToolbar封装类-MaterialToolbar网络请求框架-OkGo网络请求框架-OkHttp 日志封装类-MyLog 是对android log的封装… 文章目录 日志封装类-MyLog线程封装类-LocalThreadPools自定义进度条-LoadProgressbar解压缩类-ZipUtils本地数据库类-MySQLiteHelper访问webservice封装-HttpUtilsToolbar封装类-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数量*21*/private static final int MAXIMUM_POOL_SIZE CPU_COUNT * 21;/*** 等待线程存活时间*/private static final int KEEP_ALIVE_SECONDS 60;/*** 等待线程存活时间的单位*/private static final TimeUnit unit TimeUnit.MINUTES;private static final BlockingQueueRunnable 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,-----------ActiveCountgetActiveCount());MyLog.e(mylog,-----------PoolSizegetPoolSize());MyLog.e(mylog,-----------QueuegetQueue().size());MyLog.e(mylog,-----------finishgetCompletedTaskCount());}};//允许核心线程空闲超时时被回收threadPoolExecutor.allowCoreThreadTimeOut(true);THREAD_POOL_EXECUTOR threadPoolExecutor;}private class RejectedHandler implements RejectedExecutionHandler {Overridepublic void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {//可在这里做一些提示用户的操作Tools.showToast(mContext.get(),当前执行的任务过多请稍后再试);}}private WeakReferenceContext 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 ListRunnable 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 ;ListFile fileList new ArrayListFile();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);ArrayListFile filesToAdd new ArrayListFile();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.separatorXXXX; //需要创建的路径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:themestyle/ThemeOverlay.AppCompat.Dark.ActionBarandroid:idid/titlebarandroid:backgroundcolor/primary1stylestyle/Widget.MaterialComponents.Toolbar.Surfaceapp:layout_constraintTop_toTopOfparentapp:layout_constraintLeft_toLeftOfparentapp:layout_constraintRight_toRightOfparentandroid:layout_widthmatch_parentandroid:layout_heightwrap_contentapp:navigationIconmipmap/backapp:titleXXXXapp:titleTextColorcolor/whiteapp:titleCenteredtrueapp:titleTextAppearancestyle/Text18wbapp:subtitlexxxx年xx月xx日 星期xapp:subtitleTextColorcolor/whiteapp:subtitleCenteredtrueapp:subtitleTextAppearancestyle/Text12wapp:menumenu/scan_menu/配置文件 1、input_menu.xml ?xml version1.0 encodingutf-8? menu xmlns:androidhttp://schemas.android.com/apk/res/androidxmlns:apphttp://schemas.android.com/apk/res-auto!--showAsAction的值always一直显示ifRoom如果有地方就显示没有则隐藏never一直隐藏--item android:idid/ownerandroid:title个人中心android:iconmipmap/owner1app:showAsActionalways/ /menu2、scan_menu.xml ?xml version1.0 encodingutf-8? menu xmlns:androidhttp://schemas.android.com/apk/res/androidxmlns:apphttp://schemas.android.com/apk/res-auto!--showAsAction的值always一直显示ifRoom如果有地方就显示没有则隐藏never一直隐藏--item android:idid/cleanandroid:title一键清空android:iconmipmap/clean1app:showAsActionifRoom/itemandroid:idid/inputandroid:title行李补录android:iconmipmap/shoudongapp:showAsActionifRoom/!-- item-- !-- android:idid/setting-- !-- android:titleSetting-- !-- android:iconmipmap/ic_launcher-- !-- app:showAsActionnever/-- /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* Date2024/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* Date2024/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客户端等待服务器返回数据的时间* *///使用内存保持cookieapp退出后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, HashMapString,String hashMap, OkGoCallback callback){OkGo.Stringpost(getIP()method).params(hashMap).execute(new StringCallback() {Overridepublic void onSuccess(ResponseString response) {callback.callback(response.body());}});}下载 OkGo.Fileget(uploadUrl).tag(this)//.headers(header1, headerValue1)////.params(param1, paramValue1)//.execute(new FileCallback(saveFilePath,saveName) {Overridepublic void onStart(com.lzy.okgo.request.base.RequestFile, ? extends com.lzy.okgo.request.base.Request request) {super.onStart(request);MyLog.e(mylog,开始下载);}Overridepublic void onSuccess(com.lzy.okgo.model.ResponseFile response) {progress.getProgress(100,success);}Overridepublic void onError(com.lzy.okgo.model.ResponseFile 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\ne.getMessage());return error:\r\ne.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.w-s-a.com/news/931561/

相关文章:

  • 备案中又需要建设网站网站信息组织优化
  • 做网站推广需要什么asp响应式h5网站源码下载
  • 柳州建设网官方网站免费自助建站哪个平台好
  • 论坛网站模板源码下载网站建设与网页设计是什么
  • 跑流量的网站淘宝网站的建设目标是
  • 网站计费系统怎么做九一制作网站
  • 网红营销推广温州seo博客
  • 临沂网站制作定制现在比较流行的软件开发模型
  • 南宁企业建站系统做问卷调查哪个网站好
  • 能打开各种网站的浏览器推荐建设部的网站首页
  • 苏州高端网站建设开发wordpress 删除图片
  • saas网站开发外贸网站设计风格
  • c 手机网站开发湘阴网页定制
  • 阿里云虚拟主机搭建wordpressWordPress优化手机端
  • 湖北长安建设网站衡阳市做网站
  • 灯饰网站建设图片深圳做网站哪家公司好
  • 网站的构造有什么网站做生鲜配送的
  • 怎么在手机上做微电影网站小马厂网站建设
  • 网络广告投放网站中山网
  • 保定网站制作专业网页设计模板html代码运行
  • 中国专利申请网官网杭州seo优化
  • 杭州低价做网站网站系统功能流程图
  • 档案室建设网站名贵中药材初加工平台
  • 怎么做优惠券的网站wordpress加载速度
  • 手机网站 分辨率如何创建网站挣钱
  • 网站建设工作标准做模版网站
  • 免费注册微信网站怎样做天猫网站视频
  • 青海建设厅网站通知wordpress如何改文章id
  • 国外搜索网站建设支付网站备案
  • 合肥建站公司有哪家招聘的拼车平台网站开发