【发布时间】:2015-01-09 07:00:32
【问题描述】:
我正在尝试在 Xamarin / Android 中创建一个示例应用程序,它从 Internet 下载一张图像并将其显示在 ImageView 中。但在执行var imageContent = await httpClient.GetByteArrayAsync (ImageUrl); 后不久,用户界面/应用程序挂起。没有回叫响应即将到来。我正在添加我的完整源代码供您参考。请帮助我的示例中有什么问题。
[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);
}
}
}
}
请帮忙
【问题讨论】:
标签: c# xamarin xamarin.android httpclient xamarin.forms