您可以通过两种解决方案做到这一点:
解决方案 1: 在系统默认浏览器中打开 URL。
private async Task MWebview_Download(object sender, DownloadEventArgs e)
{
await Launcher.OpenAsync(e.Url);
}
解决方案 2 使用 HttpClient 下载。
private async void MWebview_Download(object sender, DownloadEventArgs e)
{
string fileName = GetFileName(e);
Device.BeginInvokeOnMainThread(() =>
{
Toast.MakeText(MainActivity.Instance, "Downloading File...", ToastLength.Long).Show();
});
await DownloadPdfFile(e, fileName);
}
private async Task DownloadPdfFile(DownloadEventArgs e, string fileName)
{
try
{
//Bypass the certificate
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
// Getting Cookie
String cookies = CookieManager.Instance.GetCookie(e.Url);
var client = new HttpClient(clientHandler);
var httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(e.Url),
Headers = {
{ HttpRequestHeader.TransferEncoding.ToString(), "binary" },
{ HttpRequestHeader.ContentLength.ToString(), e.ContentLength+"" },
{ HttpRequestHeader.ContentType.ToString(), "application/pdf" },
{HttpRequestHeader.Cookie.ToString(),cookies },
},
};
// Api Call
var response = await client.SendAsync(httpRequestMessage);
// Read content as Byte[]
var bytes = response.Content.ReadAsByteArrayAsync().Result;
// Save to Local DB
var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
var filePath = Path.Combine(documentsPath, fileName);
// convert byte to stream
MemoryStream stream = new MemoryStream(bytes);
// Write file
SaveAndView(fileName, "application/pdf", stream);
}
catch (Exception ee)
{
Toast.MakeText(MainActivity.Instance, "Failed !!", ToastLength.Long).Show();
}
}
public void SaveAndView(string fileName, String contentType, MemoryStream stream)
{
string exception = string.Empty;
string root = null;
if (ContextCompat.CheckSelfPermission(MainActivity.Instance, Manifest.Permission.WriteExternalStorage) != Permission.Granted)
{
ActivityCompat.RequestPermissions((Activity)MainActivity.Instance, new String[] { Manifest.Permission.WriteExternalStorage }, 1);
}
if (Android.OS.Environment.IsExternalStorageEmulated)
{
root = Android.OS.Environment.ExternalStorageDirectory.ToString();
}
else
root = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
Java.IO.File myDir = new Java.IO.File(root + "/PDFFiles");
myDir.Mkdir();
Java.IO.File file = new Java.IO.File(myDir, fileName);
if (file.Exists()) file.Delete();
try
{
FileOutputStream outs = new FileOutputStream(file);
outs.Write(stream.ToArray());
outs.Flush();
outs.Close();
}
catch (Exception e)
{
exception = e.ToString();
}
if (file.Exists() && contentType != "application/html")
{
string extension = MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString());
string mimeType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
Intent intent = new Intent(Intent.ActionView);
intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask);
Android.Net.Uri path = FileProvider.GetUriForFile(MainActivity.Instance, Android.App.Application.Context.PackageName + ".provider", file);
intent.SetDataAndType(path, mimeType);
intent.AddFlags(ActivityFlags.GrantReadUriPermission);
MainActivity.Instance.StartActivity(Intent.CreateChooser(intent, "Choose App"));
}
}
注意:确保处理 FileProvider:
**Changes in Manifest file:**
- Add android:requestLegacyExternalStorage="true" in application tag
- Add between application tag
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false" android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
在 Xamarin.Android 项目的 Resources 文件夹内的 xml 文件夹中添加 file_paths.xml:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path name="my_images" path="Pictures" />
<external-files-path name="my_movies" path="Movies" />
<external-path name="external_files" path="."/>
</paths>