SAF: App Inventor implementation of Storage Access Framework

1.Introduction

Description: Basically AI2 wrapper of Storage Access Framework. Using this extension, you can get read and/or write access to a single document or tree document (and all of its children recursively).
Latest Version: 1.3
Released: 2021-09-16T18:30:00Z
Last Updated: 2023-11-15T18:30:00Z

2.Blocks

image


image


image


image


image


image


image
image


image

3.Documentation

Events

ErrorOccurredEvent indicating error/exception has occurred and returns origin method and error message.
methodName | text
errorMessage | text
DocumentCreatedEvent invoked after creating document.Returns document's uri if operation was successful else returns error message
uriString | text
GotWriteResultEvent invoked after writing to document.Returns document's uri if operation was successful else returns error message
response | text
GotReadResultEvent invoked after reading from document.Returns content if operation was successful else returns error message
result | any
GotUriEvent invoked when user selects a document or tree from SAF file picker
uri | any
uriString | text
GotFilesListEvent invoked after getting files list
filesList | list
GotCopyResultEvent invoked after getting copy document result.Response will be target document's uri if operation was successful else returns error message
successful | boolean
response | text
GotMoveResultEvent invoked after getting move document result.Response will be target document's uri if operation was successful else returns error message
successful | boolean
response | text
DocumentCopiedToFileEvent raised after getting 'CopyDocumentToFile' result
successful | boolean
response | text
DocumentCopiedFromFileEvent raised after getting 'CopyDocumentFromFile' result
successful | boolean
response | text

Methods

CreateFlagsCombines two flags and returns resulting flag
f1 | number
f2 | number
StringFromUriObjectConvert uri to string
uri | any
StringToUriObjectConverts string to uri
uriString | text
InitialDirReturns uri which can be used as Initial Dir in SAF picker
dir | text
OpenDocumentTreePrompts user to select a document tree
title | text
initialDir | text
OpenSingleDocumentPrompts user to select a single file
title | text
initialDir | text
type | text
extraMimeTypes | list
TakePersistableUriPermissionTake a persistable URI permission grant that has been offered. Once taken, the permission grant will be remembered across device reboots.
uri | any
flags | number
IsTreeUriReturns whether given uri is a tree uri
uriString | text
IsDocumentUriReturns whether given uri is a document uri
uriString | text
IsChildDocumentUriReturns whether second uri is child of first uri
parentUri | text
childUri | text
GetTreeDocumentIdReturns document id of tree uri (should be either tree uri itself or a direct child uri)
uriString | text
GetDocumentIdReturns document id of an uri (should only be grand child)
uriString | text
BuildDocumentUriUsingTreeBuilds document uri using tree uri and document id
treeUri | text
documentId | text
BuildChildDocumentsUriUsingTreeBuilds child documents id using tree (documents which is child of parent document) uri and its parent document id
treeUri | text
parentDocumentId | text
GetDisplayNameReturns display name of given document uri
documentUri | text
GetSizeReturns size (in bytes) of given document uri
documentUri | text
GetLastModifiedTimeReturns last modified time (epoch) of given document uri
documentUri | text
GetMimeTypeReturns mime type of given document uri
documentUri | text
IsCopySupportedReturns whether document can be copied or not
documentUri | text
IsMoveSupportedReturns whether document is movable or not
documentUri | text
IsDeleteSupportedReturns whether document is deletable or not
documentUri | text
IsRenameSupportedReturns whether document is deletable or not
documentUri | text
CreateDocumentCreates a new and empty document.If document already exists then an incremental value will be suffixed.
parentDocumentUri | text
fileName | text
mimeType | text
WriteToFileWrites content as text to given uri
uriString | text
content | text
WriteAsHexStringWrites content as HEX to given uri
uriString | text
content | text
WriteAsByteArrayWrites byte array to given document
uriString | text
byteArray | any
DeleteDocumentTries to delete document from given uri and returns result
uriString | text
ReadFromFileReads from given document as text
uriString | text
ReadAsByteArrayReads content of document as byte array
uriString | text
ReadAsHexStringReads content of document as HEX string
uriString | text
IsReadGrantedReturns whether read is available for given uri
uri | text
ReleasePermissionRelinquish a persisted URI permission grant
uri | text
flags | number
IsWriteGrantedReturns whether write is available for given uri
uri | text
ListFilesTries to list files from given dir
dirUri | text
dirDocumentId | text
CopyDocumentTries to copy document from source uri to target dir
sourceUri | text
targetParentUri | text
MoveDocumentTries to move document from source uri to target dir
sourceUri | text
sourceParentUri | text
targetParentUri | text
RenameDocumentTries to rename a document and returns updated uri
documentUri | text
displayName | text
CopyDocumentToFileTries to copy document from source uri to specified folder
sourceUri | text
dirPath | text
CopyDocumentFromFile
filePath | text
targetParentUri | text
ConvertStringToBytesConverts text to bytes and return Byte Array object. It can be used with 'WriteAsByteArray' method.
byteString | text
CreateDocumentSyncCreates document on main thread and returns its uri immediately if operation was successful otherwise empty string is returned
parentDocumentUri | text
fileName | text
mimeType | text

