In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how to use the Android storage access framework". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to use the Android storage access framework.
Storage access framework, referred to as: SAF, is the system file selector + file operation API. First select the file, and then use the file operation API to process the file. System file selector, just like the file selection box in Windows.
In fact, the vast majority of app will not use this thing, because it is too inconvenient. Pictures, videos, ordinary files, users need to look for folders, such a user experience is too poor. So everyone uses a third party or writes a file selector themselves.
The reason why we talk about SAF, first, is that after Android11, we cannot access non-multimedia files using MediaStore, so we need to rely on SAF. Second, the operation of wild cards and SD cards depends on the authorization of the storage access framework.
Open system file selector and file filtering Intent intent = new Intent (Intent.ACTION_OPEN_DOCUMENT); intent.addCategory (Intent.CATEGORY_OPENABLE); intent.setType ("application/*"); startActivityForResult (intent, REQUEST_CODE)
The value of setType is mime type, which can be "image/*", "* / *", where * is a wildcard. "image/*" code for all types of pictures. "* / *" represents all types of files.
You can use Intent.EXTRA_MIME_TYPES when you only need to open a few file types. At the same time setType is set to "* / *".
Intent intent = new Intent (Intent.ACTION_OPEN_DOCUMENT); intent.addCategory (Intent.CATEGORY_OPENABLE); intent.setType ("* / *") Intent.putExtra (Intent.EXTRA_MIME_TYPES, new String [] {"application/pdf", / / .pdf "application/vnd.oasis.opendocument.text", / / .odt "text/plain" / / .txt}); startActivityForResult (intent, REQUEST_CODE)
Intent.ACTION_PICK and ACTION_GET_CONTENT, you can also open the file selection box. ACTION_GET_CONTENT is broader and can be fetched from other types of content in addition to files.
Intent intent = new Intent (Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); intent.setType ("image/*"); Intent intent = new Intent (Intent.ACTION_GET_CONTENT); intent.setType ("image/*")
All the mime type are listed below:
Private static final String [] MIME_TYPES = new String [] [] {{"3gp", "video/3gpp"}, {"apk", "application/vnd.android.package-archive"}, {"asf", "video/x-ms-asf"}, {"avi", "video/x-msvideo"}, {"bin", "application/octet-stream"} {"bmp", "image/bmp"}, {"c", "text/plain"}, {"class", "application/octet-stream"}, {"conf", "text/plain"}, {"cpp", "text/plain"}, {"doc", "application/msword"}, {"docx" "application/vnd.openxmlformats-officedocument.wordprocessingml.document", {"xls", "application/vnd.ms-excel"}, {"xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}, {"exe", "application/octet-stream"}, {"gif", "image/gif"}, {"gtar", "application/x-gtar"} {"gz", "application/x-gzip"}, {"h", "text/plain"}, {"htm", "text/html"}, {"html", "text/html"}, {"jar", "application/java-archive"}, {"java", "text/plain"}, {"jpeg" "image/jpeg"}, {"jpg", "image/jpeg"}, {"js", "application/x-JavaScript"}, {"log", "text/plain"}, {"m3u", "audio/x-mpegurl"}, {"M4a", "audio/mp4a-latm"}, {"M4b", "audio/mp4a-latm"} {"m4p", "audio/mp4a-latm"}, {"ape", "audio/ape"}, {"flac", "audio/flac"}, {"m4u", "video/vnd.mpegurl"}, {"m4v", "video/x-m4v"}, {"mov", "video/quicktime"}, {"mp2" "audio/x-mpeg", {"mp3", "audio/x-mpeg"}, {"mp4", "video/mp4"}, {"mkv", "video/x-matroska"}, {"flv", "video/x-flv"}, {"divx", "video/x-divx"}, {"mpa", "video/mpeg"} {"mpc", "application/vnd.mpohun.certificate"}, {"mpe", "video/mpeg"}, {"mpeg", "video/mpeg"}, {"mpg", "video/mpeg"}, {"mpg4", "video/mp4"}, {"mpga", "audio/mpeg"}, {"msg" "application/vnd.ms-outlook", {"ogg", "audio/ogg"}, {"pdf", "application/pdf"}, {"png", "image/png"}, {"pps", "application/vnd.ms-powerpoint"}, {"ppt", "application/vnd.ms-powerpoint"}, {"pptx" "application/vnd.openxmlformats-officedocument.presentationml.presentation", {"prop", "text/plain"}, {"rc", "text/plain"}, {"rmvb", "audio/x-pn-realaudio"}, {"rtf", "application/rtf"}, {"sh", "text/plain"}, {"tar" "application/x-tar", {"tgz", "application/x-compressed"}, {"txt", "text/plain"}, {"wav", "audio/x-wav"}, {"wma", "audio/x-ms-wma"}, {"wmv", "audio/x-ms-wmv"}, {"wps" "application/vnd.ms-works"}, {"xml", "text/plain"}, {"z", "application/x-compress"}, {"zip", "application/x-zip-compressed"}, {"rar", "application/x-rar"}, {"", "* / *"}} Open the specified folder
With DocumentsContract.EXTRA_INITIAL_URI, when you open the file selector, jump to the specified folder. Only android 8 or above is fine.
Uri uri = Uri.parse ("content://com.android.externalstorage.documents/document/primary:Download"); Intent intent = new Intent (Intent.ACTION_OPEN_DOCUMENT); intent.addCategory (Intent.CATEGORY_OPENABLE); intent.setType ("* / *"); intent.putExtra (DocumentsContract.EXTRA_INITIAL_URI, uri); startActivityForResult (intent, 1); folder permission application
When you need to read files in a non-public folder, you can apply for authorization, save Uri after authorization, and then splice all the files in this Uri operation folder.
Especially for SD cards, the modification and deletion of files starting from Android 5 must be authorized first and can only be operated through the interface of the SVF framework.
You can use EXTRA_INITIAL_URI to open the specified folder and let the user authorize
Intent intent = new Intent (Intent.ACTION_OPEN_DOCUMENT_TREE); Uri uri = Uri.parse ("content://com.android.externalstorage.documents/document/primary:Download"); intent.putExtra (DocumentsContract.EXTRA_INITIAL_URI, uri); startActivityForResult (intent)
It should be noted that after Android 11, access to the storage root directory cannot be authorized, and neither can the two folders of Download/,Android/,.
Create a folder
There are two situations in which you can create a folder. One is under an authorized folder and you can use the SVF framework API.
DocumentsContract.createDocument ()
The other is created under an unauthorized folder, so you can specify the type and name directly and create it by clicking the system selection box.
Intent intent = new Intent (Intent.ACTION_CREATE_DOCUMENT); intent.addCategory (Intent.CATEGORY_OPENABLE); intent.setType ("application/txt"); intent.putExtra (Intent.EXTRA_TITLE, "testfile.txt"); startActivityForResult (intent) Storage access Framework API
API, the storage access framework, is all in DocumentsContract. Typical examples are:
Public static @ Nullable Uri renameDocument (@ NonNull ContentResolver content, @ NonNull Uri documentUri, @ NonNull String displayName) throws FileNotFoundException {} / * * Delete the given document. * * @ param documentUri document with {@ link Document#FLAG_SUPPORTS_DELETE} * @ return if the document was deleted successfully * / public static boolean deleteDocument (@ NonNull ContentResolver content, @ NonNull Uri documentUri) throws FileNotFoundException {} / * * Copies the given document. * * @ param sourceDocumentUri document with {@ link Document#FLAG_SUPPORTS_COPY} * @ param targetParentDocumentUri document which will become a parent of the source * document's copy. * @ return the copied document, or {@ code null} if failed. * / public static @ Nullable Uri copyDocument (@ NonNull ContentResolver content, @ NonNull Uri sourceDocumentUri, @ NonNull Uri targetParentDocumentUri) throws FileNotFoundException {} / * * Moves the given document under a new parent. * * @ param sourceDocumentUri document with {@ link Document#FLAG_SUPPORTS_MOVE} * @ param sourceParentDocumentUri parent document of the document to move * @ param targetParentDocumentUri document which will become a new parent of the source * document. * @ return the moved document, or {@ code null} if failed. * / public static @ Nullable Uri moveDocument (@ NonNull ContentResolver content, @ NonNull Uri sourceDocumentUri, @ NonNull Uri sourceParentDocumentUri, @ NonNull Uri targetParentDocumentUri) throws FileNotFoundException {} / * * Removes the given document from a parent directory. * *
In contrast to {@ link # deleteDocument} it requires specifying the parent. * This method is especially useful if the document can be in multiple parents. * * @ param documentUri document with {@ link Document#FLAG_SUPPORTS_REMOVE} * @ param parentDocumentUri parent document of the document to remove * @ return true if the document was removed successfully. * / public static boolean removeDocument (@ NonNull ContentResolver content, @ NonNull Uri documentUri, @ NonNull Uri parentDocumentUri) throws FileNotFoundException {} get folder files
Use the DocumentFile class to get a list of files in the folder.
Private ActivityResultLauncher openFile () {Intent intent = new Intent (Intent.ACTION_OPEN_DOCUMENT_TREE); Uri uri = Uri.parse ("content://com.android.externalstorage.documents/document/primary:AuthSDK"); intent.putExtra (DocumentsContract.EXTRA_INITIAL_URI, uri) Return startActivityForResult (intent, new ActivityResultCallback () {@ Override public void onActivityResult (Intent result) {for (DocumentFile documentFile: DocumentFile.fromTreeUri (BaseApplication.getInstance (). GetApplicationContext (), Uri.parse (result.getData (). ToString ()). ListFiles ()) {Log.i (", documentFile.getUri ()) });}
The following code demonstrates using SVF to read the contents of the file, write the contents, and query the file properties through MediaStore.
Private ActivityResultLauncher openFile () {Intent intent = new Intent (Intent.ACTION_OPEN_DOCUMENT_TREE); Uri uri = Uri.parse ("content://com.android.externalstorage.documents/document/primary:AuthSDK"); intent.putExtra (DocumentsContract.EXTRA_INITIAL_URI, uri) Return startActivityForResult (intent, new ActivityResultCallback () {@ Override public void onActivityResult (Intent result) {for (DocumentFile documentFile: DocumentFile.fromTreeUri (BaseApplication.getInstance (). GetApplicationContext (), Uri.parse (result.getData (). ToString ()). ListFiles ()) {try {InputStream inputStream = BaseApplication.getInstance (). GetContentResolver (). OpenInputStream (documentFile.getUri ()) Byte [] readData = new byte [1024]; inputStream.read (readData); OutputStream outputStream = BaseApplication.getInstance (). GetContentResolver (). OpenOutputStream (documentFile.getUri ()); byte [] writeData = "alan gong" .getBytes (StandardCharsets.UTF_8); outputStream.write (writeData, 0,9) OutputStream.close (); if (Build.VERSION.SDK_INT > = Build.VERSION_CODES.Q) {Uri mediaUri = MediaStore.getMediaUri (BaseApplication.getInstance (). GetApplicationContext (), documentFile.getUri ()); long fileId = ContentUris.parseId (mediaUri) Cursor query = BaseApplication.getInstance (). GetContentResolver (). Query (documentFile.getUri (), null, MediaStore.MediaColumns._ID + "=" + fileId, null, null); int columnIndex = query.getColumnIndexOrThrow (MediaStore.MediaColumns.MIME_TYPE); String mimeType = query.getString (columnIndex) Log.i (",");}} catch (FileNotFoundException e) {e.printStackTrace ();} catch (IOException e) {e.printStackTrace () });}
Use MediaStore.getMediaUri (documentUri) to convert, MediaStore Uri and Document Uri. Through the database id in MediaStore Uri, you can query all the properties of the file.
MediaStore Uri:content://media/external_primary/file/101750
Document Uri: content://com.android.externalstorage.documents/tree/primary%3AAuthSDK
In addition,
If File API cannot be used in a non-public directory, the permission of READ_EXTRNAL_PERMISSION will be given even if it is authorized by SVF. FileNotFoundException will still be thrown and permission deny will be displayed.
Different from MediaStore API.
The difference between the storage access framework API and MediaStore API is that the storage access framework API is based on the system file selection box. If the user selects the file, it is equivalent to authorization and can access all types of files. The characteristic of MediaStore is that it can query all files, but after opening partition storage, it can only check and deal with multimedia files, and other types of files are not allowed.
Thank you for reading, the above is the content of "how to use the Android storage access framework". After the study of this article, I believe you have a deeper understanding of how to use the Android storage access framework, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 233
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.