Android Question FileProvider not reliable with <24 Android

JohnC

Expert
Licensed User
Longtime User
I am continuing a conversation from this thread:

https://www.b4x.com/android/forum/t...from-your-app-with-file-provider.70458/page-2

Basically, my app shares a file with the devices default MMS app using an intent.

I had the targetSdkVersion set to 21, so when I had "file://" in the uri, it worked for android 4.4, 7, 8 no problem.

But now that we must set targetSdkVersion to 26, I tried to use the recommended FileProvider (content://) method using the example in post #4:

https://www.b4x.com/android/forum/threads/share-txt-files.73166/#post-464921

And this works great on android 7. But when I tried running on 5.0, the file won't get copied over into the devices MMS app (it is Samsung's official galaxy 5.0.1 default messaging app) - it gives "unable to attach file".
However, if I instead send the file using a gmail intent, the file is copied over as an attachment. So the fileprovider method is not working reliably for all versions of android/apps.

So I had to create a routine that checks if the device is 24 or higher and uses FileProvider, but using file:// if less then 24:

B4X:
Sub GetFileUri (Dir As String, FileName As String) As Object
    Dim P As Phone
    If P.SdkVersion >= 24 Then
        Return CreateFileProviderUri(Dir,FileName)
    Else
        Return CreateUri("file://" & File.Combine(Dir, FileName))
    End If
End Sub

Sub CreateUri(uri As String) As Object
    Dim r As Reflector
    Return r.RunStaticMethod("android.net.Uri", "parse", Array As Object(uri), Array As String("java.lang.String"))
End Sub

Sub CreateFileProviderUri (Dir As String, FileName As String) As Object
    Dim FileProvider As JavaObject
    Dim context As JavaObject
    context.InitializeContext
    FileProvider.InitializeStatic("android.support.v4.content.FileProvider")
    Dim f As JavaObject
    f.InitializeNewInstance("java.io.File", Array(Dir, FileName))
    Return FileProvider.RunMethod("getUriForFile", Array(context, Application.PackageName & ".provider", f))
End Sub

So why is the FileProvider not working reliably for android <24?
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…