【发布时间】:2020-09-27 16:32:02
【问题描述】:
直到今天,我从未想过要从 Urls 下载文件,需要在他的 Activity 类上实现接口下载监听器。我在 Xamarin Android 中有一个 webview,但我似乎无法下载文件..
想那是因为我还没有在我的班级上实现这个接口下载监听器..所以我试了一下,但我似乎无法将接口实现方法与OnDwnloadStart 方法连接起来,我想当我请求从网络下载时页面然后 IDownloadListener 方法什么都不做,因为它没有代码....但是应该处理下载请求的代码在带有 url, ContentDisposition and mimetype 参数的 OnDownloadStart 方法中,任何进行接口调用 OnDownloadStart 方法的 hep 肯定会不胜感激..这是我使用的代码...
class Internet : AppCompatActivity,IDownloadListener
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
SetContentView(Resource.Layout.Browser);
//Webview definition
webview = this.FindViewById<WebView>(Resource.Id.webview1);
//webview properties
webview.SetWebViewClient(new WebViewClient());
WebSettings webSettings = webview.Settings;
webSettings.SetSupportMultipleWindows(true);
webSettings.SetEnableSmoothTransition(true);
webSettings.JavaScriptEnabled = true;
webSettings.DomStorageEnabled = true;
webSettings.AllowFileAccessFromFileURLs = true;
// webSettings.JavaScriptEnabled.
webview.SetDownloadListener(this);
}
//Interface Download Listener Method
public interface IDownloadListener : Android.Runtime.IJavaObject, IDisposable
{
//I got nothing here and this is what i think needs to call OndownloadStart
}
//implementing OnDownloadStart Method
public void OnDownloadStart(string url, string userAgent, string contentDisposition, string mimetype, long contentLength)
{
DownloadManager.Request request = new DownloadManager.Request(Android.Net.Uri.Parse(url));
String cookies = CookieManager.Instance.GetCookie(url);
request.AddRequestHeader("cookie", cookies);
request.AddRequestHeader("User-Agent", userAgent);
request.SetDescription("Downloading file to crn folder...");
request.SetTitle(URLUtil.GuessFileName(url, contentDisposition, mimetype));
request.AllowScanningByMediaScanner();
request.SetNotificationVisibility(Android.App.DownloadVisibility.VisibleNotifyCompleted);
File dest = new File(Android.OS.Environment.RootDirectory + "download");
if (!dest.Exists())
{
if (!dest.Mkdir())
{ Log.Debug("TravellerLog ::", "Problem creating Image folder"); }
}
request.SetDestinationInExternalFilesDir(Application.Context, "download",
URLUtil.GuessFileName(url, contentDisposition, mimetype));
DownloadManager manager =
(DownloadManager)GetSystemService(Android.App.Application.DownloadService);
manager.Enqueue(request);
//Notify if success with BroadCast Receiver
}
}
这段代码的哪一部分运行错误?任何帮助表示赞赏..
【问题讨论】:
-
你不需要自己定义IDownloadListener接口,你需要提供一个实现
-
@Jason,我该怎么做?
-
删除
public interface IDownloadListener... -
method,OnDownloadStart呢,我该如何实现呢? -
你已经有了它的实现。如果您不了解 C# 接口的工作原理,请花时间阅读文档。 docs.microsoft.com/en-us/dotnet/csharp/programming-guide/…
标签: c# android xamarin webview