书接上文《踩坑系列之海信安卓设备获取UUID》,这个问题还是没有解决。即使采用获取设备信息的方式获取的唯一码,同批次设备还是一样的,既然这样,那就只能使用终极方案。自己管理唯一标识。
上文中提到过的方案4,当时是以为有些麻烦,因为要h5和app进行交互。经过查找资料,以及实际验证,完全可以在H5中直接处理。有以下两种方案。
方案一
使用html5和js实现,利用FileReader和FileWriter实现文件的读写,具体参考《HTML5来实现本地文件读取和写入的实现方法》
此方案未经采用,使用环境为APP,文中描述的以浏览器环境为主。如果是windows模式的智慧屏想实现本地唯一码,倒是可以采用这种方式。
方案二
使用html5plus的native.js,实现文件的读写。参考了网友的提供的资料,非常感谢。《分享下安卓下文件和目录的读取,写入,移动,删除》
这个方案非常合适,完美解决问题。
具体实现代码
// 生成本地uuid
function generateLocalUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0; var v = c === 'x' ? r : (r & 0x3 | 0x8)
return v.toString(16)
})
}
function getSerialNoByLocal() {
// 只能用于安卓 导入java类
const File = window.plus.android.importClass('java.io.File')
const BufferedReader = window.plus.android.importClass('java.io.BufferedReader')
const FileReader = window.plus.android.importClass('java.io.FileReader')
const FileWriter = window.plus.android.importClass('java.io.FileWriter')
// 安卓11以下 /sdcard/自己的文件夹/1.txt
// 安卓11 建议用 /storage/emulated/0/Download/自己的文件夹/1.txt
// 读取txt文件 readFile ("/sdcard/修止符/配置.json")
const readFile = (fileName) => {
const readFr = new File(fileName)
try {
const reader = new BufferedReader(new FileReader(readFr))
let txt
let retxt = ''
let flag = true
while (flag) {
txt = reader.readLine() // 读取文件
if (txt == null) {
flag = false
break
}
retxt = retxt + txt
}
return retxt
} catch (e) {
console.log(e)
return ''
}
}
// 写文件 writeFile("/sdcard/修止符/配置.json",{"主键":"值"})
const writeFile = (fileName, res) => {
res = res ? JSON.stringify(res) : '' // 对象转换为json文本
try {
// 不加根目录创建文件(即用相对地址)的话directory.exists()这个判断一值都是false
const n = fileName.lastIndexOf('/')
if (n !== -1) {
const fileDirs = fileName.substring(0, n)
const directory = new File(fileDirs)
if (!directory.exists()) {
directory.mkdirs() // 不存在创建目录
}
}
const file = new File(fileName)
if (!file.exists()) {
file.createNewFile() // 创建文件
}
const fos = new FileWriter(fileName, false)
fos.write(res)
fos.close()
return true
} catch (e) {
console.log(e)
return false
}
}
const uuidPath = '/sdcard/wisdomApp/uuid.txt'
// 首先读取文件
let uuid = readFile(uuidPath)
// 如果文件内容为空
if (!uuid) {
// uuid为空 则随机生成
uuid = generateLocalUUID()
// 写入文件
writeFile(uuidPath, uuid)
}
// 返回uuid
return uuid
}生成的唯一码路径
生成的文件内容



发表评论