
本文旨在指导开发者如何在Android中工作 Scoped 在Storage环境中使用Storage Access Framework (SAF) 阅读外部存储特定文件夹中的文件。我们将提供详细的代码示例和步骤,帮助您了解SAF的工作原理,并安全有效地访问所需的文件。
Android 10 (API level 29) Scoped介绍在更高的版本中 Storage,旨在提高用户隐私和数据安全性。Scoped Storage限制了应用程序直接访问外部存储的能力。应用程序只能访问其特定的应用程序目录和用户通过系统文件选择器授予访问权限的目录。在Scoped 在Storage环境中访问外部存储,我们需要使用Storage Access Framework (SAF)。
Storage Access Framework (SAF) 概述SAF允许用户选择一个目录,并授权应用程序访问该目录及其子目录。用户授权后,应用程序可以在不需要READ_的情况下读取和写入该目录的文件EXTERNAL_STORAGE 或 WRITE_EXTERNAL_STORAGE 权限。
实现步骤以下步骤显示了如何使用SAF读取特定文件夹中的文件:
- 请求用户选择目录: ACTION_使用ACTION_OPEN_DOCUMENT_TREE Intent启动系统文件选择器,让用户选择需要访问的目录。
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.storage.StorageManager;
import android.util.Log;
public class Check {
Context context;
private String TAG="SOMNATH";
public Check(Context context) {
this.context = context;
}
public boolean ch(){
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
StorageManager sm = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
Intent intent = sm.getPrimaryStorageVolume().createOpenDocumentTreeIntent();
//String startDir = "Android";
//String startDir = "Download"; // Not choosable on an Android 11 device
//String startDir = "DCIM";
//String startDir = "DCIM/Camera"; // replace "/", "%2F"
//String startDir = "DCIM%2FCamera";
String startDir = "Documents";
Uri uri = intent.getParcelableExtra("android.provider.extra.INITIAL_URI");
String scheme = uri.toString();
Log.d(TAG, "INITIAL_URI scheme: " + scheme);
scheme = scheme.replace("/root/", "/document/");
scheme += "%3A" + startDir;
uri = Uri.parse(scheme);
intent.putExtra("android.provider.extra.INITIAL_URI", uri);
Log.d(TAG, "uri: " + uri.toString());
((Activity) context).startActivityForResult(intent, 12123);
return true;
}
else{
return false;
}
}
}
- ActivityResult处理: 在onactivityResult方法中,接收用户选择的目录URI,并持续存储URI。
package com.axanor.saf_sample
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.provider.DocumentsContract
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.documentfile.provider.DocumentFile
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
class StorageAccess {
val activity:Activity;
val LOGTAG = "SOMNATH"
val REQUEST_CODE = 12123
constructor(activity: Activity) {
this.activity = activity
}
public fun openDocumentTree() {
val check = Check(activity)
val uriString = SpUtil.getString(SpUtil.FOLDER_URI, "")
when {
uriString == "" -> {
Log.w(LOGTAG, "uri not stored")
if (!check.ch()){
askPermission()
}
}
arePermissionsGranted(uriString) -> {
makeDoc(Uri.parse(uriString))
}
else -> {
Log.w(LOGTAG, "uri permission not stored")
if (!check.ch()){
askPermission()
}
}
}
}
// this will present the user with folder browser to select a folder for our data
public fun askPermission() {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
activity.startActivityForResult(intent, REQUEST_CODE)
}
public fun makeDoc(dirUri: Uri) {
val dir = DocumentFile.fromTreeUri(activity, dirUri)
if (dir == null || !dir.exists()) {
//the folder was probably deleted
Log.e(LOGTAG, "no Dir")
//according to Commonsware blog, the number of persisted uri permissions is limited
//so we should release those we cannot use anymore
//https://commonsware.com/blog/2020/06/13/count-your-saf-uri-permission-grants.html
releasePermissions(dirUri)
//ask user to choose another folder
Toast.makeText(activity,"Folder deleted, please choose another!", Toast.LENGTH_SHORT).show()
openDocumentTree()
} else {
val file = dir.createFile("*/txt", "test.txt")
if (file != null && file.canWrite()) {
Log.d(LOGTAG, "file.uri = ${file.uri.toString()}")
alterDocument(file.uri)
} else {
Log.d(LOGTAG, "no file or cannot write")
//consider showing some more appropriate error message
Toast.makeText(activity,"Write error!", Toast.LENGTH_SHORT).show()
}
}
}
public fun releasePermissions(uri: Uri) {
val flags: Int = Intent.FLAG_GRANT_READ_URI_PERMISSION or
Intent.FLAG_GRANT_WRITE_URI_PERMISSION
activity.contentResolver.releasePersistableUriPermission(uri,flags)
//we should remove this uri from our shared prefs, so we can start over again next time
SpUtil.storeString(SpUtil.FOLDER_URI, "")
}
//Just a test function to write something into a file, from https://developer.android.com
//Please note, that all file IO MUST be done on a background thread. It is not so in this
//sample - for the sake of brevity.
public fun alterDocument(uri: Uri) {
try {
activity.contentResolver.openFileDescriptor(uri, "w")?.use { parcelFileDescriptor ->
FileOutputStream(parcelFileDescriptor.fileDescriptor).use {
it.write(
("String written at ${System.currentTimeMillis()}\n")
.toByteArray()
)
Toast.makeText(activity,"File Write OK!", Toast.LENGTH_SHORT).show()
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "application/pdf"
// Optionally, specify a URI for the file that should appear in the
// system file picker when it loads.
// Optionally, specify a URI for the file that should appear in the
// system file picker when it loads.
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, uri)
activity.startActivityForResult(intent, 2)
}
}
} catch (e: FileNotFoundException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
}
public fun arePermissionsGranted(uriString: String): Boolean {
// list of all persisted permissions for our app
val list = activity.contentResolver.persistedUriPermissions
for (i in list.indices) {
val persistedUriString = list[i].uri.toString()
//Log.d(LOGTAG, "comparing $persistedUriString and $uriString")
if (persistedUriString == uriString && list[i].isWritePermission && list[i].isReadPermission) {
//Log.d(LOGTAG, "permission ok")
return true
}
}
return false
}
}
StorageAccess access = new StorageAccess(this); access.openDocumentTree();
- 使用DocumentFile访问文件: 使用DocumentFile.fromTreeUri()方法从目录URI创建DocumentFile对象。然后,可以使用DocumentFile对象遍历目录中的文件和子目录。
public fun makeDoc(dirUri: Uri) {
val dir = DocumentFile.fromTreeUri(activity, dirUri)
if (dir == null || !dir.exists()) {
//the folder was probably deleted
Log.e(LOGTAG, "no Dir")
//according to Commonsware blog, the number of persisted uri permissions is limited
//so we should release those we cannot use anymore
//https://commonsware.com/blog/2020/06/13/count-your-saf-uri-permission-grants.html
releasePermissions(dirUri)
//ask user to choose another folder
Toast.makeText(activity,"Folder deleted, please choose another!", Toast.LENGTH_SHORT).show()
openDocumentTree()
} else {
val file = dir.createFile("*/txt", "test.txt")
if (file != null && file.canWrite()) {
Log.d(LOGTAG, "file.uri = ${file.uri.toString()}")
alterDocument(file.uri)
} else {
Log.d(LOGTAG, "no file or cannot write")
//consider showing some more appropriate error message
Toast.makeText(activity,"Write error!", Toast.LENGTH_SHORT).show()
}
}
}
- 检查权限: 在使用SAF访问文件之前,始终检查应用程序是否有权访问该文件。ArePermisionsgranted方法可用于检查URI权限是否已授予。
public fun arePermissionsGranted(uriString: String): Boolean {
// list of all persisted permissions for our app
val list = activity.contentResolver.persistedUriPermissions
for (i in list.indices) {
val persistedUriString = list[i].uri.toString()
//Log.d(LOGTAG, "comparing $persistedUriString and $uriString")
if (persistedUriString == uriString && list[i].isWritePermission && list[i].isReadPermission) {
//Log.d(LOGTAG, "permission ok")
return true
}
}
return false
}注意事项
- 用户体验: 尽可能清楚地向用户解释为什么您的应用程序需要访问特定的外部存储目录。
- 权限管理: 对用户授予的目录访问权限进行妥善管理。若不再需要访问某一目录,请释放相应的权限。
- 错误处理: 处理用户拒绝授权、目录不存在等可能出现的异常。
- 性能: 避免在主线程中执行耗时文件操作。
使用Storage Access Framework (SAF),你可以在Android中安全高效地工作 Scoped 访问Storage环境中外部存储的特定文件夹。请记住,尊重用户隐私是非常重要的。始终以用户为中心设计您的应用程序。本教程提供了一个基本框架,您可以根据自己的需要进行扩展和定制。
以上是Android Scoped Storage: 如何阅读存储特定文件夹的外部文件的详细信息,请更多地关注图灵教育的其他相关文章!