Properties

DocumentDirMimeTypeReturns mime type of document dir
Property Type : read-only
Accepts : text
FlagGrantReadPermissionFlag to get write permission
Property Type : read-only
Accepts : number
FlagGrantWritePermissionFlag to get read permission
Property Type : read-only
Accepts : number

4.Usages

1.Open document tree
image

2.Get access (not necessary for one-time usage)

image

3.Build child document uri

  1. if document is direct child

  1. if document is grandchild

4.Read file/Set picture
image

Examples by Power Users
I am thankful to them for their efforts.

5.Download

Aix:
com.sunny.saf.aix (29.2 KB)

6.Open Source

7.Liked my work/Want to donate :heart:

Thank you :hugs:

8. ChangeLog

ChangeLog Version 1.1

New Blocks
image
image

Changes

  • Removed category param from OpenSingleDocument method
  • GotCopyResult and GotMoveResult now return resulting/target document's uri

Bug Fixes

  • Fixed issue in write methods
  • Fixed null pointer exception when SAF picker was cancelled by user
ChangeLog Version 1.2

SAF: App Inventor implementation of Storage Access Framework - #331 by vknow360

ChangeLog Version 1.3

SAF: App Inventor implementation of Storage Access Framework - #360 by vknow360

Thank you.
Hope it helps! :slightly_smiling_face:

25 Likes

What an amazing extension ! Great job!
I’ve only done a few tests and it seems to be working so far.

And it's a shame that your extensions need approval in AI2.
We should change that as soon as possible!

9 Likes

This looks important.

But I am not sure exactly what constitutes a document here.

  • Surely not a Microsoft .doc file?
  • A .html file with links to other .html files nearby?
  • an in-memory runtime structure ?
6 Likes

We can consider document as strictive version of normal files, which are accessible only via URIs.
File class is part of java.io while Document/ Document File is implementation of Google for File System to give user more control over his device , files and privacy.

5 Likes

That java.io link sent me into some kind of UAE discussion group.
I was expecting a documentation page for java, maybe under oracle.com?

6 Likes

I guess he did not mean to link any resource but just referring the java.io system.

6 Likes

For Real :star_struck:

That is the Best Extension, Good Job :sunglasses: :+1:

3 Likes

Epic work @vknow360 :slight_smile:

3 Likes

As @ABG says, this looks important, but I am guessing that most developers (which includes me) are not in the lucky 10,000 on this one, and therefore haven't got a clue as to what this is about our how they might use it in their apps. The example blocks give an inkling, but don't really help. Could a better description be provided, in layman's terms, of What this extension does, Why/When/Where one might use it, and How it works in more detail?

I am certain the work adds value to the AI2 development experience, especially in these times of Google privacy concerns and file location lockdown, but there is little point saying "great extension" in a post, if I have no understanding of what it does.

10 Likes

Yes, SAF is quite complicated to understand because Google had no time to explain why they decided to strict app's access to file system. Most developers felt homely by using legacy "File" approach, but launching of Android 10 started causing troubles for them and SAF is the solution to most of their problems.
Using this, you can-

  1. access phone storage*
  2. access SD card*
  3. read from/write to files created by other apps
  4. help user in protecting his/her data and restrict Storage consumed by apps
  5. get access to files and folders which are important to your app.
    In this way, you needn't ask for MANAGE_EXTERNAL_STORAGE permission.
  6. work with non-media files too, such as creating a CSV file of user's data or accessing a PDF file

*: Android/data and Android/obb folders are exception

One major advantage I would like to emphasize is usage of URIs instead of paths.

10 Likes

Example 2

  1. Open document picker and create document


    (Since you now know how to take persistable permission, so I'll skip that part)

  2. Read and write to document

  3. List files

4 Likes

Developers might also find these links about SAF useful in addition to your nice explanation.

4 Likes

Thanks @vknow360 for your explanations, making more sense now as to what one can do with your extension.

5 Likes

Well I have fallen at the first hurdle....

Following your first image, when I click the button I am taken to the device's default file manager (or what looks like it), I went to the root folder, the file manager asked me to give permission to this area (to MIT Companion App), then returns me to the project with this error:

image

4 Likes

I forget to mention that direct child's id should be obtained using GetTreeDocumentId method.

4 Likes

Sorry, I used the wrong block :upside_down_face:

3 Likes

OK that all works. :+1:

Is there no way then, in order to get started, other than the user going into their file manager and granting a permission, to get the root or other folder (tree)? (Open Document Tree)

Perhaps a uri for the ASD ?

I can see how one can traverse through a file list to find sub (folders) trees, and then list files again and so on. An image component accepts a content uri to display an image. Is this going to be the same for other components needing a file?

4 Likes

No, user must grant access through Documents Picker.

I am not sure about this.
Image component works fine.
Same should be correct for audio and video player.

4 Likes

Understood :slight_smile:

4 Likes

SAF is only needed for → non-media files. Media files (jpg, png, mp3, m4a, mp4,...) can be accessed from all paths (outside of the ASD or privateDir) with READ permission.

5 Likes