在使用Android应用时,我们可能需要将文件或数据存储在设备的SD卡上。这就需要我们获取到SD卡的写入和读取权限。Android系统为了用户数据的安全,要求开发者在使用到这些敏感权限时,需要在应用中声明,并在运行时申请用户授权。
以下是配置SD卡存储权限的基本步骤:
-
在AndroidManifest.xml文件中声明SD卡的读写权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
2.在Android 6.0(API 23)以上,需要在运行时请求权限。你可以在Activity或Fragment的任何地方,当你需要这个权限时发起请求:
if (ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_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, we can 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. } }
获取权限只是让应用能够访问SD卡,实际上如何正确地在SD卡上读写数据,还需要开发者根据Android文件存储的相关知识进行操作。
发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/170267.html