Xamarin OpenInputStream permission ACTION_OPEN_DOC

2019-08-26 08:10发布

问题:

I'm developing an app on android and i'm getting an exception when i use openInputStream with certain uri, here is my code

try
{
   using (var stream = Context.ContentResolver.OpenInputStream(Android.Net.Uri.Parse(uriString)))
   {
      //
   }
}
catch (Exception e)
{
}

when the uri = 'content://media/external/images/media/61155' I get no exception

but when the uri is like this 'content://com.android.providers.media.documents/document/image%3A61797'

I get this exception

Permission Denial: opening provider com.android.providers.media.MediaDocumentsProvider from ProcessRecord.... requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs

I have no idea how to resolve this

I'm testing with a device with android oreo 8.0

Minimum android sdk api 21 (Lollipop 5.0)

Target android sdk api 24 (Nougat 7.0)

回答1:

Assuming you are performing a document open Intent, you need to request the uri permission(s) (read and/or write) that you need via TakePersistableUriPermission

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
    if (requestCode == (int)ResultCode.Chooser && resultCode.HasFlag(Result.Ok))
    {
        var uri = data.Data;
        if (Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat)
        {
            ContentResolver.TakePersistableUriPermission(uri, ActivityFlags.GrantReadUriPermission);
        }
        using (var stream = ContentResolver.OpenInputStream(uri))
        {          
            Log.Debug("TAG", uri.ToString());
        }
    }
}

re: takePersistableUriPermission