我正在使用Xamarin学习C#和Android编程。 在一些教程之后,我做了一个简单的程序,通过Async进程从URL下载图像。 我想改进我的项目添加一个可以删除该过程的停止按钮。 我已按照本指南https://msdn.microsoft.com/enus/library/jj155759(v=vs.110).aspx 我添加了一个令牌,但问题出在我的代码的第90行。 我的方法“GetByteArrayAsync(”“)不能使用多个参数。
你有什么建议吗?
using Android.App;
using Android.Widget;
using Android.OS;
using System.IO;
using Android.Graphics;
using System.Threading.Tasks;
using System.Net.Http;
using System;
using System.Threading;
namespace App4
{
[Activity(Label = "App4", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
//Declare a Cancellation Token Source
CancellationTokenSource cts;
Button startbutton;
Button stopbutton;
TextView textView;
TextView textView1;
ImageView image;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
startbutton = FindViewById<Button>
(Resource.Id.startbutton);
stopbutton = FindViewById<Button>
(Resource.Id.stopbutton);
textView = FindViewById<TextView>
(Resource.Id.textView);
image = FindViewById<ImageView>
(Resource.Id.image);
textView1 = FindViewById<TextView>
(Resource.Id.textView1);
image.SetImageResource(Resource.Drawable.Icon);
//BASIC ASYNC START TASK
// click the startbutton to start the process
startbutton.Click += async (sender, e) =>
{
textView1.Text += " Loading...";
// Instantiate the CancellationTokenSource
cts = new CancellationTokenSource();
try
{
// **** GET ****
await DownloadImageAsync(cts.Token);
}
catch (System.OperationCanceledException)
{
textView1.Text += " Download deleted ";
}
catch (Exception)
{
textView1.Text += "Generic Error";
}
// ***Set the CancellationTokenSource to null when the download is complete.
cts = null;
};
//STOP BUTTON
stopbutton.Click += (sender,e) =>
{
if (cts != null)
{
cts.Cancel();
}
};
}
//ASYNC METHOD called by startbutton
public async Task DownloadImageAsync(CancellationToken ct)
{
var httpClient = new HttpClient();
// You might need to slow things down to have a chance to cancel.
await Task.Delay(500);
// byte[] imageBytes = await httpClient.GetByteArrayAsync("https://xamarin.com/content/images/pages/about/team-h.jpg",ct);
byte[] imageBytes = await httpClient.GetByteArrayAsync("https://pbs.twimg.com/profile_images/604644048/sign051.gif",ct);
//// THIS CODE STORE THE IMAGE IN THE LOCAL MEMORY OF THE APP////
string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string localFilename = "image.jpg";
string localPath = System.IO.Path.Combine(documentsPath, localFilename);
File.WriteAllBytes(localPath, imageBytes);
textView1.Text = " Image downloaded.";
var localImage = new Java.IO.File(localPath);
if (localImage.Exists())
{
var teamBitmap = BitmapFactory.DecodeFile(localImage.AbsolutePath);
image.SetImageBitmap(teamBitmap);
}
///////////////////////////////////////////////////////////////////////////
}
}
}