封装一个工具类,获取相册的权限,图片的信息,截图的列表,删除图片的方法。
import { Permissions } from '@kit.AbilityKit'
import { dataSharePredicates } from '@kit.ArkData'
import { promptAction } from '@kit.ArkUI'
import { photoAccessHelper } from '@kit.MediaLibraryKit'
import { permissionManager } from '../../manager'class CleanerManager {// 权限private permissions: Permissions[] = ["ohos.permission.READ_IMAGEVIDEO", "ohos.permission.WRITE_IMAGEVIDEO"]// 图片资源private photoAssets: photoAccessHelper.PhotoAsset[] = []// 图片字段private columns: photoAccessHelper.PhotoKeys[] = [photoAccessHelper.PhotoKeys.DATE_ADDED,//获取图片大小photoAccessHelper.PhotoKeys.SIZE,] // 图片权限async requestPermissions() {try {// 申请权限(结合前面封装的检测权限的工具类)await permissionManager.requestPermissions(this.permissions)} catch {// 未开启弹窗提示const dialogRes = await promptAction.showDialog({alignment: DialogAlignment.Center,title: '温馨提示',message: '手机瘦身功能需要获取权限,请在系统设置中打开相册开关',buttons: [{ text: '取消', color: $r('app.color.font_sub') },{ text: '立即开启', color: $r('app.color.brand') }]})// 打开设置页if (dialogRes.index === 1) {permissionManager.openPermissionSettingsPage()}}}// 获取图片/视频async getAssets() {const context = getContext()// 创建多媒体管理器const phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context) // 获取照片访问助手const predicates = new dataSharePredicates.DataSharePredicates() // 创建数据共享断言const fetchOption: photoAccessHelper.FetchOptions = {fetchColumns: this.columns,predicates: predicates}const assets = await phAccessHelper.getAssets(fetchOption) // 获取资源const photoAssets = await assets.getAllObjects() // 获取所有图片// this.photoAssets = photoAssets// phAccessHelper.release()return photoAssets}
// 获取屏幕截图列表async getScreenshotList() {const photoAssets = await this.getAssets()// 筛选出包含 screenshot 的图片//screenshot 截图文件都包含return photoAssets.filter((item) => item.displayName.includes('screenshot'))}// 获取视频列表async getVideoList() {const photoAssets = await this.getAssets()return photoAssets.filter((item) => item.photoType === photoAccessHelper.PhotoType.VIDEO)} // 删除图片async deletePhotos(uris: string[]) {const photoAssets = await this.getAssets()// 转换成 PhotoAsset 对象const deleteAssets = photoAssets.filter(v => uris.includes(v.uri))await photoAccessHelper.MediaAssetChangeRequest.deleteAssets(getContext(), deleteAssets)}
}export const cleanerManager = new CleanerManager()