解决方案Harmony获取内存大小和Android类似的系统。
SystemMemoryInfo systemMemoryInfo = new SystemMemoryInfo();
IAbilityManager iAbilityManager = getAbilityManager();
iAbilityManager.getSystemMemoryInfo(systemMemoryInfo);
systemMemoryInfo.getTotalSysMem(); // 系统内存大小
systemMemoryInfo.getAvailSysMem(); // 可用内存大小
完整示例创建一个名为 SystemMemoryInfo 的 Java 语言项目。修改 MainAbilitySlice
代码如下:
package com.waylau.hmos.systemmemoryinfo.slice;
import com.waylau.hmos.systemmemoryinfo.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.SystemMemoryInfo;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Text;
import ohos.app.IAbilityManager;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
public class MainAbilitySlice extends AbilitySlice {
private static final String TAG = MainAbilitySlice.class.getSimpleName();
private static final HiLogLabel LABEL_LOG =
new HiLogLabel(HiLog.LOG_APP, 0x00001, TAG);
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
// 添加点击事件来触发请求
Text text = (Text) findComponentById(ResourceTable.Id_text_helloworld);
text.setClickedListener(listener -> this.printSystemMemoryInfo());
}
// 打印内存信息
private void printSystemMemoryInfo() {
HiLog.info(LABEL_LOG, "Before printSystemMemoryInfo");
SystemMemoryInfo systemMemoryInfo = new SystemMemoryInfo();
IAbilityManager iAbilityManager = getAbilityManager();
iAbilityManager.getSystemMemoryInfo(systemMemoryInfo);
HiLog.info(LABEL_LOG, "TotalSysMem: %{public}s B", systemMemoryInfo.getTotalSysMem() );
HiLog.info(LABEL_LOG, "AvailSysMem: %{public}s B", systemMemoryInfo.getAvailSysMem() );
HiLog.info(LABEL_LOG, "After printSystemMemoryInfo");
}
@Override
public void onActive() {
super.onActive();
}
@Override
public void onForeground(Intent intent) {
super.onForeground(intent);
}
}
上述代码
- 默认对生成文本设置Id_text_设置点击事件,点击调用打印世界的方法信息。
- printSystemMemoryInfo方法使用SystemMemoryInfo、来获取IAbilityManager系统内存大小、可用内存。
运行运行应用程序,界面显示如下。点击此处的“Hello World”,触发点击事件。
此时,界面切换到了搜索界面,如下。
日志输入如下:
10-19 17:26:31.555 9566-9566/com.waylau.hmos.systemmemoryinfo I 00001/MainAbilitySlice:在 printSystemMemoryInfo 之前
10-19 17:26:31.556 9566-9566/com.waylau.hmos.systemmemoryinfo I 00001/MainAbilitySlice: TotalSysMem: 8363315200 B
10-19 17:26:31.556 9566-9566/com.waylau.hmos.systemmemoryinfo I 00001/MainAbilitySlice: AvailSysMem: 6595653632 B
10-19 17:26:31.556 9566-9566/com.waylau.hmos.systemmemoryinfo I 00001/MainAbilitySlice:在 printSystemMemoryInfo