首页 > 解决方案 > 为什么我不能在 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 或其他论坛的不同答案中的建议应用了以下代码,但它没有按预期工作。

你们有没有遇到过类似的问题?你知道我应该改变什么吗?提前致谢。

标签: androidandroid-intentxamarin.androidemail-attachmentsandroid-7.0-nougat

解决方案


尽管 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)) 必须删除此代码才能获得正确的行为。


推荐阅读