我正在尝试在Xamarin / Android中创建一个示例应用程序,它从Internet下载一个图像并在ImageView中显示它。但是在执行var imageContent = await httpClient.GetByteArrayAsync (ImageUrl);
之后不久,UI /应用程序就会挂起。没有回电响应即将到来。我正在添加我的完整源代码供您参考。请帮我解决我的样本中的错误。
[Activity (Label = "ImageDownloadSample", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
private const string ImageUrl = "http://www.olympusimage.com.sg/content/000006422.jpg";
private ImageView imgView;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
var button = FindViewById<Button> (Resource.Id.downloadImage);
imgView = FindViewById<ImageView>(Resource.Id.imageView);
button.Click+=((sender, e) =>
DownloadImageAsync());
}
private async void DownloadImageAsync()
{
var httpClient = new HttpClient ();
imgView.SetImageResource (Android.Resource.Drawable.IcMenuGallery);
var imageContent = await httpClient.GetByteArrayAsync (ImageUrl);
var documentsPath = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal);
string localFilename = "mytestImage.jpg";
string localPath = System.IO.Path.Combine (documentsPath, localFilename);
File.WriteAllBytes (localPath, imageContent);
var localImage = new Java.IO.File (localFilename);
if (localImage.Exists ()) {
var bitmapImage = BitmapFactory.DecodeFile (localImage.AbsolutePath);
imgView.SetImageBitmap (bitmapImage);
}
}
}
}
请帮助
答案 0 :(得分:0)
他们有一个样本应用程序正是这样做的:https://github.com/xamarin/monodroid-samples/blob/master/AsyncImageAndroid/AsyncImageAndroid/MainActivity.cs
此外,您尝试下载的图片看起来非常庞大......我一定会得到一些更合理的东西,只是为了在尝试让事情发挥作用时将其视为错误。
答案 1 :(得分:0)
我有同样的问题。检查异常!如果你有超时设置HttpClient.Timeout更大!
答案 2 :(得分:-1)
您可能需要设置事件处理程序:
button.Click+=(async (sender, e) => DownloadImageAsync());
表示它包含可以异步运行的代码