107 lines
3.0 KiB
Java
107 lines
3.0 KiB
Java
package com.xwad.os.manager;
|
||
|
||
import android.text.TextUtils;
|
||
|
||
import com.tencent.mmkv.MMKV;
|
||
import com.xwad.os.config.CommonConfig;
|
||
|
||
import java.util.Random;
|
||
import java.text.SimpleDateFormat;
|
||
import java.util.Date;
|
||
import java.util.Locale;
|
||
|
||
public class DeviceSNManager {
|
||
private static final String SN_KEY = "device_sn";
|
||
private static final String PREFIX = "CDSN";
|
||
private static final int RANDOM_DIGITS = 9;
|
||
|
||
private static MMKV mMMKV = MMKV.mmkvWithID(CommonConfig.MMKV_ID, MMKV.MULTI_PROCESS_MODE);
|
||
|
||
public DeviceSNManager() {
|
||
|
||
}
|
||
|
||
/**
|
||
* 获取设备SN,如果不存在则创建新的
|
||
*/
|
||
public static String getDeviceSN() {
|
||
String existingSN = mMMKV.decodeString(SN_KEY, "");
|
||
|
||
// if (!TextUtils.isEmpty(existingSN)) {
|
||
return existingSN;
|
||
// }
|
||
|
||
// String newSN = generateNewSN();
|
||
// mMMKV.encode(SN_KEY, newSN);
|
||
// return newSN;
|
||
}
|
||
|
||
public static void saveDeviceSN(String sn) {
|
||
mMMKV.encode(SN_KEY, sn);
|
||
}
|
||
|
||
|
||
/**
|
||
* 生成新的设备SN
|
||
* 格式:CDSN202511T923852225
|
||
*/
|
||
private static String generateNewSN() {
|
||
StringBuilder snBuilder = new StringBuilder();
|
||
// 添加前缀
|
||
snBuilder.append(PREFIX);
|
||
// 添加年份月份
|
||
String timeYear = formatTimestamp(System.currentTimeMillis());
|
||
snBuilder.append(timeYear);
|
||
|
||
// 添加基于时间戳的9位随机数字
|
||
snBuilder.append(generateRandomString(10));
|
||
|
||
return snBuilder.toString();
|
||
}
|
||
|
||
// 定义可供随机选择的字符池
|
||
private static final String LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||
private static final String LETTERS_AND_DIGITS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||
|
||
public static String generateRandomString(int length) {
|
||
if (length < 1) {
|
||
throw new IllegalArgumentException("Length must be at least 1");
|
||
}
|
||
|
||
Random random = new Random();
|
||
StringBuilder sb = new StringBuilder(length);
|
||
|
||
// 第一位:确保是字母
|
||
sb.append(LETTERS.charAt(random.nextInt(LETTERS.length())));
|
||
|
||
// 剩余位数:字母或数字
|
||
for (int i = 1; i < length; i++) {
|
||
sb.append(LETTERS_AND_DIGITS.charAt(random.nextInt(LETTERS_AND_DIGITS.length())));
|
||
}
|
||
|
||
return sb.toString();
|
||
}
|
||
|
||
/**
|
||
* 删除已存储的SN(用于测试或重新生成)
|
||
*/
|
||
public static void clearDeviceSN() {
|
||
mMMKV.removeValueForKey(SN_KEY);
|
||
}
|
||
|
||
/**
|
||
* 检查是否已存在SN
|
||
*/
|
||
public static boolean hasDeviceSN() {
|
||
return mMMKV.containsKey(SN_KEY) && !TextUtils.isEmpty(mMMKV.decodeString(SN_KEY, ""));
|
||
}
|
||
|
||
public static String formatTimestamp(long timestamp) {
|
||
// 创建指定格式的格式化对象,"yyyyMM" 表示6位数字的年份和月份,"'T'" 表示字面量字符 T
|
||
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM'T'");
|
||
Date date = new Date(timestamp);
|
||
// 将 Date 对象格式化为字符串
|
||
return sdf.format(date);
|
||
}
|
||
}
|