Random random = new Random();
//产生随机数 [20~11] 之间
int valueKqwd = random.nextInt((20- 11+ 1)) + 11;
String.format("%.1f",(double)valueKqwd/10);//向左移动一位小数点
((TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId()
/**
* 获取当前时间
*/
public static String getTimes(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(new Date());
}
/**
* 获取网口的MAC地址
* @return 返回MAC值
*/
public static String getWireMac(){
String strMacAddress = null;
try {
byte[] b = NetworkInterface.getByName("eth0")
.getHardwareAddress();
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < b.length; i++) {
if (i != 0) {
buffer.append(':');
}
System.out.println("b:"+(b[i]&0xFF));
String str = Integer.toHexString(b[i] & 0xFF);
buffer.append(str.length() == 1 ? 0 + str : str);
}
strMacAddress = buffer.toString().toUpperCase();
Log.d("TAG",strMacAddress);
} catch (Exception e) {
e.printStackTrace();
}
return strMacAddress;
}
/**
* 判断某一时间是否在一个区间内
*
* @param sourceTime 时间区间,半闭合,如[10:00-20:00)
* @param curTime 需要判断的时间 如10:00
* @return
* @throws IllegalArgumentException
*/
public static boolean isInTime(String sourceTime, String curTime) {
if (sourceTime == null || !sourceTime.contains("-") || !sourceTime.contains(":")) {
throw new IllegalArgumentException("Illegal Argument arg:" + sourceTime);
}
if (curTime == null || !curTime.contains(":")) {
throw new IllegalArgumentException("Illegal Argument arg:" + curTime);
}
String[] args = sourceTime.split("-");
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
try {
long now = sdf.parse(curTime).getTime();
long start = sdf.parse(args[0]).getTime();
long end = sdf.parse(args[1]).getTime();
if (args[1].equals("00:00")) {
args[1] = "24:00";
}
if (end < start) {
if (now >= end && now < start) {
return false;
} else {
return true;
}
}
else {
if (now >= start && now < end) {
return true;
} else {
return false;
}
}
} catch (ParseException e) {
e.printStackTrace();
throw new IllegalArgumentException("Illegal Argument arg:" + sourceTime);
}
}
public class SoftKeyboardUtil {
/**
* 关闭系统的软键盘
* @param activity
*/
public static void dismissSoftKeyboard(Activity activity)
{
View view = activity.getWindow().peekDecorView();
if (view != null)
{
InputMethodManager inputmanger = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
}
/**
* 16进制字符串转化为字母ASCALL码
*
* @param hex 要转化的16进制数,用空格隔开
* 如:53 68 61 64 6f 77
* @return ASCALL码
*/
public static String convertHexToAsCall(String hex) {
StringBuilder sb = new StringBuilder();
String[] split = hex.split(" ");
for (String str : split) {
int i = Integer.parseInt(str, 16);
if (i < 0x20 || i == 0x7F) {//过滤特殊字符
continue;
}
sb.append((char) i);
}
return sb.toString();
}
/**
* 16进制数组转String
*
* @param data byte数组
* @return string
*/
public static String formatHex2String(byte[] data) {
final StringBuilder stringBuilder = new StringBuilder(data.length);
for (byte byteChar : data)
stringBuilder.append(String.format("%02X ", byteChar));
return stringBuilder.toString();
}
/**
* 16进制字符串转换为Byte值
*
* @param src Byte字符串,每个Byte之间没有分隔符,eg:616C6B
* @return byte[]
*/
public static byte[] hexStr2Bytes(String src) {
int m = 0, n = 0;
int l = src.length() / 2;
System.out.println(l);
byte[] ret = new byte[l];
for (int i = 0; i < l; i++) {
m = i * 2 + 1;
n = m + 1;
ret[i] = Byte.decode("0x" + src.substring(i * 2, m) + src.substring(m, n));
}
return ret;
}
/**
* 字符串转换成十六进制字符串
*
* @param str 待转换的ASCII字符串
* @return String 每个Byte之间没有分隔,如: [616C6B]
*/
public static String str2HexStr(String str) {
char[] chars = "0123456789ABCDEF".toCharArray();
StringBuilder sb = new StringBuilder("");
byte[] bs = str.getBytes();
int bit;
for (int i = 0; i < bs.length; i++) {
bit = (bs[i] & 0x0f0) >> 4;
sb.append(chars[bit]);
bit = bs[i] & 0x0f;
sb.append(chars[bit]);
// sb.append(' ');
}
return sb.toString().trim();
}
//byte 数组与 int 的相互转换
public static int byteArrayToInt(byte[] b) {
return b[3] & 0xFF |
(b[2] & 0xFF) << 8 |
(b[1] & 0xFF) << 16 |
(b[0] & 0xFF) << 24;
}
public static byte[] intToByteArray(int a) {
return new byte[] {
(byte) ((a >> 24) & 0xFF),
(byte) ((a >> 16) & 0xFF),
(byte) ((a >> 8) & 0xFF),
(byte) (a & 0xFF)
};
}
/**
* 判断权限集合
* permissions 权限数组
* return false-表示没有改权限 true-表示权限已开启
*/
public static boolean lacksPermissions(Context mContexts,String [] mPermissions) {
for (String permission : mPermissions) {
if (lacksPermission(mContexts, permission)) {
//没有开启权限
return false;
}
}
//权限已开启
return true;
}
/**
* 判断是否缺少权限
*/
private static boolean lacksPermission(Context mContexts, String permission) {
return ContextCompat.checkSelfPermission(mContexts, permission) == PackageManager.PERMISSION_DENIED;
}
/**
* 获取版本号
* @param context
* @return
*/
public static String getVersionName(Context context) {
if (context != null) {
try {
return context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0)
.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
return "4.0.0";
}
/**
* 获取版本
* @param context
* @return
*/
public static int getVersionCode(Context context) {
if (context != null) {
try {
return context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0)
.versionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
return 1;
}
/**
* 设置水印图片在左上角
*
* @param context 上下文
* @param src
* @param watermark
* @param paddingLeft
* @param paddingTop
* @return
*/
public static Bitmap createWaterMaskLeftTop(Context context, Bitmap src, Bitmap watermark, int paddingLeft, int paddingTop) {
return createWaterMaskBitmap(src, watermark,
dp2px(context, paddingLeft), dp2px(context, paddingTop));
}
private static Bitmap createWaterMaskBitmap(Bitmap src, Bitmap watermark, int paddingLeft, int paddingTop) {
if (src == null) {
return null;
}
int width = src.getWidth();
int height = src.getHeight();
//创建一个bitmap
Bitmap newb = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);// 创建一个新的和SRC长度宽度一样的位图
//将该图片作为画布
Canvas canvas = new Canvas(newb);
//在画布 0,0坐标上开始绘制原始图片
canvas.drawBitmap(src, 0, 0, null);
//在画布上绘制水印图片
canvas.drawBitmap(watermark, paddingLeft, paddingTop, null);
// 保存
canvas.save();//Canvas.ALL_SAVE_FLAG
// 存储
canvas.restore();
return newb;
}
/**
* 设置水印图片在右下角
*
* @param context 上下文
* @param src
* @param watermark
* @param paddingRight
* @param paddingBottom
* @return
*/
public static Bitmap createWaterMaskRightBottom(Context context, Bitmap src, Bitmap watermark, int paddingRight, int paddingBottom) {
return createWaterMaskBitmap(src, watermark,
src.getWidth() - watermark.getWidth() - dp2px(context, paddingRight),
src.getHeight() - watermark.getHeight() - dp2px(context, paddingBottom));
}
/**
* 设置水印图片到右上角
*
* @param context
* @param src
* @param watermark
* @param paddingRight
* @param paddingTop
* @return
*/
public static Bitmap createWaterMaskRightTop(Context context, Bitmap src, Bitmap watermark, int paddingRight, int paddingTop) {
return createWaterMaskBitmap(src, watermark,
src.getWidth() - watermark.getWidth() - dp2px(context, paddingRight),
dp2px(context, paddingTop));
}
/**
* 设置水印图片到左下角
*
* @param context
* @param src
* @param watermark
* @param paddingLeft
* @param paddingBottom
* @return
*/
public static Bitmap createWaterMaskLeftBottom(Context context, Bitmap src, Bitmap watermark, int paddingLeft, int paddingBottom) {
return createWaterMaskBitmap(src, watermark, dp2px(context, paddingLeft),
src.getHeight() - watermark.getHeight() - dp2px(context, paddingBottom));
}
/**
* 设置水印图片到中间
*
* @param src
* @param watermark
* @return
*/
public static Bitmap createWaterMaskCenter(Bitmap src, Bitmap watermark) {
return createWaterMaskBitmap(src, watermark,
(src.getWidth() - watermark.getWidth()) / 2,
(src.getHeight() - watermark.getHeight()) / 2);
}
/**
* 给图片添加文字到左上角
*
* @param context
* @param bitmap
* @param text
* @return
*/
public static Bitmap drawTextToLeftTop(Context context, Bitmap bitmap, String text, int size, int color, int paddingLeft, int paddingTop) {
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(color);
paint.setTextSize(dp2px(context, size));
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
return drawTextToBitmap(context, bitmap, text, paint, bounds,
dp2px(context, paddingLeft),
dp2px(context, paddingTop) + bounds.height());
}
/**
* 绘制文字到右下角
*
* @param context
* @param bitmap
* @param text
* @param size
* @param color
* @return
*/
public static Bitmap drawTextToRightBottom(Context context, Bitmap bitmap, String text, int size, int color, int paddingRight, int paddingBottom) {
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(color);
paint.setTextSize(dp2px(context, size));
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
return drawTextToBitmap(context, bitmap, text, paint, bounds,
bitmap.getWidth() - bounds.width() - dp2px(context, paddingRight),
bitmap.getHeight() - dp2px(context, paddingBottom));
}
/**
* 绘制文字到右上方
*
* @param context
* @param bitmap
* @param text
* @param size
* @param color
* @param paddingRight
* @param paddingTop
* @return
*/
public static Bitmap drawTextToRightTop(Context context, Bitmap bitmap, String text, int size, int color, int paddingRight, int paddingTop) {
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(color);
paint.setTextSize(dp2px(context, size));
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
return drawTextToBitmap(context, bitmap, text, paint, bounds,
bitmap.getWidth() - bounds.width() - dp2px(context, paddingRight),
dp2px(context, paddingTop) + bounds.height());
}
/**
* 绘制文字到左下方
*
* @param context
* @param bitmap
* @param text
* @param size
* @param color
* @param paddingLeft
* @param paddingBottom
* @return
*/
public static Bitmap drawTextToLeftBottom(Context context, Bitmap bitmap, String text, int size, int color, int paddingLeft, int paddingBottom) {
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(color);
paint.setTextSize(dp2px(context, size));
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
return drawTextToBitmap(context, bitmap, text, paint, bounds,
dp2px(context, paddingLeft),
bitmap.getHeight() - dp2px(context, paddingBottom));
}
/**
* 绘制文字到中间
*
* @param context
* @param bitmap
* @param text
* @param size
* @param color
* @return
*/
public static Bitmap drawTextToCenter(Context context, Bitmap bitmap, String text, int size, int color) {
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(color);
paint.setTextSize(dp2px(context, size));
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
return drawTextToBitmap(context, bitmap, text, paint, bounds,
(bitmap.getWidth() - bounds.width()) / 2,
(bitmap.getHeight() + bounds.height()) / 2);
}
//图片上绘制文字
private static Bitmap drawTextToBitmap(Context context, Bitmap bitmap, String text, Paint paint, Rect bounds, int paddingLeft, int paddingTop) {
android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
paint.setDither(true); // 获取跟清晰的图像采样
paint.setFilterBitmap(true);// 过滤一些
if (bitmapConfig == null) {
bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
}
bitmap = bitmap.copy(bitmapConfig, true);
Canvas canvas = new Canvas(bitmap);
canvas.drawText(text, paddingLeft, paddingTop, paint);
return bitmap;
}
/**
* 缩放图片
*
* @param src
* @param w
* @param h
* @return
*/
public static Bitmap scaleWithWH(Bitmap src, double w, double h) {
if (w == 0 || h == 0 || src == null) {
return src;
} else {
// 记录src的宽高
int width = src.getWidth();
int height = src.getHeight();
// 创建一个matrix容器
Matrix matrix = new Matrix();
// 计算缩放比例
float scaleWidth = (float) (w / width);
float scaleHeight = (float) (h / height);
// 开始缩放
matrix.postScale(scaleWidth, scaleHeight);
// 创建缩放后的图片
return Bitmap.createBitmap(src, 0, 0, width, height, matrix, true);
}
}
/**
* dip转pix
*
* @param context
* @param dp
* @return
*/
public static int dp2px(Context context, float dp) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dp * scale + 0.5f);
}
//1.首先在清单文件配置权限
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
//2.然后逻辑代码中首先要判断是否是8.0及其以上的版本
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
if (getPackageManager().canRequestPackageInstalls()) { //是否开启安装应用权限 true为开启,false为未开启。
//检查更新
checkUpdate();
} else {
DialogHandle.getHandle(mContext) //自定义弹框
.show(new DialogHandle.dialogOnclick() {
@Override
public void nativeCallback(NobgDialog dialog) {
dialog.dismiss();
}
@Override
public void positiveCallback(NobgDialog dialog) {
Uri packageruri = Uri.parse("package:" + getPackageName());
Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageruri);
startActivityForResult(intent, 985);
dialog.dismiss();
}
})
.setTitle("温馨提示")
.setNotice("请前往设置中开启安装应用所需的权限")
.setBtn_nativeTxt("取消")
.setBtn_positiveTxt("确定");
}
} else {
//检查更新
checkUpdate();
}
//3.===================返回程序=================
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 985) {
//检查更新
checkUpdate();
}
}
//TessBaseAPI初始化用到的第一个参数,是个目录
public static final String DATAPATH = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
//在DATAPATH中新建这个目录
public static final String tessdata = DATAPATH + File.separator + "文件";
//assets中的文件名
public static String DEFAULT_LANGUAGE_NAME = "文件.txt";
//保存到SD卡中的完整文件名
public static String LANGUAGE_PATH = tessdata + File.separator + DEFAULT_LANGUAGE_NAME;
//使用
/**
* 检测sd卡是否存在
* 若不存在,从assets获取到本地sd卡
*/
if (!checkTrainedDataExists()) {
SDUtils.assets2SD(context.getApplicationContext(), LANGUAGE_PATH, DEFAULT_LANGUAGE_NAME);
}
private static boolean checkTrainedDataExists() {
File file = new File(LANGUAGE_PATH);
return file.exists();
}
public class SDUtils {
/**
* 将assets中的文件复制到SD卡中
*
* @param path 要存放在SD卡中的 完整的文件名。这里是"/storage/emulated/0/tessdata/文件"
* @param name assets中的文件名 这里是 "文件"
*/
public static void assets2SD(Context context, String path, String name) {
//如果存在就删掉
File f = new File(path);
if (f.exists()) {
f.delete();
}
if (!f.exists()) {
File p = new File(Objects.requireNonNull(f.getParent()));//返回此抽象路径名父目录的路径名字符串
if (!p.exists()) {
p.mkdirs();//建立多级文件夹
}
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
InputStream is = null;
OutputStream os = null;
try {
//打开assets文件获得一个InputStream字节输入流
is = context.getAssets().open(name);
File file = new File(path);
// 创建一个向指定 File 对象表示的文件中写入数据的文件输出流
os = new FileOutputStream(file);
byte[] bytes = new byte[4096];
int len = 0;
//从输入流中读取一定数量的字节,并将其存储在缓冲区数组bytes中
//如果因为流位于文件末尾而没有可用的字节,则返回值-1
while ((len = is.read(bytes)) != -1) {
//将指定byte数组中从偏移量off开始的len个字节写入此缓冲的输出流
os.write(bytes, 0, len);
}
//java在使用流时,都会有一个缓冲区,按一种它认为比较高效的方法来发数据:把要发的数据先放到缓冲区,
//缓冲区放满以后再一次性发过去,而不是分开一次一次地发
//flush()强制将缓冲区中的数据发送出去,不必等到缓冲区满
os.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//关闭输入流和输出流
if (is != null)
is.close();
if (os != null)
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 异或校验
* @param data
* @return
*/
public static String getBCC(byte[] data) {
String ret = "";
byte BCC[] = new byte[1];
for (int i = 0; i < data.length; i++) {
BCC[0] = (byte) (BCC[0] ^ data[i]);
}
String hex = Integer.toHexString(BCC[0] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
ret += hex.toUpperCase();
return ret;
}
- 将字符串编码成16进制数字,适用于所有字符(包括中文)
private static String hexString = "0123456789ABCDEF";
/**
* 将字符串编码成16进制数字,适用于所有字符(包括中文)
*/
public static String encode(String str) {
// 根据默认编码获取字节数组
byte[] bytes = str.getBytes(Charset.forName("GBK"));
StringBuilder sb = new StringBuilder(bytes.length * 2);
// 将字节数组中每个字节拆解成2位16进制整数
for (byte aByte : bytes) {
sb.append(hexString.charAt((aByte & 0xf0) >> 4));
sb.append(hexString.charAt((aByte & 0x0f)));
}
return sb.toString();
}