Android Question Automatic Selection of External SD Root Path

GuyBooth

Active Member
Licensed User
Longtime User
The following code (in a slightly modified version of the ExtStorage class for accessing external SD storage) opens a browser, on which the user can simply tap a "Select" button to return the External SD Root Folder path to the application. (The user can also select from available choices to return a Root path from a folder lower in the tree)

Is there a piece of code that makes it possible to automatically return the root without the user tapping on the "Select" button? Or better yet, is there a piece of code that can return the Root without starting the browser in the first place?

B4X:
Public Sub Set_RootDir
    Dim i As Intent
    i.Initialize("android.intent.action.OPEN_DOCUMENT_TREE", "")
    i.PutExtra("android.content.extra.SHOW_ADVANCED", True)
    Start_ActivityForResult(i)
    ' Class Global Variable RootString is set by Start_ActivityForResult
End Sub
' For use with settings file
Private Sub Start_ActivityForResult(i As Intent)
    Dim jo As JavaObject = Get_BA
    ion2 = jo.CreateEvent("anywheresoftware.b4a.IOnActivityResult", "ion2", Null)
    jo.RunMethod("startActivityForResult", Array As Object(ion2, i))
End Sub
' For use with settings file
Private Sub ion2_Event (MethodName As String, Args() As Object) As Object
    Dim RootString As String
    If Args(0) = -1 Then 'resultCode = RESULT_OK
        Dim i As Intent = Args(1)
        Dim jo As JavaObject = i
        Dim treeUri As Uri = jo.RunMethod("getData", Null)
        Dim takeFlags As Int = Bit.And(i.Flags, 3)
        ctxt.RunMethodJO("getContentResolver", Null).RunMethod("takePersistableUriPermission", Array(treeUri, takeFlags))
        RootString = treeUri 'ignore
    Else
        RootString = ""     'ignore
    End If
    CallSubDelayed2(mCallback, mEventName & "_RootStringReady", RootString)
    Return Null
End Sub
 

DonManfred

Expert
Licensed User
Longtime User
Or better yet, is there a piece of code that can return the Root without starting the browser in the first place?
I dont think that there is such a Method as the SAF does not allow it
Starting from Android 4.4 it is no longer possible to directly access external storages.
The only way to access these storages is through the Storage Access Framework (SAF), which is a quite complex and under-documented framework.
 
Upvote 0

GuyBooth

Active Member
Licensed User
Longtime User
Note that once the user selected the path you can save the Uri for future usages.
Understood - I actually changed the code to save to a KeyValueStore, rather than a file.
 
Last edited:
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…