HarmonyOS 如何加载存储在 emulator/phone 存储中的本地 files/images?

How to load local files/images that are stored in emulator/phone storage in HarmonyOS?

我正在构建 HarmonyOS 应用程序并想加载我在 emulator/phone 存储中的图像。如何在我的 Java class 中加载此图像?

HarmonyOS加载系统镜像,可以通过以下方式获取镜像的绝对路径:

  1. 在 config.json 文件中配置以下权限:
"reqPermissions": [

 {

"name": "ohos.permission.READ_USER_STORAGE"

 },

 {

"name": "ohos.permission.WRITE_USER_STORAGE"

 },

 {

"name": "ohos.permission.GET_BUNDLE_INFO"

 }

]
  1. 手动请求 MainAbility.java 中的用户访问设备上的照片和媒体的权限:
public class MainAbility extends Ability {

   @Override

   public void onStart(Intent intent) {

       super.onStart(intent);

       super.setMainRoute(MainAbilitySlice.class.getName());

       requestPermission();

   }

   private void requestPermission() {

       String[] permissions = {

               "ohos.permission.READ_USER_STORAGE",

               "ohos.permission.WRITE_USER_STORAGE",

               "ohos.permission.DISTRIBUTED_DATASYNC"

       };

       List<String> applyPermissions = new ArrayList<>();

       for (String element : permissions) {

           if (verifySelfPermission(element) != IBundleManager.PERMISSION_GRANTED) {

               if (canRequestPermission(element)) {

                   applyPermissions.add(element);

               }

           }

       }

       requestPermissionsFromUser(applyPermissions.toArray(new String[0]), 0);

   }

}

3.TheMainAbilitySlice.java代码如下:

public class MainAbilitySlice extends AbilitySlice {

private static final HiLogLabel TAG = new HiLogLabel(3, 0xD001100, "MainAbilitySlice");

   @Override

   public void onStart(Intent intent) {

       super.onStart(intent);

       super.setUIContent(ResourceTable.Layout_ability_main);

     

       // Obtains the absolute path of the system image.

DataAbilityHelper helper = DataAbilityHelper.creator(this);

       ResultSet resultSet;

       try {

           resultSet = helper.query(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, new String[]

                   {AVStorage.Images.Media.ID, AVStorage.Images.Media.DISPLAY_NAME, AVStorage.Images.Media.DATA}, null);

           while (resultSet != null && resultSet.goToNextRow()) {

               // Obtains the absolute path of the image.

               String path = resultSet.getString(resultSet.getColumnIndexForName(AVStorage.Images.Media.DATA));

           }

       } catch (DataAbilityRemoteException e) {

           HiLog.error(TAG, "DataAbilityRemoteException e" + e);

       }

   }

   @Override

   public void onActive() {

       super.onActive();

   }

   @Override

   public void onForeground(Intent intent) {

       super.onForeground(intent);

   }

}