项目开发中关于 uniapp实现 Android和IOS获取App缓存,清除缓存功能

发布于:2024-06-27 ⋅ 阅读:(21) ⋅ 点赞:(0)

新建按钮

<u-button shape="circle" plain type="info" @click="clearStorage"><text style="color: #000;font-size: 32rpx;">当前缓存: {{fileSizeString}}, 点击清除缓存</text></u-button>

获取本机缓存

// 获取缓存
formatSize() {
	plus.cache.calculate((size) => {
		let sizeCache = parseInt(size);
		if (sizeCache == 0) {
			this.fileSizeString = "0B";
		} else if (sizeCache < 1024) {
			this.fileSizeString = sizeCache + "B";
		} else if (sizeCache < 1048576) {
			this.fileSizeString = (sizeCache / 1024).toFixed(2) + "KB";
		} else if (sizeCache < 1073741824) {
			this.fileSizeString = (sizeCache / 1048576).toFixed(2) + "MB";
		} else {
			this.fileSizeString = (sizeCache / 1073741824).toFixed(2) + "GB";
		}
	});
},

清除缓存

// 清除缓存确认
clearStorage() {
	uni.showModal({
		title: '清除缓存',
		content: '您确定要清除缓存吗?',
		success: (res) => {
			if (res.confirm) {
				console.log('用户点击确定');
				this.clearCache();
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});
},

// 清除缓存
clearCache() {
	let os = plus.os.name;
	if (os == 'Android') {
		let main = plus.android.runtimeMainActivity();
		let sdRoot = main.getCacheDir();
		let files = plus.android.invoke(sdRoot, "listFiles");
		let len = files.length;
		for (let i = 0; i < len; i++) {
			let filePath = '' + files[i]; 
			plus.io.resolveLocalFileSystemURL(filePath, (entry) => {
				if (entry.isDirectory) {
					entry.removeRecursively((entry)  => { 
						uni.showToast({
							title: '缓存清理完成',
							duration: 2000
						});
						this.formatSize();  
					   }, (e) => {
					    console.log(e.message)
				    });
			    } else {
					entry.remove();
				}
			}, (e) => {
				console.log('文件路径读取失败')
			});
		}
	} else { // ios  
		plus.cache.clear(() =>{
			uni.showToast({
				title: '缓存清理完成',
				duration: 2000
			});
			this.formatSize();
		});
	}
}