如何解决Xamarin Essentials 媒体选择器不断使我的应用程序崩溃 - 没有例外或错误
我构建了一个 Xamarin 应用程序:Android,并试图让用户能够设置头像。使用 Xamarin Essentials Media Picker 我试图捕获图像或选择一个图像。但是每次应用程序运行任一方法时,它都会工作,然后在选择或捕获图像之前使应用程序崩溃。有趣的是它有时有效,但几乎从来没有。
我尝试了很多方法来弄清楚发生了什么,但没有实际错误可以解决,我一无所获。
我使用的是 MVVM 设计模式。 我的代码:
private async Task TakePicture()
{
try
{
var photo = await MediaPicker.PickPhotoAsync();
if (photo != null)
{
await App.UserManager.UpdateAvatarasync(photo);
RenderImages();
}
}
catch (global::System.Exception ex)
{
await AppShell.Current.displayAlert("Oops","Something went wrong and its not your fault","Okay");
}
}
解决方法
您可以使用以下方式来挑选照片。
1.使用 Xam.Plugin.Media
。您可以从 NuGet 安装。不要忘记检查您保存照片的位置并请求运行时权限。
下面的代码展示了如何从相机中选取照片并将其设置为图像控件。
pickPhoto.Clicked += async (sender,args) =>
{
if (!CrossMedia.Current.IsPickPhotoSupported)
{
DisplayAlert("Photos Not Supported",":( Permission not granted to photos.","OK");
return;
}
var file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
{
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,});
if (file == null)
return;
image.Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
file.Dispose();
return stream;
});
};
2.使用依赖服务。
[assembly: Dependency(typeof(PhotoPickerService))]
namespace DependencyServiceDemos.Droid
{
public class PhotoPickerService : IPhotoPickerService
{
public Task<Stream> GetImageStreamAsync()
{
// Define the Intent for getting images
Intent intent = new Intent();
intent.SetType("image/*");
intent.SetAction(Intent.ActionGetContent);
// Start the picture-picker activity (resumes in MainActivity.cs)
MainActivity.Instance.StartActivityForResult(
Intent.CreateChooser(intent,"Select Photo"),MainActivity.PickImageId);
// Save the TaskCompletionSource object as a MainActivity property
MainActivity.Instance.PickImageTaskCompletionSource = new TaskCompletionSource<Stream>();
// Return Task object
return MainActivity.Instance.PickImageTaskCompletionSource.Task;
}
}
}
您可以从下面的链接下载源文件。 https://docs.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/dependencyservice/
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。