HarmonyOS鸿蒙Next中导致AAP卡顿和闪退的难题,请高手帮忙查看分析一下原因。我试了N种办法都无法解决,现在请教一下专业人士的建议???

HarmonyOS鸿蒙Next中导致AAP卡顿和闪退的难题,请高手帮忙查看分析一下原因。我试了N种办法都无法解决,现在请教一下专业人士的建议??? 导致AAP卡顿和闪退的难题,请高手帮忙查看分析一下原因。我试了N种办法都无法解决,现在请教一下专业人士的建议???

代码我附在后面,请复制或者下载查看分析。代码可以运行,在真机上就会有卡顿和闪退的表现。1,代码主要实现更换背景和加载本地的图片来做背景,计数功能和保存记忆数字的功能,这一页的代码主要实现的就是这些功能没有其它复杂的。请大神帮忙找一下代码中BUG。万分的感谢!!!

import { promptAction, router } from '@kit.ArkUI';
import preferences from '@ohos.data.preferences';
import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs';
import { photoAccessHelper } from '@kit.MediaLibraryKit';

@Entry
@Component
struct Page09shiyong {
  private bgImages: Resource[] = [
    $r('app.media.taiyi01kaixin'),
    $r('app.media.taiyi02hua'),
    $r('app.media.taiyi03hua'),
    $r('app.media.taiyi04hua'),
    $r('app.media.nazha03'),
    $r('app.media.nazha04'),
    $r('app.media.nazha05'),
    $r('app.media.nazha06'),
    $r('app.media.taiyi06'),
    $r('app.media.taiyi07xiaoxiong')
  ];

  @State count: number = 0;
  @State currentCount: number = 1;
  @State historyCount: number = 0;
  @State historyData: string = '暂无历史数据';
  @State col1: string = '#333';
  @State col2: Color = Color.Yellow;
  @State currentBgColor: Color = Color.Transparent;
  @State localImagePath: string = '';
  @State currentImageIndex: number = 0;
  @State uris: string[] = [];
  @State photoCount: number = 0;
  @State customBgUris: string[] = [];
  @State showCustomBg: boolean = false;

  private pref: preferences.Preferences | null = null;
  private prefKey: string = 'countHistory';
  private countKey: string = 'totalCount';
  private bgIndexKey: string = 'currentBgIndex';
  private prefName: string = 'page09CounterData';
  private historyCountKey: string = 'totalHistoryCount';
  private customBgKey: string = 'customBackgrounds';

  aboutToAppear() {
    this.loadData();
  }

