如何申请设备上的媒体读写权限?

如何申请设备上的媒体读写权限

阅读 618
avatarAI BotBETA

在Android设备上申请媒体读写权限,首先需要在你的AndroidManifest.xml文件中添加以下权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

然后,在运行时向用户请求这些权限。这通常在Activity的onCreate()方法中完成,如下所示:

if (ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
    // Permission is not granted
    // Should we show an explanation?
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        // Show an explanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.
    } else {
        // No explanation needed; request the permission
        ActivityCompat.requestPermissions(thisActivity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);

        // MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE is an
        // app-defined int constant. The callback method gets the
        // result of the request.
    }
} else {
    // Permission has already been granted
}

当用户授予或拒绝权限后,系统会回调Activity的onRequestPermissionsResult()方法。在这个方法中,你可以检查是否已获得权限,如果获得权限,则继续执行需要这些权限的操作。如果用户拒绝权限,你可以选择引导用户去设置页面手动开启权限。

注意:从Android 6.0(API 级别 23)开始,需要在运行时请求动态权限。在Android 10(API 级别 29)及更高版本中,所有应用默认都具有READ_EXTERNAL_STORAGE和WRITE_EXTERNAL_STORAGE权限。这意味着,如果你的应用针对的是Android 10或更高版本,那么不需要请求这些权限,但仍然需要在AndroidManifest.xml文件中声明它们。

1 个回答

解决措施

步骤 1

在module.json5配置文件中配置媒体读写权限ohos.permission.READ_MEDIA和ohos.permission.WRITE_MEDIA。

{ 
  "module" : {  
    "requestPermissions":[ 
      { 
        "name" : "ohos.permission.READ_MEDIA", 
        "reason": "$string:reason" 
      }, 
      { 
        "name" : "ohos.permission.WRITE_MEDIA", 
        "reason": "$string:reason" 
      } 
    ] 
  }
}

步骤 2

这两个权限的授权方式均为user_grant,因此需要调用requestPermissionsFromUser接口,以动态弹窗的方式向用户申请授权。

import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl'; 
import {BusinessError} from '@ohos.base'; 
import common from '@ohos.app.ability.common'; 
 
let context = getContext(this) as common.UIAbilityContext; 
let atManager = abilityAccessCtrl.createAtManager(); 
let permissions: Array<Permissions> = ['ohos.permission.READ_MEDIA','ohos.permission.WRITE_MEDIA']; 
atManager.requestPermissionsFromUser(context, permissions) 
  .then((data) => { 
    console.log("Succeed to request permission from user with data: " + JSON.stringify(data)); 
  }).catch((error: BusinessError) => { 
    console.log("Failed to request permission from user with error: " + JSON.stringify(error)); 
})

----结束

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进