我想在外部图片查看器应用中打开保存在我的应用中的图片。
由于图像存储在(私人)应用目录中,因此我使用内容提供商。
以下是我的内容提供商的代码:
[ContentProvider(new string[] { "com.company.myapp" })]
public class CustomContentProvider : ContentProvider
{
public static readonly string AUTHORITY = "com.company.myapp";
public static readonly Android.Net.Uri CONTENT_URI = Android.Net.Uri.Parse("content://" + AUTHORITY);
public CustomContentProvider()
{
System.Console.WriteLine ("Custom Content Provider Initialized");
}
public override int Delete (Android.Net.Uri uri, string selection, string[] selectionArgs)
{
throw new NotImplementedException ();
}
public override string GetType (Android.Net.Uri uri)
{
var mimeType = MimeTypeHelper.GetMimeType(uri.ToString());
return mimeType;
}
public override Android.Net.Uri Insert (Android.Net.Uri uri, ContentValues values)
{
throw new NotImplementedException ();
}
public override bool OnCreate ()
{
return true;
}
//DOES NOT GET CALLED ON MOST DEVICES
public override ParcelFileDescriptor OpenFile(Android.Net.Uri uri, string mode)
{
string fileName = uri.ToString ().Substring (CONTENT_URI.ToString ().Length);
System.Console.WriteLine (fileName + " - File to open in external app");
if (System.IO.File.Exists (fileName)) {
return ParcelFileDescriptor.Open(new Java.IO.File(fileName), ParcelFileMode.ReadOnly);
}
return null;
}
public override Android.Database.ICursor Query (Android.Net.Uri uri, string[] projection, string selection, string[] selectionArgs, string sortOrder)
{
throw new NotImplementedException ();
}
public override int Update (Android.Net.Uri uri, ContentValues values, string selection, string[] selectionArgs)
{
throw new NotImplementedException ();
}
}
要在外部图像查看器应用程序中打开图像,我使用以下代码:
string fullFilePath = await DataLayer.Instance.GetFilePath (clickedItem.Path);
Intent intent = new Intent(Intent.ActionView, Android.Net.Uri.Parse (CustomContentProvider.CONTENT_URI + fullFilePath));
intent.SetFlags (ActivityFlags.GrantReadUriPermission);
intent.SetFlags (ActivityFlags.NewTask);
intent.SetFlags (ActivityFlags.ClearWhenTaskReset);
Activity.StartActivity (intent);
问题是它适用于所有设备。
方法覆盖ParcelFileDescriptor OpenFile(Android.Net.Uri uri,字符串模式)并不总是被调用。
有人知道如何解决这个问题吗?
更新
测试了几个版本的Android:
答案 0 :(得分:1)
问题解决了。
需要将“已导出”属性显式设置为true
在Xamarin.Android中:
[ContentProvider(new string[] { "com.company.myapp" }, Exported = true)]
在“原生”Android中:
<provider android:name=".CustomContentProvider" android:authorities="com.company.myapp" android:exported="true" />