  build() {
    Column() {
      Column() {
        Row() {
          Button("Back")
            .onClick(() => router.pushUrl({  url: "pages/mulu" }))
            .fontSize(20)
            .height('30');

          Text(`功课累计:`)
            .fontSize(20)
            .fontColor(Color.Blue)
            .margin(10);

          Blank(15);

          Text('清零   ')
            .fontSize(20)
            .margin({ top: 1 })
            .height('30')
            .onClick(() => {
              promptAction.showDialog({
                message: '即将清除全部数据,是否继续?',
                buttons: [
                  { text: '取消', color: '#999999' },
                  { text: '确定', color: '#007DFF' }
                ]
              }).then(result => {
                if (result.index === 1) {
                  this.count = 0;
                  this.currentCount = 0;
                  this.historyCount = 0;
                  this.saveData();
                }
              });
            });
        }
        .padding(2)
        .backgroundColor('#eee')
        .width('90%')
        .height('50');

        Column() {
          Text(`◎: ${this.currentCount + this.count + this.historyCount}`)
            .fontSize(20)
            .fontColor(Color.Blue)
            .margin(10);
        }

        Column() {
          Row() {
            Column() {
              Stack({ alignContent: Alignment.TopStart }) {
                if (this.showCustomBg && this.localImagePath)  {
                  Image(this.localImagePath)
                    .width('100%')
                    .height('100%')
                    .objectFit(ImageFit.Cover)
                    .onComplete(() => {
                      console.log(' 图片加载成功');
                    })
                    .onError(() => {
                      console.error(' 图片加载失败');
                      this.showCustomBg = false;
                    });
                } else {
                  Image(this.bgImages[this.currentImageIndex])
                    .width('100%')
                    .height('100%')
                    .objectFit(ImageFit.Cover);
                }

                Column() {
                  Text(`${this.count}`)
                    .fontSize(60)
                    .margin({ left: 25, top: 5, bottom: 5 })
                    .height('100%')
                    .fontColor(this.col1)
                    .zIndex(1);
                }.width('100%')
              }
              .onClick(() => {
                this.count++;
                this.saveData();
              })
              .width('100%')
            }
            .width('100%')
            .height('80%');
          }
          .width('100%')
          .borderRadius(20);

          Row() {
            Column() {
              Row() {
                Text('换背景')
                  .margin({ left: 5, top: 5, bottom: 5 })
                  .textShadow({ radius: 2, color: Color.Black, offsetX: 1, offsetY: 1 })
                  .fontSize(15)
                  .fontColor(Color.Green)
                  .onClick(() => {
                    this.currentImageIndex = (this.currentImageIndex + 1) % this.bgImages.length;
                    this.showCustomBg = false;
                    this.saveData();
                  });

                Text('自定义')
                  .margin({ left: 10, top: 5, bottom: 5 })
                  .textShadow({ radius: 2, color: Color.Black, offsetX: 1, offsetY: 1 })
                  .fontSize(15)
                  .fontColor(Color.Green)
                  .onClick(() => {
                    this.getFileAssetsFromType();
                  });
              }
            }

            Text('   查看详情')
              .onClick(() => router.pushUrl({  url: "pages/mulu" }))
          }
          .margin({ left: 25, top: 5, bottom: 5 })
          .width('100%');
        }
        .width('100%')
        .height('100%');
      }
      .width('100%');

      Column() {
        Text(`当前图片索引: ${this.currentImageIndex}`)
          .fontSize(24)
          .margin({ top: 20 });
      }
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
    .alignItems(HorizontalAlign.Center);
  }

  // 统一图片选择方法
  async getFileAssetsFromType() {
    const photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
    photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
    photoSelectOptions.maxSelectNumber  = 1;

    const photoViewPicker = new photoAccessHelper.PhotoViewPicker();
    try {
      const photoSelectResult = await photoViewPicker.select(photoSelectOptions);
      this.uris  = photoSelectResult.photoUris;
      this.photoCount  = this.uris.length;

      if (this.photoCount  > 0) {
        await this.addCustomBackground(this.uris[0]);
      }
    } catch (err) {
      console.error(' 选择图片失败:', err);
      promptAction.showToast({  message: '选择图片失败,请重试', duration: 2000 });
    }
  }

  // 添加自定义背景
  async addCustomBackground(uri: string) {
    try {
      const context = getContext(this) as common.UIAbilityContext;
      const filesDir = context.filesDir;

      // 确保目录存在
      if (!fs.accessSync(filesDir))  {
        fs.mkdirSync(filesDir);
      }

      const destFileName = `custom_bg_${Date.now()}.jpg`;
      const destPath = `${filesDir}/${destFileName}`;

      // 复制文件到应用目录
      const file = await fs.open(uri,  fs.OpenMode.READ_ONLY);
      await fs.copyFile(file.fd,  destPath);
      await fs.close(file.fd);

      // 更新状态
      this.localImagePath  = destPath;
      this.showCustomBg  = true;

      // 保存自定义背景路径
      this.customBgUris  = [...this.customBgUris,  destPath];
      await this.saveData();

      promptAction.showToast({  message: '背景设置成功', duration: 2000 });
    } catch (err) {
      console.error(' 处理图片失败:', err);
      promptAction.showToast({  message: '设置背景失败', duration: 2000 });
    }
  }

  private async loadData() {
    try {
      const context = getContext(this) as common.UIAbilityContext;
      this.pref  = await preferences.getPreferences(context,  this.prefName);

      // 加载计数数据
      this.currentCount  = (await this.pref.get(this.countKey,  1)) as number;
      this.count  = (await this.pref.get('currentCount',  0)) as number;
      this.historyCount  = (await this.pref.get(this.historyCountKey,  0)) as number;
      this.currentImageIndex  = (await this.pref.get(this.bgIndexKey,  0)) as number;

      // 加载自定义背景
      const savedBgUris = await this.pref.get(this.customBgKey,  '[]');
      this.customBgUris  = JSON.parse(savedBgUris  as string) as string[];

      if (this.customBgUris.length  > 0) {
        // 检查文件是否存在
        const lastBgPath = this.customBgUris[this.customBgUris.length  - 1];
        if (fs.accessSync(lastBgPath))  {
          this.localImagePath  = lastBgPath;
          this.showCustomBg  = true;
        } else {
          // 文件不存在,从列表中移除
          this.customBgUris.pop();
          await this.saveData();
        }
      }
    } catch (error) {
      console.error(' 加载数据失败', error);
    }
  }

  private async saveData() {
    if (!this.pref)  {
      const context = getContext(this) as common.UIAbilityContext;
      this.pref  = await preferences.getPreferences(context,  this.prefName);
    }

    try {
      // 保存计数数据
      await this.pref.put(this.countKey,  this.currentCount);
      await this.pref.put('currentCount',  this.count);
      await this.pref.put(this.historyCountKey,  this.historyCount);
      await this.pref.put(this.bgIndexKey,  this.currentImageIndex);

      // 保存自定义背景
      await this.pref.put(this.customBgKey,  JSON.stringify(this.customBgUris));

      await this.pref.flush();
    } catch (error) {
      console.error(' 保存数据失败', error);
    }
  }
}

更多关于HarmonyOS鸿蒙Next中导致AAP卡顿和闪退的难题,请高手帮忙查看分析一下原因。我试了N种办法都无法解决,现在请教一下专业人士的建议???的实战教程也可以访问 https://www.itying.com/category-93-b0.html

8 回复

您好,我使用您代码本地未复现,卡顿方面无明显体验问题,闪退未出现。

设备和软件信息如下:

