android - 为什么我不能在 Android N+ 中附加文件?
问题描述
我正在开发一个将一些 HTML 表格作为附件导出的应用程序。我注意到,如果我尝试将 HTML 表附加到 Gmail、Google Drive 或 Android N+ 中的任何电子邮件提供商,我的代码将不起作用,但它可以将文件上传到 OneDrive、WhatsApp、Skype 等。任何问题。
这是我当前的代码:
Intent share = new Intent(Intent.ActionSend);
share.SetType("text/html");
share.AddFlags(ActivityFlags.NewDocument);
var file = CreateDirFile($"Meeting_{DateTime.Now.ToString("dd_MM_yyyy_HH_mm_ss")}.html");
try
{
FileOutputStream fout = new FileOutputStream(file);
fout.Write(System.Text.Encoding.ASCII.GetBytes($"<!DOCTYPE html><html><body><table><tr><td>1</td><td>2</td><td>3</td></tr></table></body></html>"));
fout.Close();
}
catch
{
Toast.MakeText(context, context.GetString("Please check your storage configuration.").Show();
}
if (Build.VERSION.SdkInt < BuildVersionCodes.N)
{
share.PutExtra(Intent.ExtraStream, Android.Net.Uri.FromFile(file.AbsoluteFile));
}
else
{
share.AddFlags(ActivityFlags.GrantReadUriPermission);
share.PutExtra(Intent.ExtraStream, Android.Net.Uri.Parse(file.Path));
}
share.PutExtra(Intent.ExtraSubject, $"Meeting {DateTime.Now.ToString("dd-MM-yyyy")}");
context.StartActivity(Intent.CreateChooser(share, "Email:"));
创建目录文件函数:
private Java.IO.File CreateDirFile(string fileName)
{
string root = null;
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}/Meetings");
myDir.Mkdir();
Java.IO.File file = new Java.IO.File(myDir, fileName);
if (file.Exists())
{
file.Delete();
file.CreateNewFile();
}
return file;
}
我已经测试了许多组合,甚至按照Android.Net.Uri.Parse(file.Path)
SO 或其他论坛的不同答案中的建议应用了以下代码,但它没有按预期工作。
你们有没有遇到过类似的问题?你知道我应该改变什么吗?提前致谢。
解决方案
尽管 Richard 的答案在 Java 中是正确的,但在 C# 中需要进行一些更改,如下所示:
在OnCreate
事件中:
if (Build.VERSION.SdkInt >= BuildVersionCodes.N)
{
StrictMode.VmPolicy policy = new StrictMode.VmPolicy.Builder()
.PenaltyDeathOnFileUriExposure()
.Build();
StrictMode.SetVmPolicy(policy);
}
此外,您只需要这样做即可:
share.PutExtra(Intent.ExtraStream, Android.Net.Uri.FromFile(file.AbsoluteFile));
您不需要验证操作系统版本,并且Android.Net.Uri.Parse(file.Path))
必须删除此代码才能获得正确的行为。
推荐阅读
- ios - 如何从Swift5中的最后一个索引开始获取特定字符之前的所有字符?
- php - 递归遍历 PHP 中 10000 个元素的数组:达到最大函数嵌套级别
- html - 解码html特殊字符 - Angular
- java - Firestore 查询 - orderBy 使用返回 null queryDocumentSnapshots 的时间戳
- typescript - 任意数量的函数重载
- sql - SQL - 创建具有多个连接的视图的问题
- android - 在约束布局中围绕多个视图放置边框
- html - 图片怎么才能不溢出高度
- dpdk - DPDK API 中的 rte_eth_dev_count_avail() 返回 0
- c# - C# Entity Framework Core If 语句不起作用