Aprire i file utilizzando Storage Access Framework
Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Android 4.4 (livello API 19) introduce Storage Access Framework (SAF). SAF consente agli utenti di sfogliare e aprire documenti, immagini e altri file su tutti i loro fornitori di spazio di archiviazione dei documenti preferiti. Un'interfaccia utente standard e facile da usare consente agli utenti di sfogliare i file e accedere ai file recenti in modo coerente tra app e fornitori.
I servizi di archiviazione locale o cloud possono partecipare a questo ecosistema implementando un
DocumentsProvider che incapsula i loro servizi. Le app client che devono accedere ai documenti di un fornitore possono integrarsi con la piattaforma SAF con poche righe di codice.
Il SAF include quanto segue:
Fornitore di documenti:un fornitore di contenuti che consente a un servizio di archiviazione, come Google Drive, di mostrare i file che gestisce. Un fornitore di documenti viene implementato come sottoclasse della classe DocumentsProvider.
Lo schema del fornitore di documenti si basa su una gerarchia di file tradizionale, anche se la modalità di memorizzazione fisica dei dati da parte del fornitore di documenti dipende da te.
La piattaforma Android include diversi fornitori di documenti integrati, come Download, Immagini e Video.
Selettore:un'interfaccia utente di sistema che consente agli utenti di accedere ai documenti di tutti i fornitori di documenti che soddisfano i criteri di ricerca dell'app client.
SAF offre le seguenti funzionalità:
Consente agli utenti di sfogliare i contenuti di tutti i fornitori di documenti, non solo di una singola app.
Consente alla tua app di avere accesso permanente e a lungo termine ai documenti di proprietà di un fornitore di documenti. Tramite questo accesso, gli utenti possono aggiungere, modificare,
salvare ed eliminare file sul provider.
Supporta più account utente e origini temporanee come i fornitori di archiviazione USB, che vengono visualizzati solo se l'unità è collegata.
Panoramica
L'SAF si basa su un fornitore di contenuti che è una sottoclasse della classe DocumentsProvider. All'interno di un fornitore di documenti, i dati sono strutturati come una gerarchia di file tradizionale:
Figura 1. Modello di dati del fornitore di documenti. Un nodo principale rimanda a un singolo documento, che avvia la distribuzione dell'albero.
Nota:
Ogni fornitore di documenti segnala una o più radici, che sono i punti di partenza per esplorare un albero di documenti.
Ogni radice ha un COLUMN_ROOT_ID univoco e fa riferimento a un documento (una directory) che rappresenta i contenuti sotto quella radice.
Le radici sono dinamiche per impostazione predefinita per supportare casi d'uso come più account, dispositivi di archiviazione USB temporanei o accesso e uscita degli utenti.
Sotto ogni radice è presente un singolo documento. Il documento rimanda da 1 a N documenti, ciascuno dei quali a sua volta può fare riferimento da 1 a N documenti.
Ogni backend di archiviazione mostra singoli file e directory facendovi riferimento con un COLUMN_DOCUMENT_ID univoco.
Gli ID documento sono univoci e non cambiano una volta emessi, poiché vengono utilizzati per le autorizzazioni URI permanenti durante i riavvii del dispositivo.
I documenti possono essere un file apribile con un tipo MIME specifico o una directory contenente altri documenti con il tipo MIME MIME_TYPE_DIR.
Il modello di dati del provider di documenti si basa su una gerarchia di file tradizionale. Tuttavia, puoi memorizzare fisicamente i dati come preferisci, purché tu possa accedervi utilizzando l'DocumentsProvider
API. Ad esempio, puoi utilizzare lo spazio di archiviazione sul cloud basato su tag per i tuoi dati.
La Figura 2 mostra come un'app di foto potrebbe utilizzare SAF per accedere ai dati archiviati:
Figura 2. Flusso del framework Storage Access.
Nota:
In SAF, i fornitori e i clienti non interagiscono
direttamente. Un client richiede l'autorizzazione per interagire con i file, ovvero per leggerli, modificarli, crearli o eliminarli.
L'interazione inizia quando un'applicazione, in questo caso un'app di foto, attiva l'intentACTION_OPEN_DOCUMENT o ACTION_CREATE_DOCUMENT.
L'intent può includere filtri per perfezionare ulteriormente i criteri, ad esempio "dammi tutti i file aperti con il tipo MIME "immagine"".
Una volta attivato l'intent, il selettore di sistema si rivolge a ciascun fornitore registrato
e mostra all'utente le radici dei contenuti corrispondenti.
Il selettore offre agli utenti un'interfaccia standard per accedere ai documenti, anche quando i provider di documenti sottostanti sono molto diversi. Ad esempio, la figura 2 mostra un provider Google Drive, un provider USB e un provider cloud.
Nella Figura 3, l'utente seleziona la cartella Download da un selettore aperto durante la ricerca di immagini. Il selettore mostra anche tutte le radici disponibili per l'app client.
Figura 3. Selettore che mostra la cartella Download selezionata come posizione di ricerca.
Dopo che l'utente seleziona la cartella Download, vengono visualizzate le immagini. La Figura 4 mostra il risultato di questa procedura. Ora l'utente può interagire con le immagini
nel modo supportato dall'app del provider e del client.
Figura 4. Immagini memorizzate nella cartella Download, come visualizzate nel selettore di sistema.
Scrivere un'app client
Su Android 4.3 e versioni precedenti, se vuoi che la tua app recuperi un file da un'altra app, deve invocare un'intent come ACTION_PICK o ACTION_GET_CONTENT. L'utente seleziona quindi un'app singola da cui scegliere un file. L'app selezionata deve fornire un'interfaccia utente che consenta all'utente di sfogliare e scegliere tra i file disponibili.
Su Android 4.4 (livello API 19) e versioni successive, hai la possibilità aggiuntiva di utilizzare l'intent ACTION_OPEN_DOCUMENT, che mostra un'interfaccia utente del selettore controllata dal sistema che consente all'utente di sfogliare tutti i file resi disponibili da altre app. Da questa singola interfaccia utente, l'utente può scegliere un file da qualsiasi app supportata.
Su Android 5.0 (livello API 21) e versioni successive, puoi anche utilizzare l'intent ACTION_OPEN_DOCUMENT_TREE, che consente all'utente di scegliere una directory a cui un'app client può accedere.
Nota: ACTION_OPEN_DOCUMENT non sostituisce ACTION_GET_CONTENT.
Quello che utilizzi dipende dalle esigenze della tua app:
Utilizza ACTION_GET_CONTENT se vuoi che la tua app
legga o importi i dati. Con questo approccio, l'app importa una copia dei dati, come un file immagine.
Utilizza ACTION_OPEN_DOCUMENT se vuoi che la tua app abbia accesso permanente e a lungo termine ai documenti di proprietà di un fornitore di documenti. Un esempio è un'app di fotoritocco che consente agli utenti di modificare le immagini memorizzate in un provider di documenti.
Per ulteriori informazioni su come supportare la ricerca di file e directory utilizzando l'interfaccia utente del selettore di sistema, consulta la guida sull'accesso a documenti e altri file.
Risorse aggiuntive
Per ulteriori informazioni sui fornitori di documenti, consulta le seguenti risorse:
I campioni di contenuti e codice in questa pagina sono soggetti alle licenze descritte nella Licenza per i contenuti. Java e OpenJDK sono marchi o marchi registrati di Oracle e/o delle sue società consociate.
Ultimo aggiornamento 2025-07-27 UTC.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Mancano le informazioni di cui ho bisogno","missingTheInformationINeed","thumb-down"],["Troppo complicato/troppi passaggi","tooComplicatedTooManySteps","thumb-down"],["Obsoleti","outOfDate","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Problema relativo a esempi/codice","samplesCodeIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 2025-07-27 UTC."],[],[],null,["# Open files using the Storage Access Framework\n\nAndroid 4.4 (API level 19) introduces the Storage Access Framework (SAF). The SAF\nlets users browse and open documents, images, and other files\nacross all of their preferred document storage providers. A standard, easy-to-use UI\nlets users browse files and access recent files in a consistent way across apps and providers.\n\nCloud or local storage services can participate in this ecosystem by implementing a\n[DocumentsProvider](/reference/android/provider/DocumentsProvider) that encapsulates their services. Client\napps that need access to a provider's documents can integrate with the SAF with a few\nlines of code.\n\nThe SAF includes the following:\n\n- **Document provider:** a content provider that lets a storage service, such as Google Drive, reveal the files it manages. A document provider is implemented as a subclass of the [DocumentsProvider](/reference/android/provider/DocumentsProvider) class. The document-provider schema is based on a traditional file hierarchy, though how your document provider physically stores data is up to you. The Android platform includes several built-in document providers, such as Downloads, Images, and Videos.\n- **Client app:** a custom app that invokes the [ACTION_CREATE_DOCUMENT](/reference/android/content/Intent#ACTION_CREATE_DOCUMENT), [ACTION_OPEN_DOCUMENT](/reference/android/content/Intent#ACTION_OPEN_DOCUMENT), and [ACTION_OPEN_DOCUMENT_TREE](/reference/android/content/Intent#ACTION_OPEN_DOCUMENT_TREE) intent actions and receives the files returned by document providers.\n- **Picker:** a system UI that lets users access documents from all document providers that satisfy the client app's search criteria.\n\nSAF offers the following features:\n\n- Lets users browse content from all document providers, not just a single app.\n- Makes it possible for your app to have long-term, persistent access to documents owned by a document provider. Through this access, users can add, edit, save, and delete files on the provider.\n- Supports multiple user accounts and transient roots such as USB storage providers, which only appear if the drive is plugged in.\n\nOverview\n--------\n\nThe SAF centers around a content provider that is a\nsubclass of the [DocumentsProvider](/reference/android/provider/DocumentsProvider) class. Within a document provider, data is\nstructured as a traditional file hierarchy:\n**Figure 1.** Document provider data model. A root points to a single document, which then starts the fan-out of the tree.\n\nNote the following:\n\n- Each document provider reports one or more *roots* , which are starting points into exploring a tree of documents. Each root has a unique [COLUMN_ROOT_ID](/reference/android/provider/DocumentsContract.Root#COLUMN_ROOT_ID), and it points to a document (a directory) representing the contents under that root. Roots are dynamic by design to support use cases like multiple accounts, transient USB storage devices, or user login and logout.\n- Under each root is a single document. That document points to 1 to *N* documents, each of which in turn can point to 1 to *N* documents.\n- Each storage backend surfaces individual files and directories by referencing them with a unique [COLUMN_DOCUMENT_ID](/reference/android/provider/DocumentsContract.Document#COLUMN_DOCUMENT_ID). Document IDs are unique and don't change once issued, since they are used for persistent URI grants across device reboots.\n- Documents can be either an openable file, with a specific MIME type, or a directory containing additional documents, with the [MIME_TYPE_DIR](/reference/android/provider/DocumentsContract.Document#MIME_TYPE_DIR) MIME type.\n- Each document can have different capabilities, as described by [COLUMN_FLAGS](/reference/android/provider/DocumentsContract.Document#COLUMN_FLAGS). For example, [FLAG_SUPPORTS_WRITE](/reference/android/provider/DocumentsContract.Document#FLAG_SUPPORTS_WRITE), [FLAG_SUPPORTS_DELETE](/reference/android/provider/DocumentsContract.Document#FLAG_SUPPORTS_DELETE), and [FLAG_SUPPORTS_THUMBNAIL](/reference/android/provider/DocumentsContract.Document#FLAG_SUPPORTS_THUMBNAIL). The same `COLUMN_DOCUMENT_ID` can be included in multiple directories.\n\nControl flow\n------------\n\nThe document provider data model is based on a traditional\nfile hierarchy. However, you can physically store your data however you like, as\nlong as you can access it using the [DocumentsProvider](/reference/android/provider/DocumentsProvider)\nAPI. For example, you can use tag-based cloud storage for your data.\n\nFigure 2 shows how a photo app might use the SAF\nto access stored data:\n**Figure 2.** Storage Access Framework flow.\n\nNote the following:\n\n- In the SAF, providers and clients don't interact directly. A client requests permission to interact with files, meaning to read, edit, create, or delete files.\n- The interaction starts when an application, in this example a photo app, fires the intent [ACTION_OPEN_DOCUMENT](/reference/android/content/Intent#ACTION_OPEN_DOCUMENT) or [ACTION_CREATE_DOCUMENT](/reference/android/content/Intent#ACTION_CREATE_DOCUMENT). The intent can include filters to further refine the criteria, such as \"give me all openable files that have the 'image' MIME type.\"\n- Once the intent fires, the system picker goes to each registered provider and shows the user the matching content roots.\n- The picker gives users a standard interface for accessing documents, even when the underlying document providers are very different. For example, figure 2 shows a Google Drive provider, a USB provider, and a cloud provider.\n\nIn Figure 3, the user is selecting the Downloads folder from a picker opened in a search for\nimages. The picker also shows all of the roots available to the client app.\n**Figure 3.** Picker showing Downloads folder selected as a search location.\n\nAfter the user selects the Downloads folder, the images are displayed. Figure\n4 shows the result of this process. The user can now interact with the images\nin the ways that the provider and client app support.\n**Figure 4.** Images stored in the Downloads folder, as viewed in the system picker.\n\nWrite a client app\n------------------\n\nOn Android 4.3 and lower, if you want your app to retrieve a file from another\napp, it must invoke an intent such as [ACTION_PICK](/reference/android/content/Intent#ACTION_PICK)\nor [ACTION_GET_CONTENT](/reference/android/content/Intent#ACTION_GET_CONTENT). The user then selects\na single app from which to pick a file. The selected app must provide a user\ninterface for the user to browse and pick from the available files.\n\nOn Android 4.4 (API level 19) and higher, you have the additional option of using the\n[ACTION_OPEN_DOCUMENT](/reference/android/content/Intent#ACTION_OPEN_DOCUMENT) intent,\nwhich displays a system-controlled picker UI that lets the user\nbrowse all files that other apps have made available. From this single UI, the\nuser can pick a file from any of the supported apps.\n\nOn Android 5.0 (API level 21) and higher, you can also use the\n[ACTION_OPEN_DOCUMENT_TREE](/reference/android/content/Intent#ACTION_OPEN_DOCUMENT_TREE)\nintent, which lets the user choose a directory for a client app to\naccess. \n**Note:** `ACTION_OPEN_DOCUMENT` isn't a replacement for `ACTION_GET_CONTENT`.\nThe one you use depends on the needs of your app:\n\n- Use `ACTION_GET_CONTENT` if you want your app to read or import data. With this approach, the app imports a copy of the data, such as an image file.\n- Use `ACTION_OPEN_DOCUMENT` if you want your app to have long-term, persistent access to documents owned by a document provider. An example is a photo-editing app that lets users edit images stored in a document provider.\n\nFor more information about how to support browsing for files and directories\nusing the system picker UI, see the guide about\n[accessing documents and\nother files](/training/data-storage/shared/documents-files).\n\nAdditional resources\n--------------------\n\nFor more information about document providers, take advantage of the\nfollowing resources:\n\n### Samples\n\n- [StorageProvider](https://github.com/android/storage-samples/tree/main/StorageProvider)\n\n### Videos\n\n- [DevBytes: Android 4.4 Storage Access Framework: Provider](http://www.youtube.com/watch?v=zxHVeXbK1P4)\n- [Virtual Files in the Storage Access Framework](https://www.youtube.com/watch?v=4h7yCZt231Y)"]]