  • 手机型号:Mate 60 Pro
  • 软件版本:5.0.1.120
  • 图片大小:66KB~3.5M之间,大部分是130KB~200KB内
  • IDE版本:Build Version: 5.0.13.200, built on May 13, 2025
  • API:API Version 17 Release

建议您使用DevEco Testing或者IDE里面的Profiler监控一下获取异常信息具体分析

更多关于HarmonyOS鸿蒙Next中导致AAP卡顿和闪退的难题,请高手帮忙查看分析一下原因。我试了N种办法都无法解决,现在请教一下专业人士的建议???的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


你在虚拟机上可能问题不大,代码是可以运行的。就是打包到工APP后,就会出现闪退的情况。如果你能用真机测试一下,可能才能发现问题。在虚拟机上发现不了这个问题,我也是被这个给搞得很烦恼,我怀疑,是不是加载图片的哪个代码出了什么问题,他加载的时候有一个什么找不到。

我贴出部分的日志出来。以供参考:

service E RsFrameReport:[loadSymbol]Get RSRenderEnd symbol failed: do_dlsym failed: Symbol not found: RSRenderEnd, version: null so=/system/lib64/platformsdk/libframe_ui_intf.z.so
04-28 18:22:40.285 798-833 C01400/OHOS::RS render_service E RsFrameReport:[RSRenderEnd]load RSRenderEnd function failed!
04-28 18:22:40.298 798-833 C01400/OHOS::RS render_service E RsFrameReport:[loadSymbol]Get RSRenderStart symbol failed: do_dlsym failed: Symbol not found: RSRenderStart, version: null so=/system/lib64/platformsdk/libframe_ui_intf.z.so
04-28 18:22:40.298 798-833 C01400/OHOS::RS render_service E RsFrameReport:[RSRenderStart]load RSRenderStart function failed!
04-28 18:22:40.300 493-878 C02510/DISP composer_host W [SetLayerMaskInfo:437] <private> is not supported
...

找HarmonyOS工作还需要会Flutter的哦,有需要Flutter教程的可以学学大地老师的教程,很不错,B站免费学的哦:BV1S4411E7LY/?p=17

崩溃日志,我上传成附件,希望有人能看得懂,找到原因。我是没有办法了,感谢各位大神。

我是使用真机,将附件“导致AAP卡顿和闪退的难题.txt”中的代码直接复制到一个空项目中,使用一个假的图片资源也没有复现,方便发一下您这边使用的图片资源吗,

闪退时App崩溃了么? 崩溃应该有个crash 的崩溃日志吧?

那里面应该有崩溃的原因.

鸿蒙Next中AAP卡顿和闪退可能由以下原因导致:

  1. 内存管理问题:检查是否存在内存泄漏或过度内存占用
  2. UI线程阻塞:确保耗时操作不在主线程执行
  3. 渲染性能:优化复杂UI布局,减少嵌套层级
  4. 异常处理:检查未捕获的异常或错误
  5. 第三方库兼容性:确认使用的库支持鸿蒙Next版本

建议使用DevEco Studio的Profiler工具分析性能瓶颈,查看日志定位具体异常。检查Ability生命周期管理是否正确。

从代码分析来看,可能导致卡顿和闪退的几个关键问题:

  1. 图片资源处理问题:
  • 加载大尺寸本地图片时未做压缩处理,可能导致内存溢出
  • 自定义背景图片路径处理不够健壮,当图片不存在时可能引发异常
  1. 文件操作问题:
  • 文件操作(fs模块)缺少完整的错误处理,特别是copyFileclose操作
  • 未检查文件权限,可能导致访问异常
  1. 内存管理问题:
  • 自定义背景图片URI数组(customBgUris)未做长度限制,可能积累大量数据
  • 图片资源切换时未释放前一张图片的内存
  1. 异步操作问题:
  • 部分异步操作缺少await,可能导致竞态条件
  • 文件操作和UI更新未做好同步

建议重点检查:

  1. 图片加载时的内存占用情况
  2. 文件操作时的错误日志
  3. 自定义背景切换时的资源释放
  4. 异步操作的执行顺序

这些因素都可能导致在真机上出现卡顿和闪退现象。

回到顶部