初始化

This commit is contained in:
2022-08-24 09:32:54 +08:00
parent 0d349c559c
commit 8e4d517c40
800 changed files with 74927 additions and 20 deletions
@@ -0,0 +1,37 @@
package com.arpa.hndahesudintocctmsdriver.util;
import android.os.Build;
import androidx.annotation.RequiresApi;
import java.util.Base64;
/**
* @author hlh
* @version 1.0.0
* @date 2022/1/25 17:22
* @description:
*/
public class Base64Util {
@RequiresApi(api = Build.VERSION_CODES.O)
public static void base64(String str) {
byte[] bytes = str.getBytes();
//Base64 加密
String encoded = Base64.getEncoder().encodeToString(bytes);
System.out.println("Base 64 加密后:" + encoded);
//Base64 解密
byte[] decoded = Base64.getDecoder().decode(encoded);
String decodeStr = new String(decoded);
System.out.println("Base 64 解密后:" + decodeStr);
System.out.println();
}
}
@@ -0,0 +1,664 @@
package com.arpa.hndahesudintocctmsdriver.util;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.text.TextUtils;
import android.util.Base64;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.ScrollView;
import androidx.annotation.DrawableRes;
import androidx.annotation.Nullable;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* @author hlh
* @version 1.0.0
* @date 2022/3/7 17:55
* @description:
*/
public class BitmapUtil {
private static RequestOptions options;
static {
initOptions();
}
private static void initOptions() {
options = new RequestOptions()
// .placeholder(R.drawable.ic_image_default) //加载成功之前占位图
// .error(R.drawable.ic_image_default) //加载错误之后的错误图
.dontAnimate()
// .override(400,400) //指定图片的尺寸
//指定图片的缩放类型为fitCenter (等比例缩放图片,宽或者是高等于ImageView的宽或者是高。)
// .fitCenter()
//指定图片的缩放类型为centerCrop (等比例缩放图片,直到图片的狂高都大于等于ImageView的宽度,然后截取中间的显示。)
// .centerCrop()//指定图片的缩放类型为centerCrop
// .circleCrop()//指定图片为圆形
// .skipMemoryCache(true) //跳过内存缓存
.diskCacheStrategy(DiskCacheStrategy.ALL); //缓存所有版本的图像
// .diskCacheStrategy(DiskCacheStrategy.NONE) //跳过磁盘缓存
// .diskCacheStrategy(DiskCacheStrategy.DATA) //只缓存原来分辨率的图片
// .diskCacheStrategy(DiskCacheStrategy.RESOURCE); //只缓存最终的图片
}
private static RequestOptions buildOptions(@DrawableRes int res) {
RequestOptions options = new RequestOptions()
.placeholder(res) //加载成功之前占位图
.error(res) //加载错误之后的错误图
.dontAnimate()
.diskCacheStrategy(DiskCacheStrategy.ALL);
return options;
}
/**
* 显示gif
*
* @param context
* @param url
* @param imageView
*/
public static void showGIF(Context context, String url, ImageView imageView) {
Glide.with(context)
.asGif()
.load(url)
.apply(options)
.into(imageView);
}
/**
* 显示gif,自定义默认图
*
* @param context
* @param url
* @param res
* @param imageView
*/
public static void showGIF(Context context, String url, @DrawableRes int res, ImageView imageView) {
Glide.with(context)
.asGif()
.load(url)
.apply(buildOptions(res))
.into(imageView);
}
/**
* 显示图片,自定义option
*
* @param context
* @param url
* @param imageView
*/
public static void showImage(Context context, String url, RequestOptions options, ImageView imageView) {
Glide.with(context)
.load(url)
.apply(options)
.into(imageView);
}
/**
* 显示图片,先显示默认图
*
* @param context
* @param url
* @param imageView
*/
public static void showImage(Context context, String url, ImageView imageView) {
Glide.with(context)
.load(url)
.apply(options)
.into(imageView);
}
/**
* 显示图片,先显示默认图
*
* @param context
* @param url
* @param imageView
*/
public static void showImage(Context context, String url, ImageView imageView, RequestListener<Drawable> callback) {
Glide.with(context)
.load(url)
.apply(options)
.listener(callback)
.into(imageView);
}
/**
* 显示图片,先显示默认图
*
* @param context
* @param url
* @param imageView
*/
public static void showRadiusImage(Context context, String url, int radius, ImageView imageView) {
// RequestOptions options = new RequestOptions().transform(new CenterCrop(), new RoundedCorners(DisplayUtil.dipToPixel(radius)));
// options
// .dontAnimate()
// .diskCacheStrategy(DiskCacheStrategy.ALL);
//
// Glide.with(context)
// .load(url)
// .apply(options)
// .into(imageView);
}
/**
* 显示图片,自己设定默认图
*
* @param context
* @param url
* @param imageView
*/
public static void showImage(Context context, String url, @DrawableRes int placeholder, ImageView imageView) {
Glide.with(context)
.asBitmap().fitCenter()
.load(url)
.apply(buildOptions(placeholder))
.into(imageView);
// LogUtils.d(AppConstants.LOG_TAG_PIC, "图片url = " + (!TextUtils.isEmpty(url) ? url : "url为空"));
}
/**
* 加载本地图片
*
* @param url
* @return
*/
public static Bitmap getLocalBitmap(String url) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(url, options);
//计算采样率
options.inSampleSize = calculateInSampleSize(options, 768, 1024);
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
Bitmap bitmap = BitmapFactory.decodeFile(url, options);
//旋转图片
int d = getPictureDegree(url);
if (d != 0) {
bitmap = rotateBitmap(bitmap, d);
}
return bitmap;
} catch (OutOfMemoryError e) {
e.printStackTrace();
return null;
}
}
public static void getCacheImage(Context context, String imgUrl, SimpleTarget<Bitmap> callback) {
Glide.with(context).asBitmap().load(imgUrl).into(callback);
}
/**
* 将文件生成Drawable
*
* @param path
* @return
*/
public static Drawable getDrawable(String path) {
Drawable bd = BitmapDrawable.createFromPath(path);
return bd;
}
/**
* 返回Bitmap显示像素所占位数
*
* @param config
* @return
*/
public static int getBytesPerPixel(Bitmap.Config config) {
if (config == Bitmap.Config.ARGB_8888) {
return 4;
} else if (config == Bitmap.Config.RGB_565) {
return 2;
} else if (config == Bitmap.Config.ARGB_4444) {
return 2;
} else if (config == Bitmap.Config.ALPHA_8) {
return 1;
}
return 1;
}
/**
* 获取图片旋转角度
*
* @param path
* @return
*/
public static int getPictureDegree(String path) {
int degree = 0;
try {
ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
} catch (IOException e) {
e.printStackTrace();
}
return degree;
}
/**
* 计算图片的缩放值
*
* @param options
* @param reqWidth
* @param reqHeight
* @return
*/
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
/**
* 旋转图片
*
* @param bitmap
* @param degree
* @return
*/
public static Bitmap rotateBitmap(Bitmap bitmap, int degree) {
if (bitmap != null) {
Matrix m = new Matrix();
m.postRotate(degree);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true);
return bitmap;
}
return bitmap;
}
/**
* 保存Bitmap为文件
*
* @param bitmap
* @param path
* @param fileName
* @return
*/
public static File saveBitmap(Bitmap bitmap, String path, String fileName) {
FileOutputStream outputStream = null;
try {
File mFolder = new File(path);
if (!mFolder.exists()) {
mFolder.mkdirs();
}
File file = new File(mFolder, fileName);
outputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.flush();
outputStream.close();
bitmap.recycle();
return file;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 给定宽高,根据宽高计算采样率压缩图片 并 旋转图片
*
* @param photoPath 原图片路径
* @param reqWidth 要求的宽
* @param reqHeight 要求的高
* @return
*/
public static Bitmap zipBitmapWithReq(String photoPath, int reqWidth, int reqHeight) {
// 压缩图片
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(photoPath, opts);
opts.inSampleSize = BitmapUtil.calculateInSampleSize(opts, reqWidth, reqHeight);
opts.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(photoPath, opts);
}
/**
* 根据给定 质量百分比 压缩图片
*
* @param bitmap
* @param quality 质量压缩比例(100为不压缩)
* @return
*/
public static Bitmap zipBitmapWithQuality(Bitmap bitmap, int quality) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
byte[] bytes = baos.toByteArray();
bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
return bitmap;
}
/**
* 给定宽高,根据宽高计算采样率压缩图片并存为文件
*
* @param photoPath 原图片路径
* @param saveFilePath 压缩后图片保存路径
* @param fileName 压缩后图片文件名
* @param reqWidth 要求的宽
* @param reqHeight 要求的高
* @return
*/
public static File zipBitmapAndSave(String photoPath, String saveFilePath, String fileName, int reqWidth, int reqHeight) {
Bitmap bitmap = BitmapUtil.zipBitmapWithReq(photoPath, reqWidth, reqHeight);
// 旋转图片
bitmap = BitmapUtil.rotateBitmap(bitmap, BitmapUtil.getPictureDegree(photoPath));
return BitmapUtil.saveBitmap(bitmap, saveFilePath, fileName);
}
/**
* 给定宽高,根据宽高计算采样率,
* 给定质量压缩比例
* 多重压缩图片并存为文件
*
* @param photoPath 原图片路径
* @param saveFilePath 压缩后图片保存路径
* @param fileName 压缩后图片文件名
* @param reqWidth 要求的宽
* @param reqHeight 要求的高
* @param quality 质量压缩比例(100为不压缩)
* @return
*/
public static File zipBitmapMultiAndSave(String photoPath, String saveFilePath, String fileName, int reqWidth, int reqHeight, int quality) {
Bitmap bit = zipBitmapWithReq(photoPath, reqWidth, reqHeight);
bit = zipBitmapWithQuality(bit, quality);
// 旋转图片
bit = BitmapUtil.rotateBitmap(bit, BitmapUtil.getPictureDegree(photoPath));
return BitmapUtil.saveBitmap(bit, saveFilePath, fileName);
}
/**
* 把Bitmap转Byte
*/
public static byte[] bitmap2Bytes(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
/**
* 根据高度放大, 并显示中间部分
*
* @param bitmap
* @param windowWidth
* @param windowHeight
* @return
*/
public static Bitmap compressBitmap(Bitmap bitmap, int windowWidth, int windowHeight) {
Matrix matrix = new Matrix();
int bitmapWidth = bitmap.getWidth();
int bitmapHeight = bitmap.getHeight();
float scaleY = windowHeight > bitmapHeight ? Float.valueOf(windowHeight) / Float.valueOf(bitmapHeight) : 1.0f;
matrix.postScale(scaleY, scaleY);
int offsetX = scaleY > 1 ? (int) ((bitmapWidth * scaleY - bitmapWidth) / 2) : 0;
int showHeight = windowHeight > bitmapHeight ? windowHeight : bitmapHeight;
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight, matrix, true);
try {
return Bitmap.createBitmap(bitmap, offsetX, 0, windowWidth, showHeight);
} catch (Exception e) {
}
return bitmap;
}
public static Bitmap getTransparentBitmap(Bitmap sourceImg, int number) {
int[] argb = new int[sourceImg.getWidth() * sourceImg.getHeight()];
sourceImg.getPixels(argb, 0, sourceImg.getWidth(), 0, 0, sourceImg.getWidth(), sourceImg.getHeight());// 获得图片的ARGB值
number = number * 255 / 100;
for (int i = 0; i < argb.length; i++) {
argb[i] = (number << 24) | (argb[i] & 0x00FFFFFF);
}
sourceImg = Bitmap.createBitmap(argb, sourceImg.getWidth(), sourceImg.getHeight(), Bitmap.Config.ARGB_8888);
return sourceImg;
}
/**
* 截取ScrollView显示内容
*
* @param scrollView
* @return
*/
public static Bitmap getScrollViewBitmap(ScrollView scrollView) {
int h = 0;
Bitmap bitmap = null;
for (int i = 0; i < scrollView.getChildCount(); i++) {
h += scrollView.getChildAt(i).getHeight();
scrollView.getChildAt(i).setBackgroundColor(Color.parseColor("#ffffff"));
}
bitmap = Bitmap.createBitmap(scrollView.getWidth(), h, Bitmap.Config.RGB_565);
final Canvas canvas = new Canvas(bitmap);
scrollView.draw(canvas);
return bitmap;
}
/**
* 截取WebView显示内容
*
* @param webView
* @return
*/
public static Bitmap getWebViewBitmap(WebView webView) {
Bitmap bm = null;
try {
int height = (int) (webView.getContentHeight() * webView.getScale());
int width = webView.getWidth();
int pH = webView.getHeight();
if(width <= 0){
width = 100;
}
if(height <= 0){
height = 100;
}
bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bm);
int top = height;
while (top > 0) {
if (top < pH) {
top = 0;
} else {
top -= pH;
}
canvas.save();
canvas.clipRect(0, top, width, top + pH);
webView.scrollTo(0, top);
webView.draw(canvas);
canvas.restore();
}
} catch (OutOfMemoryError e) {
if (bm != null) {
bm.recycle();
bm = null;
}
}
return bm;
}
/**
* 通过drawable文件名获取Drawable
*
* @param context
* @param name
* @return
*/
public static Drawable getDrawableFromName(Context context, String name) {
try {
Resources resources = context.getResources();
return resources.getDrawable(resources.getIdentifier(name, "drawable", context.getPackageName()));
} catch (Exception e) {
}
return null;
}
/**
* base64字符串转换bitmap
*
* @param base64
* @return
*/
public static Bitmap base64ToBitmap(String base64) {
Bitmap bitmap = null;
try {
byte[] bitmapArray = Base64.decode(base64.split(",")[1], Base64.DEFAULT);
bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
/**
* 下载图片
*
* @param context
* @param url
* @param listener
*/
public static void downloadImage(Context context, String url, ImageDownloadListener listener) {
try {
listener.start();
Glide.with(context)
.downloadOnly()
.load(url)
.addListener(new RequestListener<File>() {
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<File> target, boolean isFirstResource) {
listener.fail(e);
return false;
}
@Override
public boolean onResourceReady(File resource, Object model, Target<File> target, DataSource dataSource, boolean isFirstResource) {
listener.success(BitmapFactory.decodeFile(resource.getAbsolutePath()) , resource.getAbsolutePath());
return false;
}
}).submit();
} catch (Exception e) {
if (listener != null) listener.fail(new GlideException(e.getMessage()));
} finally {
if (listener != null) listener.finish();
}
}
public interface ImageDownloadListener {
/**
* 当前线程
*/
void start();
/**
* 子线程
*
* @param bitmap
*/
void success(Bitmap bitmap , String path);
/**
* 子线程
*
* @param e
*/
void fail(GlideException e);
/**
* 当前线程
*/
void finish();
}
/**
* 将图片转换成Base64编码的字符串
*/
public static String imageToBase64(String path){
if(TextUtils.isEmpty(path)){
return null;
}
InputStream is = null;
byte[] data = null;
String result = null;
try{
is = new FileInputStream(path);
//创建一个字符流大小的数组。
data = new byte[is.available()];
//写入数组
is.read(data);
//用默认的编码格式进行编码
result = Base64.encodeToString(data,Base64.DEFAULT);
}catch (Exception e){
e.printStackTrace();
}finally {
if(null !=is){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
}
@@ -0,0 +1,145 @@
package com.arpa.hndahesudintocctmsdriver.util;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcManager;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Parcelable;
import android.provider.Settings;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
/**
* @author hlh
* @version 1.0.0
* @date 2022/2/15 17:04
* @description:
*/
public class NfcUtils {
//nfc
public static NfcAdapter mNfcAdapter;
public static IntentFilter[] mIntentFilter = null;
public static PendingIntent mPendingIntent = null;
public static String[][] mTechList = null;
/**
* 构造函数,用于初始化nfc
*/
public NfcUtils(Activity activity) {
mNfcAdapter = NfcCheck(activity);
NfcInit(activity);
}
/**
* 检查NFC是否打开
*/
public static NfcAdapter NfcCheck(Activity activity) {
NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(activity);
if (mNfcAdapter == null) {
return null;
} else {
if (!mNfcAdapter.isEnabled()) {
Intent setNfc = new Intent(Settings.ACTION_NFC_SETTINGS);
activity.startActivity(setNfc);
}
}
return mNfcAdapter;
}
/**
* 初始化nfc设置
*/
public static void NfcInit(Activity activity) {
mPendingIntent = PendingIntent.getActivity(activity, 0, new Intent(activity, activity.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter filter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
IntentFilter filter2 = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
try {
filter.addDataType("*/*");
} catch (IntentFilter.MalformedMimeTypeException e) {
e.printStackTrace();
}
mIntentFilter = new IntentFilter[]{filter, filter2};
mTechList = null;
}
/**
* 读取NFC的数据
*/
public static String readNFCFromTag(Intent intent) throws UnsupportedEncodingException {
Parcelable[] rawArray = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (rawArray != null) {
NdefMessage mNdefMsg = (NdefMessage) rawArray[0];
NdefRecord mNdefRecord = mNdefMsg.getRecords()[0];
if (mNdefRecord != null) {
String readResult = new String(mNdefRecord.getPayload(), "UTF-8");
return readResult;
}
}
return "";
}
/**
* 往nfc写入数据
*/
public static void writeNFCToTag(String data, Intent intent) throws IOException, FormatException {
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Ndef ndef = Ndef.get(tag);
ndef.connect();
NdefRecord ndefRecord = NdefRecord.createTextRecord(null, data);
NdefRecord[] records = {ndefRecord};
NdefMessage ndefMessage = new NdefMessage(records);
ndef.writeNdefMessage(ndefMessage);
}
/**
* 读取nfcID
*/
public static String readNFCId(Intent intent) throws UnsupportedEncodingException {
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
String id = ByteArrayToHexString(tag.getId());
return id;
}
/**
* 将字节数组转换为字符串
*/
private static String ByteArrayToHexString(byte[] inarray) {
int i, j, in;
String[] hex = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};
String out = "";
for (j = 0; j < inarray.length; ++j) {
in = (int) inarray[j] & 0xff;
i = (in >> 4) & 0x0f;
out += hex[i];
i = in & 0x0f;
out += hex[i];
}
return out;
}
public static boolean hasNfc(Context context){
boolean bRet=false;
if(context==null)
return bRet;
NfcManager manager = (NfcManager) context.getSystemService(Context.NFC_SERVICE);
NfcAdapter adapter = manager.getDefaultAdapter();
if (adapter != null && adapter.isEnabled()) {
// adapter存在,能启用
bRet=true;
}
return bRet;
}
}
@@ -0,0 +1,86 @@
package com.arpa.hndahesudintocctmsdriver.util;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import androidx.core.app.NotificationManagerCompat;
/**
* 通知栏权限工具
*
* @author xuexiang
* @since 2019-09-04 14:00
*/
public final class NotifyUtils {
private NotifyUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
/**
* 通知栏权限是否获取
*
* @param context
* @return
*/
public static boolean isNotifyPermissionOpen(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
return NotificationManagerCompat.from(context).getImportance() != NotificationManager.IMPORTANCE_NONE;
}
return NotificationManagerCompat.from(context).areNotificationsEnabled();
}
/**
* 打开通知栏权限设置页面
*
* @param context
*/
public static void openNotifyPermissionSetting(Context context) {
try {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//直接跳转到应用通知设置的代码:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName());
intent.putExtra(Settings.EXTRA_CHANNEL_ID, context.getApplicationInfo().uid);
context.startActivity(intent);
return;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
intent.putExtra("app_package", context.getPackageName());
intent.putExtra("app_uid", context.getApplicationInfo().uid);
context.startActivity(intent);
return;
}
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setData(Uri.parse("package:" + context.getPackageName()));
context.startActivity(intent);
return;
}
//4.4以下没有从app跳转到应用通知设置页面的Action,可考虑跳转到应用详情页面,
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
intent.setData(Uri.fromParts("package", context.getPackageName(), null));
context.startActivity(intent);
return;
}
intent.setAction(Intent.ACTION_VIEW);
intent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
intent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
context.startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,137 @@
package com.arpa.hndahesudintocctmsdriver.util;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.webkit.PermissionRequest;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
/**
* @author hlh
* @version 1.0.0
* @date 2022/1/20 17:27
* @description:
*/
public class PaxWebChromeClient extends WebChromeClient {
private static final int CHOOSE_REQUEST_CODE = 0x9001;
private Activity mActivity;
private ValueCallback<Uri> uploadFile;//定义接受返回值
private ValueCallback<Uri[]> uploadFiles;
private ProgressBar bar;
private TextView mTitle;
public PaxWebChromeClient(@NonNull Activity mActivity, ProgressBar bar, TextView title) {
this.mActivity = mActivity;
this.bar=bar;
this.mTitle=title;
}
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (newProgress == 100) {
//bar.setVisibility(View.INVISIBLE);
} else {
// if (View.INVISIBLE == bar.getVisibility()) {
// bar.setVisibility(View.VISIBLE);
// }
// bar.setProgress(newProgress);
}
super.onProgressChanged(view, newProgress);
}
@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
// mTitle.setText(title);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onPermissionRequest(PermissionRequest request) {
// super.onPermissionRequest(request);//必须要注视掉
request.grant(request.getResources());
}
// For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
this.uploadFile = uploadFile;
openFileChooseProcess();
}
// For Android < 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsgs) {
this.uploadFile = uploadFile;
openFileChooseProcess();
}
// For Android > 4.1.1
// @Override
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
this.uploadFile = uploadFile;
openFileChooseProcess();
}
// For Android >= 5.0
@Override
public boolean onShowFileChooser(WebView webView,
ValueCallback<Uri[]> filePathCallback,
WebChromeClient.FileChooserParams fileChooserParams) {
this.uploadFiles = filePathCallback;
openFileChooseProcess();
return true;
}
private void openFileChooseProcess() {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
mActivity.startActivityForResult(Intent.createChooser(i, "Choose"), CHOOSE_REQUEST_CODE);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//LogCat.d("requestCode===",requestCode+"====");
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case CHOOSE_REQUEST_CODE:
if (null != uploadFile) {
Uri result = data == null || resultCode != Activity.RESULT_OK ? null
: data.getData();
uploadFile.onReceiveValue(result);
uploadFile = null;
}
if (null != uploadFiles) {
Uri result = data == null || resultCode != Activity.RESULT_OK ? null
: data.getData();
uploadFiles.onReceiveValue(new Uri[]{result});
uploadFiles = null;
}
break;
default:
break;
}
} else if (resultCode == Activity.RESULT_CANCELED) {
if (null != uploadFile) {
uploadFile.onReceiveValue(null);
uploadFile = null;
}
if (null != uploadFiles) {
uploadFiles.onReceiveValue(null);
uploadFiles = null;
}
}
}
}
@@ -0,0 +1,46 @@
package com.arpa.hndahesudintocctmsdriver.util;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import com.arpa.hndahesudintocctmsdriver.R;
import com.github.gzuliyujiang.wheelpicker.OptionPicker;
import com.github.gzuliyujiang.wheelpicker.contract.OnOptionPickedListener;
import com.github.gzuliyujiang.wheelpicker.widget.OptionWheelLayout;
import com.github.gzuliyujiang.wheelview.contract.TextProvider;
import java.util.ArrayList;
/**
* @ClassName PickerUtils
* @Author 用户
* @Date 2022/4/22 16:29
* @Description TODO
*/
public class PickerUtils<T extends TextProvider> {
private static class SingletonHolder {
private static final PickerUtils INSTANCE = new PickerUtils();
}
private PickerUtils() {
}
public static final PickerUtils getInstance() {
return SingletonHolder.INSTANCE;
}
public void pickSingle(Activity activity, String title, ArrayList<T> data, OnOptionPickedListener listener){
OptionPicker picker = new OptionPicker(activity);
picker.setTitle(title);
// picker.setBodyWidth(140);
picker.setData(data);
// picker.setDefaultPosition(2);
picker.setOnOptionPickedListener(listener);
// OptionWheelLayout wheelLayout = picker.getWheelLayout();
// picker.getWheelView().setStyle(R.style.WheelStyleDemo);
picker.show();
}
}
@@ -0,0 +1,175 @@
package com.arpa.hndahesudintocctmsdriver.util;
import android.app.Activity;
import androidx.fragment.app.Fragment;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import java.util.List;
public class PicturlUtil {
public static void selectPicter(Activity activity, List<LocalMedia> imgs, int maxNum) {
//(Activity) ctx 图片选择器
PictureSelector.create(activity)
.openGallery(PictureConfig.TYPE_IMAGE)
.maxSelectNum(maxNum)
.minSelectNum(1)
.imageSpanCount(4)// 每行显示个数
.selectionMode(PictureConfig.MULTIPLE)//多选
.previewImage(true)//预览图片
.compress(true)//压缩
.isCamera(true)// 是否显示拍照按钮 true or false
.minimumCompressSize(100)// 小于100kb的图片不压缩
.selectionMedia(imgs)
.forResult(PictureConfig.CHOOSE_REQUEST);//回调请求码
}
public static void selectPicter(Fragment fragment, List<LocalMedia> imgs, int maxNum) {
//(Activity) ctx 图片选择器
PictureSelector.create(fragment)
.openGallery(PictureConfig.TYPE_IMAGE)
.maxSelectNum(maxNum)
.minSelectNum(1)
.imageSpanCount(4)// 每行显示个数
.selectionMode(PictureConfig.MULTIPLE)//多选
.previewImage(true)//预览图片
.compress(true)//压缩
.isCamera(true)// 是否显示拍照按钮 true or false
.minimumCompressSize(100)// 小于100kb的图片不压缩
.selectionMedia(imgs)
.forResult(PictureConfig.CHOOSE_REQUEST);//回调请求码
}
public static void selectPicterAndVideo(Activity activity, List<LocalMedia> imgs, int maxNum) {
//(Activity) ctx 图片选择器
PictureSelector.create(activity)
.openGallery(PictureConfig.TYPE_ALL)
.maxSelectNum(maxNum)
.minSelectNum(1)
.imageSpanCount(4)// 每行显示个数
.selectionMode(PictureConfig.MULTIPLE)//多选
.previewImage(true)//预览图片
.compress(true)//压缩
.isCamera(true)// 是否显示拍照按钮 true or false
.minimumCompressSize(100)// 小于100kb的图片不压缩
.selectionMedia(imgs)
.forResult(PictureConfig.CHOOSE_REQUEST);//回调请求码
}
public static void selectVideo(Fragment activity, List<LocalMedia> imgs) {
//(Activity) ctx 图片选择器
PictureSelector.create(activity)
.openGallery(PictureConfig.TYPE_VIDEO)
.maxSelectNum(1)
.minSelectNum(1)
.imageSpanCount(4)// 每行显示个数
.selectionMode(PictureConfig.MULTIPLE)//多选
.previewImage(true)//预览图片
.compress(true)//压缩
.isCamera(true)// 是否显示拍照按钮 true or false
.minimumCompressSize(100)// 小于100kb的图片不压缩
.selectionMedia(imgs)
.forResult(PictureConfig.CHOOSE_REQUEST);//回调请求码
}
public static void selectPicterCute(Activity activity, List<LocalMedia> imgs, int maxNum) {
//(Activity) ctx 图片选择器
PictureSelector.create(activity)
.openGallery(PictureConfig.TYPE_IMAGE)
.maxSelectNum(maxNum)
.minSelectNum(1)
.imageSpanCount(4)// 每行显示个数
.selectionMode(PictureConfig.MULTIPLE)//多选
.previewImage(true)//预览图片
.compress(true)//压缩
.isCamera(true)// 是否显示拍照按钮 true or false
.minimumCompressSize(100)// 小于100kb的图片不压缩
.selectionMedia(imgs)
.enableCrop(true)// 是否裁剪
.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
.withAspectRatio(5, 1)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
.forResult(PictureConfig.CHOOSE_REQUEST);//回调请求码
}
public static void selectPicterCute(Activity activity, List<LocalMedia> imgs, int maxNum, int width, int height) {
//(Activity) ctx 图片选择器
PictureSelector.create(activity)
.openGallery(PictureConfig.TYPE_IMAGE)
.maxSelectNum(maxNum)
.minSelectNum(1)
.imageSpanCount(4)// 每行显示个数
.selectionMode(PictureConfig.MULTIPLE)//多选
.previewImage(true)//预览图片
.compress(true)//压缩
.isCamera(true)// 是否显示拍照按钮 true or false
.minimumCompressSize(100)// 小于100kb的图片不压缩
.selectionMedia(imgs)
.enableCrop(true)// 是否裁剪
.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
.withAspectRatio(width, height)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
.forResult(PictureConfig.CHOOSE_REQUEST);//回调请求码
}
public static void selectCameraCute(Activity activity, List<LocalMedia> imgs, int maxNum, int width, int height) {
//(Activity) ctx 图片选择器
PictureSelector.create(activity)
.openCamera(PictureConfig.TYPE_IMAGE)
.maxSelectNum(maxNum)
.minSelectNum(1)
.imageSpanCount(4)// 每行显示个数
.selectionMode(PictureConfig.MULTIPLE)//多选
.previewImage(true)//预览图片
.compress(true)//压缩
.isCamera(true)// 是否显示拍照按钮 true or false
.minimumCompressSize(100)// 小于100kb的图片不压缩
.selectionMedia(imgs)
.enableCrop(true)// 是否裁剪
.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
.withAspectRatio(width, height)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
.forResult(PictureConfig.CHOOSE_REQUEST);//回调请求码
}
public static void selectCamera(Activity activity, List<LocalMedia> imgs, int maxNum) {
//(Activity) ctx 图片选择器
PictureSelector.create(activity)
.openCamera(PictureConfig.TYPE_IMAGE)
.maxSelectNum(maxNum)
.minSelectNum(1)
.imageSpanCount(4)// 每行显示个数
.selectionMode(PictureConfig.MULTIPLE)//多选
.previewImage(true)//预览图片
.compress(true)//压缩
.isCamera(true)// 是否显示拍照按钮 true or false
.minimumCompressSize(100)// 小于100kb的图片不压缩
.selectionMedia(imgs)
.enableCrop(false)// 是否裁剪
.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
// .withAspectRatio(width, height)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
.forResult(PictureConfig.CHOOSE_REQUEST);//回调请求码
}
public static void selectPicterHtml(Activity activity, List<LocalMedia> imgs, int maxNum) {
//(Activity) ctx 图片选择器
PictureSelector.create(activity)
.openGallery(PictureConfig.TYPE_IMAGE)
.maxSelectNum(maxNum)
.minSelectNum(1)
.imageSpanCount(4)// 每行显示个数
.selectionMode(PictureConfig.MULTIPLE)//多选
.previewImage(true)//预览图片
.compress(true)//压缩
.isCamera(true)// 是否显示拍照按钮 true or false
.minimumCompressSize(100)// 小于100kb的图片不压缩
.selectionMedia(imgs)
.enableCrop(true)// 是否裁剪
.cropWH(340, 1000)
.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
.forResult(PictureConfig.CHOOSE_REQUEST);//回调请求码
}
}
@@ -0,0 +1,68 @@
package com.arpa.hndahesudintocctmsdriver.util;
import android.content.Context;
import androidx.annotation.NonNull;
import com.lxj.xpopup.animator.PopupAnimator;
import com.lxj.xpopup.core.CenterPopupView;
import com.arpa.hndahesudintocctmsdriver.R;
import org.jetbrains.annotations.NotNull;
/**
* @author hlh
* @version 1.0.0
* @date 2021/8/20 8:57
* @description:
*/
public class YinDaoFs extends CenterPopupView {
public YinDaoFs(@NonNull @NotNull Context context) {
super(context);
}
@Override
protected int getImplLayoutId() {
return R.layout.my_there_popup;
}
// 执行初始化操作,比如:findView,设置点击,或者任何你弹窗内的业务逻辑
@Override
protected void onCreate() {
super.onCreate();
}
// 设置最大宽度,看需要而定,
@Override
protected int getMaxWidth() {
return super.getMaxWidth();
}
// 设置最大高度,看需要而定
@Override
protected int getMaxHeight() {
return super.getMaxHeight();
}
// 设置自定义动画器,看需要而定
@Override
protected PopupAnimator getPopupAnimator() {
return super.getPopupAnimator();
}
/**
* 弹窗的宽度,用来动态设定当前弹窗的宽度,受getMaxWidth()限制
*
* @return
*/
protected int getPopupWidth() {
return getResources().getDimensionPixelOffset(R.dimen.dp_300);
}
/**
* 弹窗的高度,用来动态设定当前弹窗的高度,受getMaxHeight()限制
*
* @return
*/
protected int getPopupHeight() {
return getResources().getDimensionPixelOffset(R.dimen.dp_500);
}
}
@@ -0,0 +1,94 @@
package com.arpa.hndahesudintocctmsdriver.util.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.arpa.hndahesudintocctmsdriver.util.bean.GetObjectName;
import java.util.ArrayList;
import java.util.List;
public class AdapterAll extends RecyclerView.Adapter<AdapterAll.ViewHolder> {
private Context context;
private List object;
private int layout;
private onItemViewListenter listenterView;
public AdapterAll(Context context, List object, int layout){
this.context = context;
this.object=object;
this.layout=layout;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(layout, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
View v=holder.itemView;
ViewGroup vg=v.findViewById(v.getId());
GetObjectName.ZIModel(vg,object.get(position),context);
if(listenterView!=null){
listenterView.onItemView(position,object.get(position),v);
}
}
public void updateItem(int position,Object o) {
//更新数据
notifyItemChanged(position,o);
}
public void removeAll(){
object=new ArrayList();
notifyDataSetChanged();
}
public void delItemV(int position) {
object.remove(position);
notifyItemRemoved(position);
notifyDataSetChanged();
//android:editable="false"
}
public void addItemV(Object o) {
//增加数据
int position = object.size();
object.add(o);
notifyItemInserted(position);
}
public void removeItemV(int index) {
int position = object.size();
object.remove(index);
notifyItemInserted(position);
}
@Override
public int getItemCount() {
if(object==null){
return 0;
}
return object.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(View view) {
super(view);
}
}
//对内容的补充
public void setOnItemViewListener(onItemViewListenter listenterView) { this.listenterView = listenterView; }
public interface onItemViewListenter { void onItemView(int position,Object o, View v);}
}
@@ -0,0 +1,76 @@
package com.arpa.hndahesudintocctmsdriver.util.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.arpa.hndahesudintocctmsdriver.util.bean.GetObjectName;
import java.util.List;
public class AdapterAlls extends RecyclerView.Adapter<AdapterAlls.ViewHolder> {
private Context context;
private List<ManyBean> object;
public AdapterAlls(Context context, List<ManyBean> object){
this.context = context;
this.object=object;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(object.get(viewType).getLayout(), parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
View v=holder.itemView;
ViewGroup vg=v.findViewById(v.getId());
GetObjectName.ZIModel(vg,object.get(position).getBean(),context);
listenterView.onItemView(position,object.get(position).getBean(),v,object.get(position).getLayout());
}
@Override
public int getItemViewType(int position) {
return position;
}
@Override
public int getItemCount() {
if(object==null){
return 0;
}
return object.size();
}
public void add(List<ManyBean> addMessageList) {
//增加数据
int position = object.size();
object.addAll(position, addMessageList);
notifyItemInserted(position);
}
public void addItem(ManyBean mb) {
//增加数据
int position = object.size();
object.add(mb);
notifyItemInserted(position);
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(View view) {
super(view);
}
}
//对内容的补充
private onItemViewListenter listenterView;
public void setOnItemViewListener(onItemViewListenter listenterView) { this.listenterView = listenterView; }
public interface onItemViewListenter { void onItemView(int position, Object o, View v, int layout);}
}
@@ -0,0 +1,27 @@
package com.arpa.hndahesudintocctmsdriver.util.adapter;
public class ManyBean {
private Object bean;
private int layout;
public ManyBean(Object bean, int layout) {
this.bean = bean;
this.layout = layout;
}
public Object getBean() {
return bean;
}
public void setBean(Object bean) {
this.bean = bean;
}
public int getLayout() {
return layout;
}
public void setLayout(int layout) {
this.layout = layout;
}
}
@@ -0,0 +1,17 @@
package com.arpa.hndahesudintocctmsdriver.util.adapter;
import java.util.ArrayList;
import java.util.List;
public class TFList {
public static List<Object> getList(List lists){
List<Object> list=new ArrayList<>();
for (Object o : lists) {
list.add(o);
}
return list;
}
}
@@ -0,0 +1,50 @@
package com.arpa.hndahesudintocctmsdriver.util.alert;
import android.app.Dialog;
import android.content.Context;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.widget.TextView;
import com.arpa.hndahesudintocctmsdriver.R;
public class CustomDialog extends Dialog {
private String content;
private boolean key=false;
public CustomDialog(Context context, String content) {
super(context, R.style.CustomDialog);
this.content=content;
initView();
}
public CustomDialog(Context context, String content,boolean key) {
super(context, R.style.CustomDialog);
this.content=content;
this.key=key;
initView();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode){
case KeyEvent.KEYCODE_BACK:
if(CustomDialog.this.isShowing())
if (!key){
CustomDialog.this.dismiss();
}
break;
}
return true;
}
private void initView(){
setContentView(R.layout.load);
((TextView)findViewById(R.id.tvcontent)).setText(content);
setCanceledOnTouchOutside(true);
WindowManager.LayoutParams attributes = getWindow().getAttributes();
attributes.alpha=0.8f;
getWindow().setAttributes(attributes);
setCancelable(false);
}
}
@@ -0,0 +1,90 @@
package com.arpa.hndahesudintocctmsdriver.util.alert;
import android.content.Context;
import android.os.CountDownTimer;
import android.os.Handler;
import android.widget.Toast;
/**
* @author hlh
* @version 1.0.0
* @date 2021/11/2 21:02
* @description:
*/
public class ToastUtil {
private Toast mToast;
private TimeCount timeCount;
private String message;
private int gravity;
private Context mContext;
private Handler mHandler = new Handler();
private boolean canceled = true;
public ToastUtil(Context context, int gravity, String msg) {
message = msg;
mContext = context;
this.gravity = gravity;
}
/**
* 自定义时长、居中显示toast
*
* @param duration
*/
public void show(int duration) {
timeCount = new TimeCount(duration, 1000);
if (canceled) {
timeCount.start();
canceled = false;
showUntilCancel();
}
}
/**
* 隐藏toast
*/
public void hide() {
if (mToast != null) {
mToast.cancel();
}
if (timeCount != null) {
timeCount.cancel();
}
canceled = true;
}
private void showUntilCancel() {
if (canceled) { //如果已经取消显示,就直接return
return;
}
mToast = Toast.makeText(mContext,message,Toast.LENGTH_LONG);
mToast.setGravity(gravity, 0, 0);
mToast.show();
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
showUntilCancel();
}
}, 3500);
}
/**
* 自定义计时器
*/
private class TimeCount extends CountDownTimer {
public TimeCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval); //millisInFuture总计时长,countDownInterval时间间隔(一般为1000ms)
}
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
hide();
}
}
}
@@ -0,0 +1,58 @@
package com.arpa.hndahesudintocctmsdriver.util.app;
import java.util.Locale;
/**
* @author hlh
* @version 1.0.0
* @date 2021/8/18 11:49
* @description:
*/
public class SystemUtil {
/**
* 获取当前手机系统语言。
*
* @return 返回当前系统语言。例如:当前设置的是“中文-中国”,则返回“zh-CN”
*/
public static String getSystemLanguage() {
return Locale.getDefault().getLanguage();
}
/**
* 获取当前系统上的语言列表(Locale列表)
*
* @return 语言列表
*/
public static Locale[] getSystemLanguageList() {
return Locale.getAvailableLocales();
}
/**
* 获取当前手机系统版本号
*
* @return 系统版本号
*/
public static String getSystemVersion() {
return android.os.Build.VERSION.RELEASE;
}
/**
* 获取手机型号
*
* @return 手机型号
*/
public static String getSystemModel() {
return android.os.Build.MODEL;
}
/**
* 获取手机厂商
*
* @return 手机厂商
*/
public static String getDeviceBrand() {
return android.os.Build.BRAND;
}
}
@@ -0,0 +1,23 @@
package com.arpa.hndahesudintocctmsdriver.util.app;
import android.content.Context;
import android.content.pm.PackageManager;
/**
* @author hlh
* @version 1.0.0
* @date 2021/9/14 11:17
* @description:
*/
public class VersionUtil {
public static String getVersion(Context con){
String vs="1.0.0";
try {
vs = con.getPackageManager().getPackageInfo(con.getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return vs;
}
}
@@ -0,0 +1,132 @@
package com.arpa.hndahesudintocctmsdriver.util.bean;
import android.content.Context;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.arpa.hndahesudintocctmsdriver.util.string.StringUtil;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
public class GetObjectName {
public static List<String> GetName(Object o) {
List<String> str = new ArrayList<>();
Field[] fields = o.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
fields[i].setAccessible(true);
str.add(fields[i].getName());
}
return str;
}
public static boolean isName(List<String> list,String name){
for (int i=0;i<list.size();i++) {
if(list.get(i).equals(name)){
list.remove(i);
return true;
}
}
return false;
}
public static Object getFieldValueByFieldName(String fieldName, Object object) {
try {
Field field = object.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(object);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void ZIModel(ViewGroup vg, Object o, Context con) {
List<String> names = GetName(o);
List<Integer> list = forData(vg);
for (int i = 0; i < list.size(); i++) {
if (list.get(i) != -1 && Integer.parseInt(String.valueOf(list.get(i))) > 100) {
String name = vg.getResources().getResourceName(list.get(i));
String idName = name.substring(name.indexOf("/") + 1);
if (isName(names,idName)) {
switch (vg.findViewById(list.get(i)).getClass().getSimpleName()) {
case "TextView":
case "AppCompatTextView":
String str=StringUtil.isNull(getFieldValueByFieldName(idName, o)+"","");
if (!str.equals("")){
textView(vg, list.get(i), str);
}
break;
case "ImageView":
case "AppCompatImageView":
imgView(vg, list.get(i), getFieldValueByFieldName(idName, o)+"", con);
break;
}
}
}
}
}
private static List<Integer> forData(ViewGroup llRoot) {
List<Integer> list = new ArrayList<>();
int childCount = llRoot.getChildCount();
for (int i = 0; i < childCount; i++) {
if (llRoot.getChildAt(i) instanceof ViewGroup) {
list.add(llRoot.getChildAt(i).getId());
List<Integer> list1 = forData((ViewGroup) llRoot.getChildAt(i));
list.addAll(list1);
} else {
list.add(llRoot.getChildAt(i).getId());
}
}
return list;
}
public static void ZIBean(ViewGroup vg, Object o, Context con) {
//System.out.println("引入"+o.toString());
List<String> names = GetName(o);
for (int i = 0; i < vg.getChildCount(); i++) {
if (vg.getChildAt(i).getId() != -1) {
int id = vg.getChildAt(i).getId();
String name = vg.getResources().getResourceName(id);
String idName = name.substring(name.indexOf("/") + 1);
for (int j = 0; j < names.size(); j++) {
if (names.get(j).equals(idName)) {
switch (vg.getChildAt(i).getClass().getSimpleName()) {
case "TextView":
case "AppCompatTextView":
String str=StringUtil.isNull(getFieldValueByFieldName(idName,o).toString()+"","");
if(!str.equals("")){
textView(vg, id, str);
}
names.remove(j);
break;
case "ImageView":
case "AppCompatImageView":
imgView(vg,id,getFieldValueByFieldName(idName,o).toString()+"",con);
names.remove(j);
break;
}
}
}
}
}
}
private static void textView(ViewGroup vg, int id, String o) {
TextView t = vg.findViewById(id);
t.setText(o);
}
private static void imgView(ViewGroup vg, int id, String o,Context con) {
if(o.indexOf("http")!=-1){
ImageView bv = vg.findViewById(id);
Glide.with(con).load(o).into(bv);
}
}
}
@@ -0,0 +1,17 @@
package com.arpa.hndahesudintocctmsdriver.util.cache;
import android.view.View;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class CacheGroup {
public final static Map<String, String> cacheList=new HashMap<>();
public final static Map<String, String> cacheListA=new HashMap<>();
public final static Map<String, Date> cacheTimeList=new HashMap<>();
public final static Map<String, String> cacheDateList=new HashMap<>();
public final static Map<String, View> fragList=new HashMap<>();
}
@@ -0,0 +1,97 @@
package com.arpa.hndahesudintocctmsdriver.util.edit;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author hlh
* @version 1.0.0
* @date 2021/10/12 20:11
* @description:
*/
public class CashierInputFilter implements InputFilter {
Pattern mPattern;
//输入的最大金额
private static final int MAX_VALUE = Integer.MAX_VALUE;
//小数点后的位数
private static final int POINTER_LENGTH = 2;
private static final int LENGTH=9;
private static final String POINTER = ".";
private static final String ZERO = "0";
public CashierInputFilter() {
mPattern = Pattern.compile("([0-9]|\\.)*");
}
/**
* @param source 新输入的字符串
* @param start 新输入的字符串起始下标,一般为0
* @param end 新输入的字符串终点下标,一般为source长度-1
* @param dest 输入之前文本框内容
* @param dstart 原内容起始坐标,一般为0
* @param dend 原内容终点坐标,一般为dest长度-1
* @return 输入内容
*/
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
String sourceText = source.toString();
String destText = dest.toString();
//验证删除等按键
if (TextUtils.isEmpty(sourceText)) {
return "";
}
Matcher matcher = mPattern.matcher(source);
//已经输入小数点的情况下,只能输入数字
if(destText.contains(POINTER)) {
if (!matcher.matches()) {
return "";
} else {
if (POINTER.equals(source.toString())) { //只能输入一个小数点
return "";
}
}
//验证小数点精度,保证小数点后只能输入两位
int index = destText.indexOf(POINTER);
int length = dend - index;
if (length > POINTER_LENGTH) {
return dest.subSequence(dstart, dend);
}
} else {
/**
* 没有输入小数点的情况下,只能输入小数点和数字
* 1. 首位不能输入小数点
* 2. 如果首位输入0,则接下来只能输入小数点了
*/
if (!matcher.matches()) {
return "";
} else {
if ((POINTER.equals(source.toString())) && TextUtils.isEmpty(destText)) { //首位不能输入小数点
return "";
} else if (!POINTER.equals(source.toString()) && ZERO.equals(destText)) { //如果首位输入0,接下来只能输入小数点
return "";
}
}
}
//验证输入金额的大小
double sumText = Double.parseDouble(destText + sourceText);
if (sumText > MAX_VALUE) {
return dest.subSequence(dstart, dend);
}
return dest.subSequence(dstart, dend) + sourceText;
}
}
@@ -0,0 +1,49 @@
package com.arpa.hndahesudintocctmsdriver.util.file;
import android.graphics.Bitmap;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @author hlh
* @version 1.0.0
* @date 2021/7/30 15:56
* @description:
*/
public class FileUtil {
public static File bitmapTurnFile(Bitmap bit, String path){
File file=new File(path);
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
bit.compress(Bitmap.CompressFormat.JPEG, 100, bos);
bos.flush();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
public static String lastName(File file){
if(file==null) return null;
String filename = file.getName();
if(filename.lastIndexOf(".")==-1){
return "";//文件没有后缀名的情况
}
//此时返回的是带有 . 的后缀名,
return filename.substring(filename.lastIndexOf(".")+1);
}
public static String fileName(File file){
if(file==null) return null;
String filename = file.getName();
if(filename.lastIndexOf(".")==-1){
return "";//文件没有后缀名的情况
}
//此时返回的是带有 . 的后缀名,
return filename.substring(0,filename.lastIndexOf("."));
}
}
@@ -0,0 +1,46 @@
package com.arpa.hndahesudintocctmsdriver.util.file;
import android.content.Context;
import android.os.Handler;
import com.arpa.hndahesudintocctmsdriver.util.msg.MsgUtil;
import java.io.File;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;
/**
* @author hlh
* @version 1.0.0
* @date 2021/7/30 16:19
* @description:图片文件压缩
*/
public class ImageFileCompressUtil {
public final static int COMPRESS_START=32;
public final static int COMPRESS_SUCCESS=33;
public final static int COMPRESS_ONERROR=34;
public static void imageFileCompress(Context con, File file, Handler hd){
Luban.with(con)
.load(file) // 传人要压缩的图片列表
.ignoreBy(100) // 忽略不压缩图片的大小
.setTargetDir(file.getParent()) // 设置压缩后文件存储位置
.setCompressListener(new OnCompressListener() { //设置回调
@Override
public void onStart() {
MsgUtil.addHdMsgWat(hd,COMPRESS_START);
}
@Override
public void onSuccess(File file) {
MsgUtil.addHdMsgWatBody(hd,COMPRESS_SUCCESS,file.getPath());
}
@Override
public void onError(Throwable e) {
MsgUtil.addHdMsgWatBody(hd,COMPRESS_ONERROR,e.toString());
}
}).launch();
}
}
@@ -0,0 +1,11 @@
package com.arpa.hndahesudintocctmsdriver.util.html;
public class HtmlAutoUtil {
public static String pinjie(String html) {
String head = "<head>" +
"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " +
"<style>*{margin:0;padding:0;}img{max-width: 100%; width:auto; height:auto;}</style>" +
"</head>";
return "<html>" + head + "<body>" + html + "</body></html>";
}
}
@@ -0,0 +1,42 @@
package com.arpa.hndahesudintocctmsdriver.util.http;
import android.content.Context;
import android.os.Build;
import android.provider.Settings;
import android.webkit.WebSettings;
/**
* @author hlh
* @version 1.0.0
* @date 2021/9/14 15:08
* @description:
*/
public class GetUtil {
public static String getUserAgent(Context con) {
String userAgent = "";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
try {
userAgent = WebSettings.getDefaultUserAgent(con);
} catch (Exception e) {
userAgent = System.getProperty("http.agent");
}
} else {
userAgent = System.getProperty("http.agent");
}
StringBuffer sb = new StringBuffer();
for (int i = 0, length = userAgent.length(); i < length; i++) {
char c = userAgent.charAt(i);
if (c <= '\u001f' || c >= '\u007f') {
sb.append(String.format("\\u%04x", (int) c));
} else {
sb.append(c);
}
}
return sb.toString();
}
public static String getDeviceId(Context con){
return Settings.System.getString(con.getContentResolver(), Settings.Secure.ANDROID_ID);
}
}
@@ -0,0 +1,53 @@
package com.arpa.hndahesudintocctmsdriver.util.http;
public class OkDate {
private String url;
private String type;
private String madiaType;
public OkDate(String url, String type, String madiaType) {
this.url = url;
this.type = type;
this.madiaType = madiaType;
}
public OkDate(String url, String madiaType) {
this.url = url;
this.madiaType = madiaType;
}
public OkDate(String url) {
this.url = url;
}
public OkDate() {
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getMadiaType() {
return madiaType;
}
public void setMadiaType(String madiaType) {
this.madiaType = madiaType;
}
}
@@ -0,0 +1,169 @@
package com.arpa.hndahesudintocctmsdriver.util.http;
import android.content.Context;
import com.arpa.hndahesudintocctmsdriver.util.app.VersionUtil;
import java.io.File;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
public class OkHttpUtil {
private static String SIGN_PASSWORD="tEzOoHXXPkak*y(BfIH(YMSiV0ZHz1Ki";
public static Request post(OkDate od, Context con){
MediaType mediaType = MediaType.parse("application/json");
if(od.getMadiaType()!=null && od.getMadiaType().equals("")){
od.setMadiaType("{}");
}
// JSONObject jsonObject = JSON.parseObject(od.getMadiaType());
// jsonObject.put("timestamp", DateUtil.current());
// jsonObject.put("deviceId", GetUtil.getDeviceId(con));
// String sign = SecureUtil.signParamsSha1(jsonObject,SIGN_PASSWORD);
// Log.e("jsonObject",jsonObject.toString());
// Log.e("sign",sign);
// Map<String,Object> map=new HashMap<>();
// map.put("data",SecurityUtil.encrypt(jsonObject.toString()));
// Log.e("参数1",od.getMadiaType());
// Log.e("参数2",MapUtil.mapJson(map));
//MapUtil.mapJson(map)
RequestBody body = RequestBody.create(mediaType,od.getMadiaType());
Headers.Builder hb=new Headers.Builder();
hb.add("Content-Type","application/json");
hb.add("Cache-Control","no-cache");
Request request = new Request.Builder()
.url(od.getUrl())
.post(body)
.headers(hb.build())
.addHeader("Version", VersionUtil.getVersion(con))
//.addHeader("sign",sign)
.removeHeader("User-Agent")
.addHeader("User-Agent",GetUtil.getUserAgent(con))
.build();
return request;
}
public static Request posts(OkDate od, String token, Context con){
MediaType mediaType = MediaType.parse("application/json");
if(od.getMadiaType()!=null && od.getMadiaType().equals("")){
od.setMadiaType("{}");
}
// JSONObject jsonObject = JSON.parseObject(od.getMadiaType());
// jsonObject.put("timestamp", DateUtil.current());
// jsonObject.put("deviceId", GetUtil.getDeviceId(con));
// String sign = SecureUtil.signParamsSha1(jsonObject,SIGN_PASSWORD);
// Log.e("jsonObject",jsonObject.toString());
// Log.e("sign",sign);
// Map<String,Object> map=new HashMap<>();
// map.put("data",SecurityUtil.encrypt(jsonObject.toString()));
// Log.e("参数1",od.getMadiaType());
// Log.e("参数2",MapUtil.mapJson(map));
//MapUtil.mapJson(map)
RequestBody body = RequestBody.create(mediaType,od.getMadiaType());
Request request = new Request.Builder()
.url(od.getUrl())
.method("POST", body)
.addHeader("Authorization", token)
.addHeader("Content-Type", "application/json")
.addHeader("Version", VersionUtil.getVersion(con))
//.addHeader("sign",sign)
.removeHeader("User-Agent")
.addHeader("User-Agent",GetUtil.getUserAgent(con))
.build();
return request;
}
public static Request get(OkDate od){
Headers.Builder hb=new Headers.Builder();
hb.add("Content-Type","application/json");
hb.add("Cache-Control","no-cache");
Request request = new Request.Builder()
.url(od.getUrl())
.get()
.headers(hb.build())
.build();
return request;
}
public static Request get(OkDate od,String token){
Headers.Builder hb=new Headers.Builder();
hb.add("Content-Type","application/json");
hb.add("Cache-Control","no-cache");
hb.add("Authorization",token);
Request request = new Request.Builder()
.url(od.getUrl())
.addHeader("Authorization", token)
.get()
.headers(hb.build())
.build();
return request;
}
public static Request postWe(OkDate od){
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType,od.getMadiaType());
Headers.Builder hb=new Headers.Builder();
hb.add("Content-Type","application/json");
hb.add("Cache-Control","no-cache");
Request request = new Request.Builder()
.url(od.getUrl())
.post(body)
.headers(hb.build())
.build();
return request;
}
public static Request postFile(OkDate od,String token,File file) {
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file",file.getPath(),
RequestBody.create(MediaType.parse("application/octet-stream"), file))
.build();
Request request = new Request.Builder()
.url(od.getUrl())
.method("POST", body)
.addHeader("Authorization", token)
.addHeader("Cookie", "JSESSIONID=NqpqKQstwceQurcNK5hjl4GnTgiF4eSzZSo5a1rz")
.build();
return request;
}
public static Request postFiles(OkDate od,File file,String token,String carId) {
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file",file.getPath(),RequestBody.create(MediaType.parse("application/octet-stream"), file))
.addFormDataPart("carId",carId)
.build();
Request request = new Request.Builder()
.url(od.getUrl())
.method("POST", body)
.addHeader("Authorization", token)
.addHeader("Cookie", "JSESSIONID=NqpqKQstwceQurcNK5hjl4GnTgiF4eSzZSo5a1rz")
.build();
return request;
}
public static Request postFiles(OkDate od,File file,String token,String carId,String carNum) {
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file",file.getPath(),RequestBody.create(MediaType.parse("application/octet-stream"), file))
.addFormDataPart("carId",carId)
.addFormDataPart("carNum",carNum)
.build();
Request request = new Request.Builder()
.url(od.getUrl())
.method("POST", body)
.addHeader("Authorization", token)
.addHeader("Cookie", "JSESSIONID=NqpqKQstwceQurcNK5hjl4GnTgiF4eSzZSo5a1rz")
.build();
return request;
}
}
@@ -0,0 +1,259 @@
package com.arpa.hndahesudintocctmsdriver.util.http;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import com.google.gson.Gson;
import com.arpa.hndahesudintocctmsdriver.bean.MsgBean;
import com.arpa.hndahesudintocctmsdriver.ui.MainActivity;
import com.arpa.hndahesudintocctmsdriver.ui.UiAuxiliary;
import com.arpa.hndahesudintocctmsdriver.util.cache.CacheGroup;
import com.arpa.hndahesudintocctmsdriver.util.time.Timer;
import java.io.IOException;
import java.util.Date;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class RequestUtil {
public static final int FEEDBACK=-1;
public static final String FEEDBACK_TEXT="请求失败,请检查网络状况";
private static Gson gson=new Gson();
private static MsgBean mb;
//1执行重新请求,并更新缓存
//2自动判断是否有缓存,如果有,不在请求
//3自动判断是否有缓存,如果有,定时检测缓存,如果两次时间相隔超过规定时间,则也会再次请求
public static void start(int code, final String name, Request re, Context con, final Handler hd){
switch (code){
case 1:a1(name,re,con,hd);break;
case 12:a1s(name,re,con,hd);break;
case 2:a2(name,re,con,hd);break;
case 11:a11(name,re,con,hd);break;
default:break;
}
}
public static void start(final String name, Request re, Context con, final Handler hd, int s){
a3(name,re,con,hd,s);
}
public static void a1(final String name, Request re, Context con, final Handler hd){
Log.e("请求开始","........");
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
client.newCall(re).enqueue( new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("请求错误","error:"+e.toString());
Message message=new Message();
message.obj=RequsetCodeConstants.FEEDBACK_TEXT;
message.what=RequsetCodeConstants.ERROR;
hd.sendMessage(message);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String body=response.body().string();
final int code=response.code();
Log.e("e",body+"");
//SecurityUtil.decrypt(body);
if(body.startsWith("04")){
body=SecurityUtil.decrypt(body);
}
Log.e("es",body+"");
Message message=new Message();
if(code==RequsetCodeConstants.SUCCESS){
mb=gson.fromJson(body,MsgBean.class);
if(!body.equals("")){
if(mb.getCode()==401){
UiAuxiliary.delLogin(con);
Intent intent = new Intent(con, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
con.startActivity(intent);
}else{
CacheGroup.cacheList.put(name,body);
message.obj=response.code();
message.what=RequsetCodeConstants.SUCCESS;
}
}
}else{
message.obj=response.code();
message.what=code;
}
Log.e("请求响应",body);
hd.sendMessage(message);
//customDialog.dismiss();
}
});
}
public static void a1s(final String name, Request re, Context con, final Handler hd){
Log.e("请求开始","........");
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
client.newCall(re).enqueue( new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("请求错误","error:"+e.toString());
Message message=new Message();
message.obj=RequsetCodeConstants.FEEDBACK_TEXT;
message.what=RequsetCodeConstants.ERROR;
hd.sendMessage(message);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String body=response.body().string();
final int code=response.code();
Log.e("e",body+"");
//SecurityUtil.decrypt(body);
String bodys=body;
Log.e("es",bodys+"");
Message message=new Message();
if(code==RequsetCodeConstants.SUCCESS){
mb=gson.fromJson(bodys,MsgBean.class);
if(!bodys.equals("")){
if(mb.getCode()==401){
UiAuxiliary.delLogin(con);
final Intent intent = con.getPackageManager().getLaunchIntentForPackage(con.getPackageName());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
con.startActivity(intent);
android.os.Process.killProcess(android.os.Process.myPid());
Toast.makeText(con,"登陆失效",Toast.LENGTH_SHORT).show();
}else{
CacheGroup.cacheList.put(name,bodys);
message.obj=response.code();
message.what=RequsetCodeConstants.SUCCESS;
}
}
}else{
message.obj=response.code();
message.what=code;
}
Log.e("请求响应",body);
hd.sendMessage(message);
//customDialog.dismiss();
}
});
}
public static void a2(final String name, Request re, Context con, final Handler hd){
//CustomDialog customDialog= new CustomDialog(con, "正在加载...");
//customDialog.show();//显示,显示时页面不可点击,只能点击返回
if(CacheGroup.cacheListA.get(name)==null){
OkHttpClient client = new OkHttpClient();
client.newCall(re).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Message message=new Message();
message.obj=e.toString();
message.what=-1;
hd.sendMessage(message);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String body=response.body().string();
//System.out.println(body);
CacheGroup.cacheListA.put(name,body);
Message message=new Message();
message.what=2;
hd.sendMessage(message);
}
});
}else{
System.out.println("已有缓存,不需要再次请求");
Message message=new Message();
message.what=2;
hd.sendMessage(message);
}
}
public static void a3(final String name, Request re, Context con, final Handler hd, long s){
if(CacheGroup.cacheDateList.get(name)==null){
//CustomDialog customDialog= new CustomDialog(con, "正在加载...");
//customDialog.show();//显示,显示时页面不可点击,只能点击返回
OkHttpClient client = new OkHttpClient();
client.newCall(re).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Message message=new Message();
message.obj=FEEDBACK;
message.what=-1;
hd.sendMessage(message);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String body=response.body().string();
//System.out.println(body);
Date d=new Date();
CacheGroup.cacheTimeList.put(name, d);
CacheGroup.cacheDateList.put(name, body);
Message message=new Message();
message.what=3;
hd.sendMessage(message);
//customDialog.dismiss();
}
});
}else{
Date ds=new Date();
System.out.println("时间差:"+ Timer.TimeD(ds,CacheGroup.cacheTimeList.get(name)));
System.out.println("实时时间:"+s);
if(Timer.TimeD(ds,CacheGroup.cacheTimeList.get(name))>=s){
//CustomDialog customDialog= new CustomDialog(con, "正在加载...");
//customDialog.show();//显示,显示时页面不可点击,只能点击返回
OkHttpClient client = new OkHttpClient();
client.newCall(re).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Message message=new Message();
message.obj=FEEDBACK;
message.what=-1;
hd.sendMessage(message);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String body=response.body().string();
//System.out.println(body);
Date d=new Date();
CacheGroup.cacheTimeList.put(name, d);
CacheGroup.cacheDateList.put(name, body);
Message message=new Message();
message.what=3;
hd.sendMessage(message);
//customDialog.dismiss();
}
});
}else{
System.out.println("没有超过实时缓存时间,不进行请求");
Message message=new Message();
message.what=3;
hd.sendMessage(message);
}
}
}
public static void a11(final String name,Request re,Context con,final Handler hd){
OkHttpClient client = new OkHttpClient();
client.newCall(re).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Message message=new Message();
message.obj=FEEDBACK;
message.what=-1;
hd.sendMessage(message);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String body=response.body().string();
System.out.println("存储空间"+name);
CacheGroup.cacheList.put(name,body);
Message message=new Message();
message.what=1;
hd.sendMessage(message);
}
});
}
}
@@ -0,0 +1,27 @@
package com.arpa.hndahesudintocctmsdriver.util.http;
public class RequsetCodeConstants {
public static final int ERROR=-1;
//响应码
//登录失效
public static final int NOT_LOGIN=401;
//返回成功
public static final int SUCCESS=200;
//请求地址找不到
public static final int UNKONWN=404;
//网关错误
public static final int GATEWAY_ERROR=502;
//服务器错误
public static final int SERVER_ERROR=500;
//请求的实体过大
public static final int ENTITY_TOO_LARGE=413;
//
public static final String UNKONWN_TEXT="请求地址未找到";
public static final String GATEWAY_ERROR_TEXT="网关错误";
public static final String SERVER_ERROR_TEXT="服务器出现异常";
public static final String ENTITY_TOO_LARGE_TEXT="上传的图片过大";
public static final String FEEDBACK_TEXT="请求失败,请检查网络状况";
}
@@ -0,0 +1,57 @@
package com.arpa.hndahesudintocctmsdriver.util.http;
import java.io.IOException;
/**
* @author hlh
* @version 1.0.0
* @date 2021/9/14 11:01
* @description:
*/
public class SecurityUtil {
/**
* 公钥
*/
private static final String public_key = "04B16143229EF2DF546DE8AEC5E0242E9C7B564A7D6C3D982450DAC0E46606C5851AB710059E2BBCE6D86EE2215B18274EF2642626650F9774AB57F7ADE44DF0A3";
/**
* 私钥
*/
private static final String private_key = "4993A5ED6E3F865279481A96453E4907E5943F0086EAB9C3E3B24C8A36D7CBFD";
/**
* 加密
*
* @param data 带加密数据
* @return 加密后的结果
*/
public static String encrypt(String data) {
String str="";
// try {
// str=SM2Utils.encrypt132(data.getBytes(),Util.hexToByte(public_key));
// } catch (IOException e) {
// e.printStackTrace();
// }
return str;
}
/**
* 解密
*
* @param data 带加密数据
* @return 解密后的结果
*/
public static String decrypt(String data) {
byte[] bs=null;
// try {
// bs=SM2Utils.decrypt132(Util.hexToByte(private_key), Util.hexToByte(data));
// } catch (IOException e) {
// e.printStackTrace();
// }
return new String(bs);
}
}
@@ -0,0 +1,107 @@
package com.arpa.hndahesudintocctmsdriver.util.img;
import android.Manifest;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.arpa.hndahesudintocctmsdriver.R;
import com.arpa.hndahesudintocctmsdriver.util.PicturlUtil;
import com.luck.picture.lib.permissions.RxPermissions;
import java.io.File;
import java.util.ArrayList;
/**
* @author hlh
* @version 1.0.0
* @date 2022/1/4 16:13
* @description:
*/
public class GetCarImageAlert {
File file;
PopupWindow popupWindow;
ImageView img;
public void showPopueWindow(AppCompatActivity act,boolean key){
View popView = View.inflate(act, R.layout.choice_car_timg,null);
Button btn_xiangce =popView.findViewById(R.id.btn_xiangce);
Button btn_paizhao = popView.findViewById(R.id.btn_paizhao);
Button btn_quxiao = popView.findViewById(R.id.btn_quxiao);
View v_1=popView.findViewById(R.id.v_1);
TextView tv_ts=popView.findViewById(R.id.tv_ts);
img=popView.findViewById(R.id.img);
//获取屏幕宽高
int weight =act.getResources().getDisplayMetrics().widthPixels;
int height = act.getResources().getDisplayMetrics().heightPixels*2/3;
popupWindow = new PopupWindow(popView,weight,height);
//popupWindow.setAnimationStyle(R.style.anim_popup_dir);
popupWindow.setFocusable(true);
//点击外部popueWindow消失
popupWindow.setOutsideTouchable(true);
if(key){
btn_xiangce.setVisibility(View.VISIBLE);
img.setImageResource(R.drawable.huidan);
tv_ts.setText("请按照如图所示拍摄回单照片,回单照片必须保持清晰完整,能看清具体吨数,便于结算运费时核查,感谢配合。");
v_1.setVisibility(View.VISIBLE);
//请按照如图所示拍摄回单照片,回单照片必须保持清晰完整,能看清具体吨数,便于结算运费时核查,感谢配合。
}
btn_xiangce.setOnClickListener(v -> {
RxPermissions rp=new RxPermissions(act);
rp.request(
Manifest.permission.READ_EXTERNAL_STORAGE
).subscribe(b -> {
if (b) {
//ImageGetUtil.AlbumGetImage(act);
PicturlUtil.selectPicter(act, new ArrayList<>(), 1);
} else {
Toast.makeText(act.getBaseContext(),"开启权限失败,请手动开启权限",Toast.LENGTH_LONG).show();
}
}
);
});
btn_paizhao.setOnClickListener(v -> {
RxPermissions rp=new RxPermissions(act);
rp.request(
Manifest.permission.CAMERA
).subscribe(b -> {
if (b) {
file=ImageGetUtil.createImageFile(act);
ImageGetUtil.cameraAlbumGetImage(act,file);
} else {
Toast.makeText(act.getBaseContext(),"开启权限失败,请手动开启权限",Toast.LENGTH_LONG).show();
}
}
);
});
btn_quxiao.setOnClickListener(v -> popupWindow.dismiss());
//popupWindow消失屏幕变为不透明
popupWindow.setOnDismissListener(() -> {
WindowManager.LayoutParams lp = act.getWindow().getAttributes();
lp.alpha = 1.0f;
act.getWindow().setAttributes(lp);
});
//popupWindow出现屏幕变为半透明
WindowManager.LayoutParams lp = act.getWindow().getAttributes();
lp.alpha = 0.5f;
act.getWindow().setAttributes(lp);
popupWindow.showAtLocation(popView, Gravity.BOTTOM,0,50);
}
public File getFile() {
return file;
}
public void dis(){
popupWindow.dismiss();
}
}
@@ -0,0 +1,92 @@
package com.arpa.hndahesudintocctmsdriver.util.img;
import android.Manifest;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.arpa.hndahesudintocctmsdriver.util.PicturlUtil;
import com.luck.picture.lib.permissions.RxPermissions;
import com.arpa.hndahesudintocctmsdriver.R;
import java.io.File;
import java.util.ArrayList;
/**
* @author hlh
* @version 1.0.0
* @date 2021/8/16 8:43
* @description:
*/
public class GetImageAlert {
File file;
PopupWindow popupWindow;
public void showPopueWindow(AppCompatActivity act){
View popView = View.inflate(act, R.layout.choice_img,null);
Button btn_xiangce =popView.findViewById(R.id.btn_xiangce);
Button btn_paizhao = popView.findViewById(R.id.btn_paizhao);
Button btn_quxiao = popView.findViewById(R.id.btn_quxiao);
//获取屏幕宽高
int weight =act.getResources().getDisplayMetrics().widthPixels;
int height = act.getResources().getDisplayMetrics().heightPixels*1/3;
popupWindow = new PopupWindow(popView,weight,height);
//popupWindow.setAnimationStyle(R.style.anim_popup_dir);
popupWindow.setFocusable(true);
//点击外部popueWindow消失
popupWindow.setOutsideTouchable(true);
btn_xiangce.setOnClickListener(v -> {
RxPermissions rp=new RxPermissions(act);
rp.request(
Manifest.permission.READ_EXTERNAL_STORAGE
).subscribe(b -> {
if (b) {
PicturlUtil.selectPicter(act, new ArrayList<>(), 1);
} else {
Toast.makeText(act.getBaseContext(),"开启权限失败,请手动开启权限",Toast.LENGTH_LONG).show();
}
}
);
});
btn_paizhao.setOnClickListener(v -> {
RxPermissions rp=new RxPermissions(act);
rp.request(
Manifest.permission.CAMERA
).subscribe(b -> {
if (b) {
file=ImageGetUtil.createImageFile(act);
ImageGetUtil.cameraAlbumGetImage(act,file);
} else {
Toast.makeText(act.getBaseContext(),"开启权限失败,请手动开启权限",Toast.LENGTH_LONG).show();
}
}
);
});
btn_quxiao.setOnClickListener(v -> popupWindow.dismiss());
//popupWindow消失屏幕变为不透明
popupWindow.setOnDismissListener(() -> {
WindowManager.LayoutParams lp = act.getWindow().getAttributes();
lp.alpha = 1.0f;
act.getWindow().setAttributes(lp);
});
//popupWindow出现屏幕变为半透明
WindowManager.LayoutParams lp = act.getWindow().getAttributes();
lp.alpha = 0.5f;
act.getWindow().setAttributes(lp);
popupWindow.showAtLocation(popView, Gravity.BOTTOM,0,50);
}
public File getFile() {
return file;
}
public void dis(){
popupWindow.dismiss();
}
}
@@ -0,0 +1,71 @@
package com.arpa.hndahesudintocctmsdriver.util.img;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import androidx.core.content.FileProvider;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author hlh
* @version 1.0.0
* @date 2021/7/30 16:41
* @description:图片获取工具
*/
public class ImageGetUtil {
public static final int ALBUM_CODE=11;
public static final int CAMERA_CODE=12;
public static void AlbumGetImage(Activity act){
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
act.startActivityForResult(intent,ALBUM_CODE);
}
public static void cameraAlbumGetImage(Activity act,File imageFile){
Uri uri;
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//打开相机的Intent
if(takePhotoIntent.resolveActivity(act.getPackageManager())!=null){//这句作用是如果没有相机则该应用不会闪退,要是不加这句则当系统没有相机应用的时候该应用会闪退
if(imageFile!=null){
if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.N){
/*7.0以上要通过FileProvider将File转化为Uri*/
uri = FileProvider.getUriForFile(act.getApplicationContext(),"com.arpa.hndahesudintocctmsdriver.fileprovider",imageFile);
}else {
/*7.0以下则直接使用Uri的fromFile方法将File转化为Uri*/
uri = Uri.fromFile(imageFile);
}
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT,uri);//将用于输出的文件Uri传递给相机
act.startActivityForResult(takePhotoIntent, CAMERA_CODE);//打开相机
}
}
}
/**
* 创建用来存储图片的文件,以时间来命名就不会产生命名冲突
* @return 创建的图片文件
*/
public static File createImageFile(Activity act) {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_"+timeStamp+"_";
File storageDir = act.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File imageFile = null;
try {
imageFile = File.createTempFile(imageFileName,".jpg",storageDir);
} catch (IOException e) {
e.printStackTrace();
}
return imageFile;
}
}
@@ -0,0 +1,27 @@
package com.arpa.hndahesudintocctmsdriver.util.img;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
/**
* @author hlh
* @version 1.0.0
* @date 2021/7/30 17:21
* @description:uri转化工具
*/
public class ImageUriUtil {
public static String uriTurnPath(Uri uri, Context con){
String path="";
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = con.getContentResolver().query(uri,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
path = cursor.getString(columnIndex);
return path;
}
}
@@ -0,0 +1,35 @@
package com.arpa.hndahesudintocctmsdriver.util.img;
import android.content.Context;
import android.util.AttributeSet;
import androidx.annotation.Nullable;
import com.bumptech.glide.Glide;
import com.arpa.hndahesudintocctmsdriver.R;
/**
* @author hlh
* @version 1.0.0
* @date 2021/11/18 18:00
* @description:
*/
public class ImageViewGif extends androidx.appcompat.widget.AppCompatImageView {
public ImageViewGif(Context context) {
super(context);
Glide.with(context).load(R.drawable.kf).into(this);
}
public ImageViewGif(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
Glide.with(context).load(R.drawable.kf).into(this);
}
public ImageViewGif(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
Glide.with(context).load(R.drawable.kf).into(this);
}
}
@@ -0,0 +1,22 @@
package com.arpa.hndahesudintocctmsdriver.util.json;
import org.json.JSONObject;
/**
* @author hlh
* @version 1.0.0
* @date 2021/10/11 14:45
* @description:
*/
public class JsonUtil {
public boolean isJson(String str){
try {
JSONObject json=new JSONObject(str);
return true;
} catch (Exception e) {
return false;
}
}
}
@@ -0,0 +1,150 @@
package com.arpa.hndahesudintocctmsdriver.util.location;
import android.content.Context;
import android.os.Handler;
import android.util.Log;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.arpa.hndahesudintocctmsdriver.util.msg.MsgUtil;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author hlh
* @version 1.0.0
* @date 2021/8/13 16:13
* @description:高德地图定位
*/
public class LocationGDUtil {
public final static int RES=14;
private double latitude;
private double longitude;
private String address;
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
public String getAddress() {
return address;
}
private Context con;
private Handler hd;
//声明AMapLocationClient类对象
public AMapLocationClient mLocationClient = null;
//声明AMapLocationClientOption对象
public AMapLocationClientOption mLocationOption = null;
//声明定位回调监听器
public AMapLocationListener mLocationListener = new AMapLocationListener() {
@Override
public void onLocationChanged(AMapLocation aMapLocation) {
if (aMapLocation != null) {
if (aMapLocation.getErrorCode() == 0) {
//可在其中解析amapLocation获取相应内容。
Log.e("x经纬度gd",aMapLocation.getLatitude()+"-----");
aMapLocation.getLocationType();//获取当前定位结果来源,如网络定位结果,详见定位类型表
latitude=aMapLocation.getLatitude();//获取纬度
longitude=aMapLocation.getLongitude();//获取经度
aMapLocation.getAccuracy();//获取精度信息
address=aMapLocation.getAddress();//地址,如果option中设置isNeedAddress为false,则没有此结果,网络定位结果中会有地址信息,GPS定位不返回地址信息。
aMapLocation.getCountry();//国家信息
aMapLocation.getProvince();//省信息
aMapLocation.getCity();//城市信息
aMapLocation.getDistrict();//城区信息
aMapLocation.getStreet();//街道信息
aMapLocation.getStreetNum();//街道门牌号信息
aMapLocation.getCityCode();//城市编码
aMapLocation.getAdCode();//地区编码
aMapLocation.getAoiName();//获取当前定位点的AOI信息
aMapLocation.getBuildingId();//获取当前室内定位的建筑物Id
aMapLocation.getFloor();//获取当前室内定位的楼层
aMapLocation.getGpsAccuracyStatus();//获取GPS的当前状态
//获取定位时间
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date(aMapLocation.getTime());
df.format(date);
MsgUtil.addHdMsgWat(hd,RES);
if (mLocationClient!=null) {
mLocationClient.onDestroy();
}
}else {
MsgUtil.addHdMsgWat(hd,16);
//定位失败时,可通过ErrCode(错误码)信息来确定失败的原因,errInfo是错误信息,详见错误码表。
Log.e("AmapError","location Error, ErrCode:"
+ aMapLocation.getErrorCode() + ", errInfo:"
+ aMapLocation.getErrorInfo());
}
}
}
};
public LocationGDUtil(Context con,Handler hd) {
this.con = con;
this.hd=hd;
}
public void onCreate(){
// AMapLocationClient.updatePrivacyShow(con,true,true);
// AMapLocationClient.updatePrivacyAgree(con,true);
//初始化定位
try {
mLocationClient = new AMapLocationClient(con.getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
//设置定位回调监听
mLocationClient.setLocationListener(mLocationListener);
//初始化AMapLocationClientOption对象
mLocationOption = new AMapLocationClientOption();
AMapLocationClientOption option = new AMapLocationClientOption();
/**
* 设置定位场景,目前支持三种场景(签到、出行、运动,默认无场景)
*/
option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
if(null != mLocationClient){
mLocationClient.setLocationOption(option);
//设置场景模式后最好调用一次stop,再调用start以保证场景模式生效
mLocationClient.stopLocation();
mLocationClient.startLocation();
}
//设置定位模式为AMapLocationMode.Hight_Accuracy,高精度模式。
//mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//设置定位模式为AMapLocationMode.Battery_Saving,低功耗模式。
mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//设置定位模式为AMapLocationMode.Device_Sensors,仅设备模式。
//mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Device_Sensors);
//获取一次定位结果:
//该方法默认为false。
mLocationOption.setOnceLocation(true);
//获取最近3s内精度最高的一次定位结果:
//设置setOnceLocationLatest(boolean b)接口为true,启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为truesetOnceLocation(boolean b)接口也会被设置为true,反之不会,默认为false。
mLocationOption.setOnceLocationLatest(true);
//设置是否返回地址信息(默认返回地址信息)
mLocationOption.setNeedAddress(true);
//设置是否允许模拟位置,默认为true,允许模拟位置
mLocationOption.setMockEnable(true);
//单位是毫秒,默认30000毫秒,建议超时时间不要低于8000毫秒。
mLocationOption.setHttpTimeOut(20000);
//关闭缓存机制
mLocationOption.setLocationCacheEnable(false);
//给定位客户端对象设置定位参数
mLocationClient.setLocationOption(mLocationOption);
//启动定位
mLocationClient.stopLocation();
mLocationClient.startLocation();
}
}
@@ -0,0 +1,129 @@
package com.arpa.hndahesudintocctmsdriver.util.location;
import android.content.Context;
import android.os.Handler;
import android.util.Log;
import com.arpa.hndahesudintocctmsdriver.util.msg.MsgUtil;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
/**
* @author hlh
* @version 1.0.0
* @date 2021/8/13 14:13
* @description:定位工具类
*/
public class LocationUtil{
private double latitude;
private double longitude;
private String address;
private Context con;
private Handler hd;
public LocationClient mLocationClient = null;
private MyLocationListener myListener = new MyLocationListener();
public LocationUtil(Context con,Handler hd){
this.con=con;
this.hd=hd;
}
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
public String getAddress() {
return address;
}
public void close(){
if(mLocationClient!=null){
mLocationClient.stop();
}
}
//BDAbstractLocationListener为7.2版本新增的Abstract类型的监听接口
//原有BDLocationListener接口暂时同步保留。具体介绍请参考后文第四步的说明
public void onCreate() {
mLocationClient = new LocationClient(con.getApplicationContext());
//声明LocationClient类
mLocationClient.registerLocationListener(myListener);
//注册监听函数
LocationClientOption option = new LocationClientOption();
option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
//可选,设置定位模式,默认高精度
//LocationMode.Hight_Accuracy:高精度;
//LocationMode. Battery_Saving:低功耗;
//LocationMode. Device_Sensors:仅使用设备;
option.setCoorType("GCJ02");
//可选,设置返回经纬度坐标类型,默认GCJ02
//GCJ02:国测局坐标;
//BD09ll:百度经纬度坐标;
//BD09:百度墨卡托坐标;
//海外地区定位,无需设置坐标类型,统一返回WGS84类型坐标
option.setScanSpan(0);
//可选,设置发起定位请求的间隔,int类型,单位ms
//如果设置为0,则代表单次定位,即仅定位一次,默认为0
//如果设置非0,需设置1000ms以上才有效
option.setOpenGps(true);
//可选,设置是否使用gps,默认false
//使用高精度和仅用设备两种定位模式的,参数必须设置为true
option.setLocationNotify(true);
//可选,设置是否当GPS有效时按照1S/1次频率输出GPS结果,默认false
option.setIgnoreKillProcess(false);
//可选,定位SDK内部是一个service,并放到了独立进程。
//设置是否在stop的时候杀死这个进程,默认(建议)不杀死,即setIgnoreKillProcess(true)
option.SetIgnoreCacheException(false);
//可选,设置是否收集Crash信息,默认收集,即参数为false
option.setWifiCacheTimeOut(5*60*1000);
//可选,V7.2版本新增能力
//如果设置了该接口,首次启动定位时,会先判断当前Wi-Fi是否超出有效期,若超出有效期,会先重新扫描Wi-Fi,然后定位
option.setEnableSimulateGps(false);
option.setIsNeedAddress(true);
//可选,是否需要地址信息,默认为不需要,即参数为false
//如果开发者需要获得当前点的地址信息,此处必须为true
//可选,设置是否需要最新版本的地址信息。默认需要,即参数为true
//可选,设置是否需要过滤GPS仿真结果,默认需要,即参数为false
// option.setNeedNewVersionRgc(true);
//可选,设置是否需要最新版本的地址信息。默认需要,即参数为true
mLocationClient.setLocOption(option);
//mLocationClient为第二步初始化过的LocationClient对象
//需将配置好的LocationClientOption对象,通过setLocOption方法传递给LocationClient对象使用
//更多LocationClientOption的配置,请参照类参考中LocationClientOption类的详细说明
mLocationClient.start();
}
public class MyLocationListener extends BDAbstractLocationListener {
@Override
public void onReceiveLocation(BDLocation location){
//此处的BDLocation为定位结果信息类,通过它的各种get方法可获取定位相关的全部结果
//以下只列举部分获取经纬度相关(常用)的结果信息
//更多结果信息获取说明,请参照类参考中BDLocation类中的说明
address = location.getAddrStr(); //获取详细地址信息
latitude = location.getLatitude(); //获取纬度信息
longitude = location.getLongitude(); //获取经度信息
float radius = location.getRadius(); //获取定位精度,默认值为0.0f
String coorType = location.getCoorType();
//获取经纬度坐标类型,以LocationClientOption中设置过的坐标类型为准
int errorCode = location.getLocType();
//获取定位类型、定位错误返回码,具体信息可参照类参考中BDLocation类中的说明
Log.e("定位位置address",address+"");
Log.e("定位坐标latitude",latitude+"");
Log.e("定位坐标longitude",longitude+"");
Log.e("返回码latitude",errorCode+"");
// if(location.is){
//
// }
MsgUtil.addHdMsgWat(hd,15);
close();
}
}
}
@@ -0,0 +1,40 @@
package com.arpa.hndahesudintocctmsdriver.util.log;
import android.util.Log;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
/**
* @author hlh
* @version 1.0.0
* @date 2022/1/10 16:55
* @description:日志工具类
*/
public class LogUtil{
public static void show(String title,String value){
Log.e(title,value);
Log.d(title,value);
}
public static byte[] desDecrypt(byte[] encryptText, String desKeyParameter) throws Exception {
SecureRandom sr = new SecureRandom();
byte rawKeyData[] = desKeyParameter.getBytes();
DESKeySpec dks = new DESKeySpec(rawKeyData);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, key, sr);
byte encryptedData[] = encryptText;
byte decryptedData[] = cipher.doFinal(encryptedData);
return decryptedData;
}
}
@@ -0,0 +1,19 @@
package com.arpa.hndahesudintocctmsdriver.util.map;
import org.json.JSONObject;
import java.util.Map;
/**
* @author hlh
* @version 1.0.0
* @date 2021/9/13 14:29
* @description:
*/
public class MapUtil {
public static String mapJson(Map map){
JSONObject json=new JSONObject(map);
return json.toString();
}
}
@@ -0,0 +1,25 @@
package com.arpa.hndahesudintocctmsdriver.util.msg;
import android.os.Handler;
import android.os.Message;
/**
* @author hlh
* @version 1.0.0
* @date 2021/7/30 16:29
* @description:
*/
public class MsgUtil {
public static void addHdMsgWat(Handler hd,int what){
Message msg=new Message();
msg.what=what;
hd.sendMessage(msg);
}
public static void addHdMsgWatBody(Handler hd,int what,String body){
Message msg=new Message();
msg.what=what;
msg.obj=body;
hd.sendMessage(msg);
}
}
@@ -0,0 +1,20 @@
package com.arpa.hndahesudintocctmsdriver.util.sp;
import android.content.Context;
import android.content.SharedPreferences;
public class SPUtil {
private static SharedPreferences sp=null;
public static String getSP(Context con, String dataname, String name){
sp=con.getSharedPreferences(dataname,con.MODE_PRIVATE);
return sp.getString(name,"");
}
public static void insSP(Context con, String dataname, String name, String body){
SharedPreferences.Editor editor=con.getSharedPreferences(dataname,con.MODE_PRIVATE).edit();
editor.putString(name,body);
editor.commit();
}
}
@@ -0,0 +1,19 @@
package com.arpa.hndahesudintocctmsdriver.util.statusbar;
import android.app.Activity;
import android.graphics.Color;
import android.os.Build;
import android.view.View;
public class StateStyleUtil {
public static void stateTextColor(Activity a){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// a.getWindow().setBackgroundDrawableResource(R.color.Blue);
a.getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN| View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
a.getWindow().setStatusBarColor(Color.TRANSPARENT);
}
}
}
@@ -0,0 +1,111 @@
package com.arpa.hndahesudintocctmsdriver.util.statusbar;
import android.app.Activity;
import android.os.Build;
import android.view.View;
import android.view.Window;
import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
/**
* Utils for status bar
* Created by qiu on 3/29/16.
*/
public class StatusBar {
//Get alpha color
static int calculateStatusBarColor(int color, int alpha) {
float a = 1 - alpha / 255f;
int red = color >> 16 & 0xff;
int green = color >> 8 & 0xff;
int blue = color & 0xff;
red = (int) (red * a + 0.5);
green = (int) (green * a + 0.5);
blue = (int) (blue * a + 0.5);
return 0xff << 24 | red << 16 | green << 8 | blue;
}
/**
* set statusBarColor
* @param statusColor color
* @param alpha 0 - 255
*/
public static void setStatusBarColor(@NonNull Activity activity, @ColorInt int statusColor, int alpha) {
setStatusBarColor(activity, calculateStatusBarColor(statusColor, alpha));
}
public static void setStatusBarColor(@NonNull Activity activity, @ColorInt int statusColor) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
StatusBarCompatLollipop.setStatusBarColor(activity, statusColor);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
StatusBarCompatKitKat.setStatusBarColor(activity, statusColor);
}
}
public static void translucentStatusBar(@NonNull Activity activity) {
translucentStatusBar(activity, false);
}
/**
* change to full screen mode
* @param hideStatusBarBackground hide status bar alpha Background when SDK > 21, true if hide it
*/
public static void translucentStatusBar(@NonNull Activity activity, boolean hideStatusBarBackground) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
StatusBarCompatLollipop.translucentStatusBar(activity, hideStatusBarBackground);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
StatusBarCompatKitKat.translucentStatusBar(activity);
}
}
public static void setStatusBarColorForCollapsingToolbar(@NonNull Activity activity, AppBarLayout appBarLayout, CollapsingToolbarLayout collapsingToolbarLayout,
Toolbar toolbar, @ColorInt int statusColor) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
StatusBarCompatLollipop.setStatusBarColorForCollapsingToolbar(activity, appBarLayout, collapsingToolbarLayout, toolbar, statusColor);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
StatusBarCompatKitKat.setStatusBarColorForCollapsingToolbar(activity, appBarLayout, collapsingToolbarLayout, toolbar, statusColor);
}
}
public static void changeToLightStatusBar(@NonNull Activity activity) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return;
}
if (activity == null) {
return;
}
Window window = activity.getWindow();
if (window == null) {
return;
}
View decorView = window.getDecorView();
if (decorView == null) {
return;
}
decorView.setSystemUiVisibility(decorView.getSystemUiVisibility() | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
}
public static void cancelLightStatusBar(@NonNull Activity activity) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return;
}
if (activity == null) {
return;
}
Window window = activity.getWindow();
if (window == null) {
return;
}
View decorView = window.getDecorView();
if (decorView == null) {
return;
}
decorView.setSystemUiVisibility(decorView.getSystemUiVisibility() ^ View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
}
}
@@ -0,0 +1,221 @@
package com.arpa.hndahesudintocctmsdriver.util.statusbar;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.view.ViewCompat;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
/**
* After kitkat add fake status bar
* Created by qiu on 8/27/16.
*/
@TargetApi(Build.VERSION_CODES.KITKAT)
class StatusBarCompatKitKat {
private static final String TAG_FAKE_STATUS_BAR_VIEW = "statusBarView";
private static final String TAG_MARGIN_ADDED = "marginAdded";
/**
* node_return statusBar's Height in pixels
*/
private static int getStatusBarHeight(Context context) {
int result = 0;
int resId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resId > 0) {
result = context.getResources().getDimensionPixelOffset(resId);
}
return result;
}
/**
* 1. Add fake statusBarView.
* 2. set tag to statusBarView.
*/
private static View addFakeStatusBarView(Activity activity, int statusBarColor, int statusBarHeight) {
Window window = activity.getWindow();
ViewGroup mDecorView = (ViewGroup) window.getDecorView();
View mStatusBarView = new View(activity);
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, statusBarHeight);
layoutParams.gravity = Gravity.TOP;
mStatusBarView.setLayoutParams(layoutParams);
mStatusBarView.setBackgroundColor(statusBarColor);
mStatusBarView.setTag(TAG_FAKE_STATUS_BAR_VIEW);
mDecorView.addView(mStatusBarView);
return mStatusBarView;
}
/**
* use reserved order to remove is more quickly.
*/
private static void removeFakeStatusBarViewIfExist(Activity activity) {
Window window = activity.getWindow();
ViewGroup mDecorView = (ViewGroup) window.getDecorView();
View fakeView = mDecorView.findViewWithTag(TAG_FAKE_STATUS_BAR_VIEW);
if (fakeView != null) {
mDecorView.removeView(fakeView);
}
}
/**
* add marginTop to simulate set FitsSystemWindow true
*/
private static void addMarginTopToContentChild(View mContentChild, int statusBarHeight) {
if (mContentChild == null) {
return;
}
if (!TAG_MARGIN_ADDED.equals(mContentChild.getTag())) {
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mContentChild.getLayoutParams();
lp.topMargin += statusBarHeight;
mContentChild.setLayoutParams(lp);
mContentChild.setTag(TAG_MARGIN_ADDED);
}
}
/**
* remove marginTop to simulate set FitsSystemWindow false
*/
private static void removeMarginTopOfContentChild(View mContentChild, int statusBarHeight) {
if (mContentChild == null) {
return;
}
if (TAG_MARGIN_ADDED.equals(mContentChild.getTag())) {
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mContentChild.getLayoutParams();
lp.topMargin -= statusBarHeight;
mContentChild.setLayoutParams(lp);
mContentChild.setTag(null);
}
}
/**
* set StatusBarColor
*
* 1. set Window Flag : WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
* 2. removeFakeStatusBarViewIfExist
* 3. addFakeStatusBarView
* 4. addMarginTopToContentChild
* 5. cancel ContentChild's fitsSystemWindow
*/
static void setStatusBarColor(Activity activity, int statusColor) {
Window window = activity.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
ViewGroup mContentView = (ViewGroup) window.findViewById(Window.ID_ANDROID_CONTENT);
View mContentChild = mContentView.getChildAt(0);
int statusBarHeight = getStatusBarHeight(activity);
removeFakeStatusBarViewIfExist(activity);
addFakeStatusBarView(activity, statusColor, statusBarHeight);
addMarginTopToContentChild(mContentChild, statusBarHeight);
if (mContentChild != null) {
ViewCompat.setFitsSystemWindows(mContentChild, false);
}
}
/**
* translucentStatusBar
*
* 1. set Window Flag : WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
* 2. removeFakeStatusBarViewIfExist
* 3. removeMarginTopOfContentChild
* 4. cancel ContentChild's fitsSystemWindow
*/
static void translucentStatusBar(Activity activity) {
Window window = activity.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
ViewGroup mContentView = (ViewGroup) activity.findViewById(Window.ID_ANDROID_CONTENT);
View mContentChild = mContentView.getChildAt(0);
removeFakeStatusBarViewIfExist(activity);
removeMarginTopOfContentChild(mContentChild, getStatusBarHeight(activity));
if (mContentChild != null) {
ViewCompat.setFitsSystemWindows(mContentChild, false);
}
}
/**
* compat for CollapsingToolbarLayout
*
* 1. set Window Flag : WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
* 2. set FitsSystemWindows for views.
* 3. add Toolbar's height, let it layout from top, then add paddingTop to layout normal.
* 4. removeFakeStatusBarViewIfExist
* 5. removeMarginTopOfContentChild
* 6. add OnOffsetChangedListener to change statusBarView's alpha
*/
static void setStatusBarColorForCollapsingToolbar(Activity activity, final AppBarLayout appBarLayout, final CollapsingToolbarLayout collapsingToolbarLayout,
Toolbar toolbar, int statusColor) {
Window window = activity.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
ViewGroup mContentView = (ViewGroup) window.findViewById(Window.ID_ANDROID_CONTENT);
View mContentChild = mContentView.getChildAt(0);
mContentChild.setFitsSystemWindows(false);
((View) appBarLayout.getParent()).setFitsSystemWindows(false);
appBarLayout.setFitsSystemWindows(false);
collapsingToolbarLayout.setFitsSystemWindows(false);
collapsingToolbarLayout.getChildAt(0).setFitsSystemWindows(false);
toolbar.setFitsSystemWindows(false);
if (toolbar.getTag() == null) {
CollapsingToolbarLayout.LayoutParams lp = (CollapsingToolbarLayout.LayoutParams) toolbar.getLayoutParams();
int statusBarHeight = getStatusBarHeight(activity);
lp.height += statusBarHeight;
toolbar.setLayoutParams(lp);
toolbar.setPadding(toolbar.getPaddingLeft(), toolbar.getPaddingTop() + statusBarHeight, toolbar.getPaddingRight(), toolbar.getPaddingBottom());
toolbar.setTag(true);
}
int statusBarHeight = getStatusBarHeight(activity);
removeFakeStatusBarViewIfExist(activity);
removeMarginTopOfContentChild(mContentChild, statusBarHeight);
final View statusView = addFakeStatusBarView(activity, statusColor, statusBarHeight);
CoordinatorLayout.Behavior behavior = ((CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams()).getBehavior();
if (behavior != null && behavior instanceof AppBarLayout.Behavior) {
int verticalOffset = ((AppBarLayout.Behavior) behavior).getTopAndBottomOffset();
if (Math.abs(verticalOffset) > appBarLayout.getHeight() - collapsingToolbarLayout.getScrimVisibleHeightTrigger()) {
statusView.setAlpha(1f);
} else {
statusView.setAlpha(0f);
}
} else {
statusView.setAlpha(0f);
}
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (Math.abs(verticalOffset) > appBarLayout.getHeight() - collapsingToolbarLayout.getScrimVisibleHeightTrigger()) {
if (statusView.getAlpha() == 0) {
statusView.animate().cancel();
statusView.animate().alpha(1f).setDuration(collapsingToolbarLayout.getScrimAnimationDuration()).start();
}
} else {
if (statusView.getAlpha() == 1) {
statusView.animate().cancel();
statusView.animate().alpha(0f).setDuration(collapsingToolbarLayout.getScrimAnimationDuration()).start();
}
}
}
});
}
}
@@ -0,0 +1,193 @@
package com.arpa.hndahesudintocctmsdriver.util.statusbar;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.view.OnApplyWindowInsetsListener;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
/**
* After Lollipop use system method.
* Created by qiu on 8/27/16.
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
class StatusBarCompatLollipop {
/**
* node_return statusBar's Height in pixels
*/
private static int getStatusBarHeight(Context context) {
int result = 0;
int resId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resId > 0) {
result = context.getResources().getDimensionPixelOffset(resId);
}
return result;
}
/**
* set StatusBarColor
*
* 1. set Flags to call setStatusBarColor
* 2. call setSystemUiVisibility to clear translucentStatusBar's Flag.
* 3. set FitsSystemWindows to false
*/
static void setStatusBarColor(Activity activity, int statusColor) {
Window window = activity.getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(statusColor);
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
ViewGroup mContentView = (ViewGroup) window.findViewById(Window.ID_ANDROID_CONTENT);
View mChildView = mContentView.getChildAt(0);
if (mChildView != null) {
ViewCompat.setFitsSystemWindows(mChildView, false);
ViewCompat.requestApplyInsets(mChildView);
}
}
/**
* translucentStatusBar(full-screen)
*
* 1. set Flags to full-screen
* 2. set FitsSystemWindows to false
*
* @param hideStatusBarBackground hide statusBar's shadow
*/
static void translucentStatusBar(Activity activity, boolean hideStatusBarBackground) {
Window window = activity.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
if (hideStatusBarBackground) {
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(Color.TRANSPARENT);
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
} else {
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
}
ViewGroup mContentView = (ViewGroup) window.findViewById(Window.ID_ANDROID_CONTENT);
View mChildView = mContentView.getChildAt(0);
if (mChildView != null) {
ViewCompat.setFitsSystemWindows(mChildView, false);
ViewCompat.requestApplyInsets(mChildView);
}
}
/**
* compat for CollapsingToolbarLayout
*
* 1. change to full-screen mode(like translucentStatusBar).
* 2. cancel CollapsingToolbarLayout's WindowInsets, let it layout as normal(now setStatusBarScrimColor is useless).
* 3. set View's FitsSystemWindow to false.
* 4. add Toolbar's height, let it layout from top, then add paddingTop to layout normal.
* 5. change statusBarColor by AppBarLayout's offset.
* 6. add Listener to change statusBarColor
*/
static void setStatusBarColorForCollapsingToolbar(Activity activity, final AppBarLayout appBarLayout, final CollapsingToolbarLayout collapsingToolbarLayout,
Toolbar toolbar, final int statusColor) {
final Window window = activity.getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
ViewCompat.setOnApplyWindowInsetsListener(collapsingToolbarLayout, new OnApplyWindowInsetsListener() {
@Override
public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
return insets;
}
});
ViewGroup mContentView = (ViewGroup) window.findViewById(Window.ID_ANDROID_CONTENT);
View mChildView = mContentView.getChildAt(0);
if (mChildView != null) {
ViewCompat.setFitsSystemWindows(mChildView, false);
ViewCompat.requestApplyInsets(mChildView);
}
((View) appBarLayout.getParent()).setFitsSystemWindows(false);
appBarLayout.setFitsSystemWindows(false);
toolbar.setFitsSystemWindows(false);
if (toolbar.getTag() == null) {
CollapsingToolbarLayout.LayoutParams lp = (CollapsingToolbarLayout.LayoutParams) toolbar.getLayoutParams();
int statusBarHeight = getStatusBarHeight(activity);
lp.height += statusBarHeight;
toolbar.setLayoutParams(lp);
toolbar.setPadding(toolbar.getPaddingLeft(), toolbar.getPaddingTop() + statusBarHeight, toolbar.getPaddingRight(), toolbar.getPaddingBottom());
toolbar.setTag(true);
}
CoordinatorLayout.Behavior behavior = ((CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams()).getBehavior();
if (behavior != null && behavior instanceof AppBarLayout.Behavior) {
int verticalOffset = ((AppBarLayout.Behavior) behavior).getTopAndBottomOffset();
if (Math.abs(verticalOffset) > appBarLayout.getHeight() - collapsingToolbarLayout.getScrimVisibleHeightTrigger()) {
window.setStatusBarColor(statusColor);
} else {
window.setStatusBarColor(Color.TRANSPARENT);
}
} else {
window.setStatusBarColor(Color.TRANSPARENT);
}
collapsingToolbarLayout.setFitsSystemWindows(false);
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (Math.abs(verticalOffset) > appBarLayout.getHeight() - collapsingToolbarLayout.getScrimVisibleHeightTrigger()) {
if (window.getStatusBarColor() != statusColor) {
startColorAnimation(window.getStatusBarColor(), statusColor, collapsingToolbarLayout.getScrimAnimationDuration(), window);
}
} else {
if (window.getStatusBarColor() != Color.TRANSPARENT) {
startColorAnimation(window.getStatusBarColor(), Color.TRANSPARENT, collapsingToolbarLayout.getScrimAnimationDuration(), window);
}
}
}
});
collapsingToolbarLayout.getChildAt(0).setFitsSystemWindows(false);
collapsingToolbarLayout.setStatusBarScrimColor(statusColor);
}
/**
* use ValueAnimator to change statusBarColor when using collapsingToolbarLayout
*/
static void startColorAnimation(int startColor, int endColor, long duration, final Window window) {
if (sAnimator != null) {
sAnimator.cancel();
}
sAnimator = ValueAnimator.ofArgb(startColor, endColor)
.setDuration(duration);
sAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
if (window != null) {
window.setStatusBarColor((Integer) valueAnimator.getAnimatedValue());
}
}
});
sAnimator.start();
}
private static ValueAnimator sAnimator;
}
@@ -0,0 +1,48 @@
package com.arpa.hndahesudintocctmsdriver.util.statusbar;
import android.app.Activity;
import android.app.Dialog;
import android.graphics.Color;
import android.os.Build;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
public class StatusBarUtil {
public static void setWindowStatusBarColor(Activity activity, int colorResId) {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = activity.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(activity.getResources().getColor(colorResId));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void touming(Window w){
w.requestFeature(Window.FEATURE_NO_TITLE);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = w;
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
| WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//这里删除的话 可以解决华为虚拟按键的覆盖
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
window.setNavigationBarColor(Color.TRANSPARENT);//这里删除的话
}
}
public static void setWindowStatusBarColor(Dialog dialog, int colorResId) {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = dialog.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(dialog.getContext().getResources().getColor(colorResId));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,19 @@
package com.arpa.hndahesudintocctmsdriver.util.string;
/**
* @author hlh
* @version 1.0.0
* @date 2021/8/7 17:54
* @description:字符串工具类
*/
public class StringUtil {
public static String isNull(String in_str,String out_str){
if(in_str==null || in_str.equals("null") || in_str.trim().equals("")){
return out_str;
}
return in_str;
}
}
@@ -0,0 +1,18 @@
package com.arpa.hndahesudintocctmsdriver.util.string;
/**
* @author hlh
* @version 1.0.0
* @date 2021/10/9 11:08
* @description:
*/
public class UrlUtil {
public static String getParam(String url, String name) {
String params = url.substring(url.indexOf("?") + 1);
//Map<String, String> split = Splitter.on("&").withKeyValueSeparator("=").split(params);
return "";
}
}
@@ -0,0 +1,50 @@
package com.arpa.hndahesudintocctmsdriver.util.time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Timer {
public static String formatChange(String time,String old,String news){
SimpleDateFormat sdf = new SimpleDateFormat(old);
SimpleDateFormat sdf1 = new SimpleDateFormat(news);
try {
Date date=sdf.parse(time);
return sdf1.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return "时间格式错误";
}
public static long TimeD(Date d1, Date d2) {
long diff = d1.getTime() - d2.getTime();//这样得到的差值是微秒级别
return diff;
}
public static String getTimer() {
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return df.format(date);
}
public static String getTimerT() {
return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(new Date());
}
public static String getTimerData() {
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd_HHmmss");
return df.format(date);
}
public static boolean compareTimer(String time){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date sd1=new Date();
Date sd2=null;
try {
sd2=df.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
return sd1.after(sd2);
}
}
@@ -0,0 +1,111 @@
package com.arpa.hndahesudintocctmsdriver.util.view;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import com.arpa.hndahesudintocctmsdriver.R;
import com.arpa.hndahesudintocctmsdriver.util.http.RequsetCodeConstants;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
public abstract class BaseActivity extends Activity {
public Context con;
public Activity act;
public static String dataName,dataName2,dataName3="";
public View root;
private String title_text="空白标题";
public Handler hd=new Handler(msg -> {
msgMethod(msg);
return false;
});
public SmartRefreshLayout refreshLayout;
public void msgMethod(Message m){
switch (m.what){
case RequsetCodeConstants.ERROR:
Toast.makeText(con,RequsetCodeConstants.FEEDBACK_TEXT,Toast.LENGTH_SHORT).show();
if(refreshLayout!=null){
refreshLayout.finishRefresh();
}
break;
case RequsetCodeConstants.UNKONWN:
Toast.makeText(con,RequsetCodeConstants.UNKONWN_TEXT,Toast.LENGTH_SHORT).show();
if(refreshLayout!=null){
refreshLayout.finishRefresh();
}
break;
case RequsetCodeConstants.SERVER_ERROR:
Toast.makeText(con,RequsetCodeConstants.SERVER_ERROR_TEXT,Toast.LENGTH_SHORT).show();
if(refreshLayout!=null){
refreshLayout.finishRefresh();
}
break;
case RequsetCodeConstants.GATEWAY_ERROR:
Toast.makeText(con,RequsetCodeConstants.GATEWAY_ERROR_TEXT,Toast.LENGTH_SHORT).show();
if(refreshLayout!=null){
refreshLayout.finishRefresh();
}
break;
}
}
public void initView(Object obj){
//ViewGroup vg=findViewById(layout);
//vg.findViewById(R)
if(findViewById(R.id.return_btn)!=null){
findViewById(R.id.return_btn).setOnClickListener(v -> {
finish();
});
}
if(findViewById(R.id.title_view)!=null){
TextView title_view=findViewById(R.id.title_view);
title_view.setText(title_text);
}
//GetObjectName.ZIModel(vg,obj,con);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
MyReceiver receiver;
private void registerBroadcast() {
// 注册广播接收者
receiver = new MyReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("exit_app");
if(receiver!=null){
Log.e("广播概况",receiver.toString()+"_"+this.toString());
registerReceiver(receiver,filter);
}
}
class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(this);
if(intent.getAction().equals("exit_app")){
finish();
}
}
}
public void setTitle(String title){
this.title_text=title;
}
}
@@ -0,0 +1,95 @@
package com.arpa.hndahesudintocctmsdriver.util.view;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.arpa.hndahesudintocctmsdriver.R;
import com.arpa.hndahesudintocctmsdriver.util.http.RequsetCodeConstants;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
public class BaseAppCompatActivity extends AppCompatActivity {
public Context con;
public Activity act;
public static String dataName,dataName2,dataName3="";
public View root;
public Handler hd=new Handler(msg -> {
msgMethod(msg);
return false;
});
public SmartRefreshLayout refreshLayout;
public void msgMethod(Message m){
switch (m.what){
case RequsetCodeConstants.ERROR:
Toast.makeText(con,RequsetCodeConstants.FEEDBACK_TEXT,Toast.LENGTH_SHORT).show();
if(refreshLayout!=null){
refreshLayout.finishRefresh();
}
break;
case RequsetCodeConstants.UNKONWN:
Toast.makeText(con,RequsetCodeConstants.UNKONWN_TEXT,Toast.LENGTH_SHORT).show();
if(refreshLayout!=null){
refreshLayout.finishRefresh();
}
break;
case RequsetCodeConstants.SERVER_ERROR:
Toast.makeText(con,RequsetCodeConstants.SERVER_ERROR_TEXT,Toast.LENGTH_SHORT).show();
if(refreshLayout!=null){
refreshLayout.finishRefresh();
}
break;
case RequsetCodeConstants.GATEWAY_ERROR:
Toast.makeText(con,RequsetCodeConstants.GATEWAY_ERROR_TEXT,Toast.LENGTH_SHORT).show();
if(refreshLayout!=null){
refreshLayout.finishRefresh();
}
break;
}
}
public void initView(Object obj){
if(findViewById(R.id.return_btn)!=null){
findViewById(R.id.return_btn).setOnClickListener(v -> {
finish();
});
}
//ViewGroup vg=root.findViewById(root.getId());
//GetObjectName.ZIModel(vg,obj,con);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
MyReceiver receiver;
private void registerBroadcast() {
// 注册广播接收者
receiver = new MyReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("exit_app");
registerReceiver(receiver,filter);
}
class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(this);
if(intent.getAction().equals("exit_app")){
finish();
}
}
}
}
@@ -0,0 +1,49 @@
package com.arpa.hndahesudintocctmsdriver.util.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import androidx.lifecycle.Lifecycle;
import com.arpa.hndahesudintocctmsdriver.R;
import com.arpa.hndahesudintocctmsdriver.ui.wallet.BannerApdate;
import com.zhpan.bannerview.BannerViewPager;
import com.zhpan.bannerview.constants.PageStyle;
import java.util.List;
/**
* @author hlh
* @version 1.0.0
* @date 2021/10/11 14:11
* @description:
*/
public class BaseBannerView extends BannerViewPager {
public BaseBannerView(Context context) {
super(context);
}
public BaseBannerView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public BaseBannerView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public BannerApdate init(Context con, Lifecycle li, List<Object> list,int layout){
this.setPageStyle(PageStyle.MULTI_PAGE_SCALE);
BannerApdate ba=new BannerApdate(con,layout);
this.setLifecycleRegistry(li)
.setPageMargin(getResources().getDimensionPixelOffset(R.dimen.dp_20))
.setRevealWidth(getResources().getDimensionPixelOffset(R.dimen.dp_20))
.setAdapter(ba)
.create();
this.refreshData(list);
this.setIndicatorVisibility(View.GONE);
return ba;
}
}
@@ -0,0 +1,108 @@
package com.arpa.hndahesudintocctmsdriver.util.view;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.arpa.hndahesudintocctmsdriver.R;
import com.arpa.hndahesudintocctmsdriver.util.http.RequsetCodeConstants;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import org.jetbrains.annotations.NotNull;
public class BaseFragment extends Fragment {
public SmartRefreshLayout refreshLayout;
public Context con=getContext();
public Activity act=getActivity();
public static String dataName,dataName2,dataName3="";
public View root;
public Handler hd=new Handler(msg -> {
msgMethod(msg);
return false;
});
public void msgMethod(Message m){
switch (m.what){
case RequsetCodeConstants.ERROR:
Toast.makeText(con,RequsetCodeConstants.FEEDBACK_TEXT,Toast.LENGTH_SHORT).show();
if(refreshLayout!=null){
refreshLayout.finishRefresh();
}
break;
case RequsetCodeConstants.UNKONWN:
Toast.makeText(con,RequsetCodeConstants.UNKONWN_TEXT,Toast.LENGTH_SHORT).show();
if(refreshLayout!=null){
refreshLayout.finishRefresh();
}
break;
case RequsetCodeConstants.SERVER_ERROR:
Toast.makeText(con,RequsetCodeConstants.SERVER_ERROR_TEXT,Toast.LENGTH_SHORT).show();
if(refreshLayout!=null){
refreshLayout.finishRefresh();
}
break;
case RequsetCodeConstants.GATEWAY_ERROR:
Toast.makeText(con,RequsetCodeConstants.GATEWAY_ERROR_TEXT,Toast.LENGTH_SHORT).show();
if(refreshLayout!=null){
refreshLayout.finishRefresh();
}
break;
}
}
public void initView(Object obj){
// if(root.getId()!=-1){
// ViewGroup vg=root.findViewById(root.getId());
// GetObjectName.ZIModel(vg,obj,con);
// }
if(root.findViewById(R.id.return_btn)!=null){
root.findViewById(R.id.return_btn).setOnClickListener(v -> {
getActivity().finish();
});
}
}
@Nullable
@org.jetbrains.annotations.Nullable
@Override
public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
//registerBroadcast();
return super.onCreateView(inflater, container, savedInstanceState);
}
MyReceiver receiver;
private void registerBroadcast() {
// 注册广播接收者
receiver = new MyReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("exit_app");
getActivity().registerReceiver(receiver,filter);
}
class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(this);
if(intent.getAction().equals("exit_app")){
getActivity().finish();
}
}
}
}
@@ -0,0 +1,137 @@
package com.arpa.hndahesudintocctmsdriver.util.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.TouchDelegate;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.arpa.hndahesudintocctmsdriver.util.adapter.AdapterAll;
import com.arpa.hndahesudintocctmsdriver.util.adapter.AdapterAlls;
import com.arpa.hndahesudintocctmsdriver.util.adapter.ManyBean;
import java.util.List;
public class BaseRecyclerView extends RecyclerView {
@Override
public TouchDelegate getTouchDelegate() {
return super.getTouchDelegate();
}
public BaseRecyclerView(@NonNull Context context) {
super(context);
}
public BaseRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public BaseRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
private AdapterAlls ra;
private AdapterAll aa;
public AdapterAll createV(Context con,List list, int layout){
LinearLayoutManager layoutManager = new LinearLayoutManager(con);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
this.setLayoutManager(layoutManager);
aa=new AdapterAll(con,list,layout);
this.setAdapter(aa);
return aa;
}
public AdapterAll createH(Context con, List<Object> list,int layout){
LinearLayoutManager layoutManager = new LinearLayoutManager(con);
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
this.setLayoutManager(layoutManager);
aa=new AdapterAll(con,list,layout);
this.setAdapter(aa);
return aa;
}
public AdapterAll createG(int ral,Context con, List<Object> list,int layout){
GridLayoutManager gm=new GridLayoutManager(con,ral){
@Override
public boolean canScrollVertically() {
return false;
}
};
this.setLayoutManager(gm);
aa=new AdapterAll(con,list,layout);
this.setAdapter(aa);
return aa;
}
public AdapterAlls createGs(int ral,Context con, List<ManyBean> list){
this.setLayoutManager(new GridLayoutManager(con,ral));
AdapterAlls ra=new AdapterAlls(con,list);
this.setAdapter(ra);
return ra;
}
//多任务布局
public AdapterAlls creates(Context con, List<ManyBean> list){
LinearLayoutManager layoutManager = new LinearLayoutManager(con);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
this.setLayoutManager(layoutManager);
ra=new AdapterAlls(con,list);
this.setAdapter(ra);
return ra;
}
public void removeAll(){
aa.removeAll();
}
public void updateItemV(int position,Object o){
aa.updateItem(position,o);
}
public void addItemV(Object o){
aa.addItemV(o);
}
public void delItemV(int p){
aa.delItemV(p);
}
public void removeItemV(int index){
aa.removeItemV(index);
}
public void addV(List<ManyBean> list){
}
public void addItem(ManyBean mb){
ra.addItem(mb);
}
public void adds(List<ManyBean> list){
ra.add(list);
}
public AdapterAlls createsH(Context con, List<ManyBean> list){
LinearLayoutManager layoutManager = new LinearLayoutManager(con);
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
this.setLayoutManager(layoutManager);
AdapterAlls ra=new AdapterAlls(con,list);
this.setAdapter(ra);
return ra;
}
//下拉刷新
public void insDropDown(){
}
//上拉加载更多
public void pullUpLoading(){
}
//加载中状态
public void Loading(){
}
//加载无数据状态
public void loadFeedback(){
}
}
@@ -0,0 +1,54 @@
package com.arpa.hndahesudintocctmsdriver.util.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.SlidingDrawer;
public class BaseSlidingDrawer extends SlidingDrawer {
private boolean mVertical;
private int mTopOffset;
public BaseSlidingDrawer(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
int orientation = attrs.getAttributeIntValue("android", "orientation", ORIENTATION_VERTICAL);
mTopOffset = attrs.getAttributeIntValue("android", "topOffset", 0);
mVertical = (orientation == SlidingDrawer.ORIENTATION_VERTICAL);
}
public BaseSlidingDrawer(Context context, AttributeSet attrs) {
super(context, attrs);
int orientation = attrs.getAttributeIntValue("android", "orientation", ORIENTATION_VERTICAL);
mTopOffset = attrs.getAttributeIntValue("android", "topOffset", 0);
mVertical = (orientation == SlidingDrawer.ORIENTATION_VERTICAL);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
final View handle = getHandle();
final View content = getContent();
measureChild(handle, widthMeasureSpec, heightMeasureSpec);
if (mVertical) {
int height = heightSpecSize - handle.getMeasuredHeight() - mTopOffset;
content.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, heightSpecMode));
heightSpecSize = handle.getMeasuredHeight() + mTopOffset + content.getMeasuredHeight();
widthSpecSize = content.getMeasuredWidth();
if (handle.getMeasuredWidth() > widthSpecSize) widthSpecSize = handle.getMeasuredWidth();
}
else {
int width = widthSpecSize - handle.getMeasuredWidth() - mTopOffset;
getContent().measure(MeasureSpec.makeMeasureSpec(width, widthSpecMode), heightMeasureSpec);
widthSpecSize = handle.getMeasuredWidth() + mTopOffset + content.getMeasuredWidth();
heightSpecSize = content.getMeasuredHeight();
if (handle.getMeasuredHeight() > heightSpecSize) heightSpecSize = handle.getMeasuredHeight();
}
setMeasuredDimension(widthSpecSize, heightSpecSize);
}
}
@@ -0,0 +1,198 @@
package com.arpa.hndahesudintocctmsdriver.util.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class BaseTableView extends LinearLayout {
private List<TextView> TextViewlist=new ArrayList<>();
private List<Integer> hang=new ArrayList<>();
private int rol=0;
private int height=0;
public List<TextView> getTextViewlist() {
return TextViewlist;
}
public void setTextViewlist(List<TextView> textViewlist) {
TextViewlist = textViewlist;
}
public BaseTableView(Context context) {
super(context);
}
public BaseTableView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public BaseTableView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void initView(List<List<Table>> lists){
rol=lists.size();
// LinearLayout.LayoutParams vlp = new LinearLayout.LayoutParams(
// LinearLayout.LayoutParams.MATCH_PARENT,
// LinearLayout.LayoutParams.WRAP_CONTENT);
this.setOrientation(LinearLayout.VERTICAL);
//this.setLayoutParams(vlp);
for(int i=0;i<rol;i++){
this.addView(addHangView(lists.get(i)));
}
}
public LinearLayout addHangView(List<Table> list){
LinearLayout li=new LinearLayout(getContext());
LayoutParams vlp = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
li.setLayoutParams(vlp);
li.setOrientation(LinearLayout.HORIZONTAL);
for(int i=0;i<list.size();i++){
li.addView(addView(list.get(i).getBody(),list.get(i).getWeight()));
}
if (hang.size()==0) {
hang.add(list.size());
}else{
hang.add(hang.get(hang.size()-1)+list.size());
}
return li;
}
public TextView addView(String text,int q){
TextView t=new TextView(getContext());
LayoutParams vlp = new LayoutParams(
0,
20,1.0f*q);
t.setLayoutParams(vlp);
t.setGravity(Gravity.CENTER);
t.setText(text);
TextViewlist.add(t);
return t;
}
public void setCellBack(int dr){
for (TextView textView : TextViewlist) {
textView.setBackgroundResource(dr);
}
}
public void setCellSize(int size){
for (TextView textView : TextViewlist) {
textView.setTextSize(size);
}
}
public void setCellHight(int h){
for (TextView textView : TextViewlist) {
LayoutParams lp = (LayoutParams) textView.getLayoutParams();
lp.height=h;
textView.setLayoutParams(lp);
}
}
public void setCellBg(int c){
for (TextView textView : TextViewlist) {
textView.setBackgroundColor(c);
}
}
public void setCellMargin(int l,int t,int r,int b){
for (TextView textView : TextViewlist) {
LayoutParams lp = (LayoutParams) textView.getLayoutParams();
lp.setMargins(l,t,r,b);
textView.setLayoutParams(lp);
}
}
public void setCellColor(int c){
for (TextView textView : TextViewlist) {
textView.setTextColor(c);
}
}
//
public void setHangSize(int hsum,int size){
if(hsum==0){
for(int i=0;i<hang.get(hsum);i++){
TextViewlist.get(i).setTextSize(size);
}
}else{
for(int i=hang.get(hsum-1);i<hang.get(hsum);i++){
TextViewlist.get(i).setTextSize(size);
}
}
}
public void setHangHight(int hsum,int h){
if(hsum==0){
for(int i=0;i<hang.get(hsum);i++){
LayoutParams lp = (LayoutParams) TextViewlist.get(i).getLayoutParams();
lp.height=h;
TextViewlist.get(i).setLayoutParams(lp);
}
}else{
for(int i=hang.get(hsum-1);i<hang.get(hsum);i++){
LayoutParams lp = (LayoutParams) TextViewlist.get(i).getLayoutParams();
lp.height=h;
TextViewlist.get(i).setLayoutParams(lp);
}
}
}
public void setHangBg(int hsum,int c){
if(hsum==0){
for(int i=0;i<hang.get(hsum);i++){
TextViewlist.get(i).setBackgroundColor(c);
}
}else{
for(int i=hang.get(hsum-1);i<hang.get(hsum);i++){
TextViewlist.get(i).setBackgroundColor(c);
}
}
}
public void setHangMargin(int hsum,int l,int t,int r,int b){
if(hsum==0){
for(int i=0;i<hang.get(hsum);i++){
LayoutParams lp = (LayoutParams) TextViewlist.get(i).getLayoutParams();
lp.setMargins(l,t,r,b);
TextViewlist.get(i).setLayoutParams(lp);
}
}else{
for(int i=hang.get(hsum-1);i<hang.get(hsum);i++){
LayoutParams lp = (LayoutParams) TextViewlist.get(i).getLayoutParams();
lp.setMargins(l,t,r,b);
TextViewlist.get(i).setLayoutParams(lp);
}
}
}
public void setHangColor(int hsum,int c){
if(hsum==0){
for(int i=0;i<hang.get(hsum);i++){
TextViewlist.get(i).setTextColor(c);
}
}else{
for(int i=hang.get(hsum-1);i<hang.get(hsum);i++){
TextViewlist.get(i).setTextColor(c);
}
}
}
public void setMargin(int index,int l,int t,int r,int b){
LayoutParams lp = (LayoutParams) TextViewlist.get(index).getLayoutParams();
lp.setMargins(l,t,r,b);
TextViewlist.get(index).setLayoutParams(lp);
}
public void setHeight(int index,int h){
LayoutParams lp = (LayoutParams) TextViewlist.get(index).getLayoutParams();
lp.height=h;
TextViewlist.get(index).setLayoutParams(lp);
}
public void setSize(int index,int size){
TextViewlist.get(index).setTextSize(size);
}
}
@@ -0,0 +1,38 @@
package com.arpa.hndahesudintocctmsdriver.util.view;
import android.content.Context;
import android.widget.TextView;
import androidx.annotation.NonNull;
import com.lxj.xpopup.core.HorizontalAttachPopupView;
import com.arpa.hndahesudintocctmsdriver.R;
/**
* @author hlh
* @version 1.0.0
* @date 2021/8/19 16:15
* @description:
*/
public class BaseTextAlertPopup extends HorizontalAttachPopupView {
private String body;
public BaseTextAlertPopup(@NonNull Context context,String body) {
super(context);
this.body=body;
}
@Override
protected int getImplLayoutId() {
return 0;
}
@Override
protected void onCreate() {
String a="使用我们产品前";
super.onCreate();
TextView text=findViewById(R.id.text);
text.setText(body);
}
}
@@ -0,0 +1,50 @@
package com.arpa.hndahesudintocctmsdriver.util.view;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;
import com.lxj.xpopup.XPopup;
import org.jetbrains.annotations.NotNull;
/**
* @author hlh
* @version 1.0.0
* @date 2021/8/19 15:49
* @description:
*/
public class BaseTextView extends AppCompatTextView{
public BaseTextView(@NonNull @NotNull Context context) {
super(context);
openShow();
}
public BaseTextView(@NonNull @NotNull Context context, @Nullable @org.jetbrains.annotations.Nullable AttributeSet attrs) {
super(context, attrs);
}
public BaseTextView(@NonNull @NotNull Context context, @Nullable @org.jetbrains.annotations.Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void openShow(){
this.setOnClickListener(v -> {
Log.e("點擊了","123456");
new XPopup.Builder(getContext())
.isDestroyOnDismiss(true) //对于只使用一次的弹窗,推荐设置这个
//.offsetX(50) //偏移10
// .offsetY(10) //往下偏移10
// .popupPosition(PopupPosition.Right) //手动指定位置,有可能被遮盖
.hasShadowBg(false) // 去掉半透明背景
.atView(v)
.asCustom(new BaseTextAlertPopup(getContext(),this.getText()+""))
.show();
});
}
}
@@ -0,0 +1,48 @@
package com.arpa.hndahesudintocctmsdriver.util.view;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
public class BottomTabUtil {
private AppCompatActivity act;
private int layout;
private FragmentManager fm;
private Fragment[] fs;
private int index=0;
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public BottomTabUtil(AppCompatActivity act, int layout, Fragment[] fs) {
this.act = act;
this.layout = layout;
this.fs = fs;
}
public void selectItem(Fragment f){
fm = act.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
//ft.replace(R.id.body,f);
ft.add(layout,f,"").commit();
}
public void setDefaultFragment(Fragment f) {
fm =act.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.hide(fs[index]);
ft.show(f);
ft.commit();
}
public void hide(Fragment f) {
fm =act.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.hide(f);
ft.commit();
}
}
@@ -0,0 +1,204 @@
package com.arpa.hndahesudintocctmsdriver.util.view;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.OvershootInterpolator;
import androidx.annotation.ColorRes;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import com.arpa.hndahesudintocctmsdriver.R;
public class CircularProgressView extends View {
private Paint mBackPaint, mProgPaint; // 绘制画笔
private RectF mRectF; // 绘制区域
private int[] mColorArray; // 圆环渐变色
private int mProgress; // 圆环进度(0-100)
public CircularProgressView(Context context) {
this(context, null);
}
public CircularProgressView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public CircularProgressView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
@SuppressLint("Recycle")
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CircularProgressView);
// 初始化背景圆环画笔
mBackPaint = new Paint();
mBackPaint.setStyle(Paint.Style.STROKE); // 只描边,不填充
mBackPaint.setStrokeCap(Paint.Cap.ROUND); // 设置圆角
mBackPaint.setAntiAlias(true); // 设置抗锯齿
mBackPaint.setDither(true); // 设置抖动
mBackPaint.setStrokeWidth(typedArray.getDimension(R.styleable.CircularProgressView_backWidth, 5));
mBackPaint.setColor(typedArray.getColor(R.styleable.CircularProgressView_backColor, Color.LTGRAY));
// 初始化进度圆环画笔
mProgPaint = new Paint();
mProgPaint.setStyle(Paint.Style.STROKE); // 只描边,不填充
mProgPaint.setStrokeCap(Paint.Cap.ROUND); // 设置圆角
mProgPaint.setAntiAlias(true); // 设置抗锯齿
mProgPaint.setDither(true); // 设置抖动
mProgPaint.setStrokeWidth(typedArray.getDimension(R.styleable.CircularProgressView_progWidth, 10));
mProgPaint.setColor(typedArray.getColor(R.styleable.CircularProgressView_progColor, Color.BLUE));
// 初始化进度圆环渐变色
int startColor = typedArray.getColor(R.styleable.CircularProgressView_progStartColor, -1);
int firstColor = typedArray.getColor(R.styleable.CircularProgressView_progFirstColor, -1);
if (startColor != -1 && firstColor != -1) mColorArray = new int[]{startColor, firstColor};
else mColorArray = null;
// 初始化进度
mProgress = typedArray.getInteger(R.styleable.CircularProgressView_progress, 0);
typedArray.recycle();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int viewWide = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
int viewHigh = getMeasuredHeight() - getPaddingTop() - getPaddingBottom();
int mRectLength = (int) ((viewWide > viewHigh ? viewHigh : viewWide) - (mBackPaint.getStrokeWidth() > mProgPaint.getStrokeWidth() ? mBackPaint.getStrokeWidth() : mProgPaint.getStrokeWidth()));
int mRectL = getPaddingLeft() + (viewWide - mRectLength) / 2;
int mRectT = getPaddingTop() + (viewHigh - mRectLength) / 2;
mRectF = new RectF(mRectL, mRectT, mRectL + mRectLength, mRectT + mRectLength);
// 设置进度圆环渐变色
if (mColorArray != null && mColorArray.length > 1)
mProgPaint.setShader(new LinearGradient(0, 0, 0, getMeasuredWidth(), mColorArray, null, Shader.TileMode.MIRROR));
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawArc(mRectF, 0, 360, false, mBackPaint);
canvas.drawArc(mRectF, 275, 360 * mProgress / 100, false, mProgPaint);
}
// ---------------------------------------------------------------------------------------------
/**
* 获取当前进度
*
* @return 当前进度(0-100
*/
public int getProgress() {
return mProgress;
}
/**
* 设置当前进度
*
* @param progress 当前进度(0-100
*/
public void setProgress(int progress) {
this.mProgress = progress;
invalidate();
}
/**
* 设置当前进度,并展示进度动画。如果动画时间小于等于0,则不展示动画
*
* @param progress 当前进度(0-100
* @param animTime 动画时间(毫秒)
*/
public void setProgress(int progress, long animTime) {
if (animTime <= 0) setProgress(progress);
else {
ValueAnimator animator = ValueAnimator.ofInt(mProgress, progress);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mProgress = (int) animation.getAnimatedValue();
invalidate();
}
});
animator.setInterpolator(new OvershootInterpolator());
animator.setDuration(animTime);
animator.start();
}
}
/**
* 设置背景圆环宽度
*
* @param width 背景圆环宽度
*/
public void setBackWidth(int width) {
mBackPaint.setStrokeWidth(width);
invalidate();
}
/**
* 设置背景圆环颜色
*
* @param color 背景圆环颜色
*/
public void setBackColor(@ColorRes int color) {
mBackPaint.setColor(ContextCompat.getColor(getContext(), color));
invalidate();
}
/**
* 设置进度圆环宽度
*
* @param width 进度圆环宽度
*/
public void setProgWidth(int width) {
mProgPaint.setStrokeWidth(width);
invalidate();
}
/**
* 设置进度圆环颜色
*
* @param color 景圆环颜色
*/
public void setProgColor(@ColorRes int color) {
mProgPaint.setColor(ContextCompat.getColor(getContext(), color));
mProgPaint.setShader(null);
invalidate();
}
/**
* 设置进度圆环颜色(支持渐变色)
*
* @param startColor 进度圆环开始颜色
* @param firstColor 进度圆环结束颜色
*/
public void setProgColor(@ColorRes int startColor, @ColorRes int firstColor) {
mColorArray = new int[]{ContextCompat.getColor(getContext(), startColor), ContextCompat.getColor(getContext(), firstColor)};
mProgPaint.setShader(new LinearGradient(0, 0, 0, getMeasuredWidth(), mColorArray, null, Shader.TileMode.MIRROR));
invalidate();
}
/**
* 设置进度圆环颜色(支持渐变色)
*
* @param colorArray 渐变色集合
*/
public void setProgColor(@ColorRes int[] colorArray) {
if (colorArray == null || colorArray.length < 2) return;
mColorArray = new int[colorArray.length];
for (int index = 0; index < colorArray.length; index++)
mColorArray[index] = ContextCompat.getColor(getContext(), colorArray[index]);
mProgPaint.setShader(new LinearGradient(0, 0, 0, getMeasuredWidth(), mColorArray, null, Shader.TileMode.MIRROR));
invalidate();
}
}
@@ -0,0 +1,22 @@
package com.arpa.hndahesudintocctmsdriver.util.view;
import android.content.Context;
public class DensityUtil {
/**
* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
*/
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
/**
* 根据手机的分辨率从 px(像素) 的单位 转成为 dp
*/
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
}
@@ -0,0 +1,11 @@
package com.arpa.hndahesudintocctmsdriver.util.view;
import android.content.Context;
import android.util.TypedValue;
public class PX_DP {
public static int getDp(int body,Context con){
return ((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, body,con.getResources().getDisplayMetrics()));
}
}
@@ -0,0 +1,23 @@
package com.arpa.hndahesudintocctmsdriver.util.view;
import android.content.Context;
import com.arpa.hndahesudintocctmsdriver.ui.login.LoginActivity;
import com.arpa.hndahesudintocctmsdriver.util.sp.SPUtil;
/**
* @author hlh
* @version 1.0.0
* @date 2021/8/2 10:33
* @description:判断事件的工具
*/
public class PanDuanUtil {
public static boolean isLogin(Context con){
String token=SPUtil.getSP(con, LoginActivity.USER,LoginActivity.USER_TOKEN);
if(token.equals("")){
return false;
}
return true;
}
}
@@ -0,0 +1,120 @@
package com.arpa.hndahesudintocctmsdriver.util.view;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import androidx.annotation.Nullable;
import com.arpa.hndahesudintocctmsdriver.R;
/**
* @author hlh
* @version 1.0.0
* @date 2021/8/7 15:46
* @description:评分view
*/
public class ScoreView extends LinearLayout {
private ImageButton[] xings=new ImageButton[5];
private int score=0;
private boolean upKey=true;
public ScoreView(Context context) {
super(context);
}
public ScoreView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public ScoreView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public ScoreView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public void initView(){
this.setOrientation(LinearLayout.HORIZONTAL);
View v=inflate(getContext(),R.layout.item_view_score,null);
xings[0]=v.findViewById(R.id.xing1);
xings[1]=v.findViewById(R.id.xing2);
xings[2]=v.findViewById(R.id.xing3);
xings[3]=v.findViewById(R.id.xing4);
xings[4]=v.findViewById(R.id.xing5);
xings[0].setOnClickListener(v1 -> {
switchClick(0);
});
xings[1].setOnClickListener(v1 -> {
switchClick(1);
});
xings[2].setOnClickListener(v1 -> {
switchClick(2);
});
xings[3].setOnClickListener(v1 -> {
switchClick(3);
});
xings[4].setOnClickListener(v1 -> {
switchClick(4);
});
this.addView(v);
}
public void switchClick(int i){
if (upKey) {
for(int j=0;j<xings.length;j++){
Log.e("-j-",j+"");
xings[j].setImageResource(R.mipmap.xingxing0);
}
switch (i){
case 4:
xings[4].setImageResource(R.mipmap.xingxing);
xings[3].setImageResource(R.mipmap.xingxing);
xings[2].setImageResource(R.mipmap.xingxing);
xings[1].setImageResource(R.mipmap.xingxing);
xings[0].setImageResource(R.mipmap.xingxing);
score=5;
break;
case 3:
xings[3].setImageResource(R.mipmap.xingxing);
xings[2].setImageResource(R.mipmap.xingxing);
xings[1].setImageResource(R.mipmap.xingxing);
xings[0].setImageResource(R.mipmap.xingxing);
score=4;
break;
case 2:
xings[2].setImageResource(R.mipmap.xingxing);
xings[1].setImageResource(R.mipmap.xingxing);
xings[0].setImageResource(R.mipmap.xingxing);
score=3;
break;
case 1:
xings[1].setImageResource(R.mipmap.xingxing);
xings[0].setImageResource(R.mipmap.xingxing);
score=2;
break;
case 0:
xings[0].setImageResource(R.mipmap.xingxing);
score=1;
break;
default:break;
}
}
}
public int getScore() {
return score;
}
public void setScore(int s){
switchClick(s-1);
}
public void setUpKey(boolean upKey) {
this.upKey = upKey;
}
}
@@ -0,0 +1,35 @@
package com.arpa.hndahesudintocctmsdriver.util.view;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import java.util.List;
public class TabUtil extends FragmentPagerAdapter {
private List<Fragment> fs;
private List<String> titles;
public TabUtil(FragmentManager fm, List<Fragment> fs, List<String> titles){
super(fm);
this.fs=fs;
this.titles=titles;
}
@NonNull
@Override
public Fragment getItem(int position) {
return fs.get(position);
}
@Override
public int getCount() {
return fs.size();
}
@Override
public CharSequence getPageTitle(int position) {
return titles.get(position);
}
}
@@ -0,0 +1,31 @@
package com.arpa.hndahesudintocctmsdriver.util.view;
public class Table {
private String body;
private int weight;
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public Table(String body, int weight) {
this.body = body;
this.weight = weight;
}
public Table() {
}
}