无法附加.xls文件电子邮件意图 - 安卓



我正在创建一个.xls文件并将其保存到下载文件夹中。我正在尝试将.xls文件作为电子邮件附件发送。然而,当Gmail打开时,我收到一条祝酒词错误消息,上面写着"无法附加文件"。此错误消息来自Gmail。我已验证文件创建是否正确。我不知道为什么它没有附在电子邮件中。

这是创建文件和emailIntent的代码。

try{
String nowDateTime = System.currentTimeMillis()+"";
File filePath = new File(Environment.getExternalStorageDirectory()+"/Download/"+"ExcelFile_"+nowDateTime+".xls");
if(!filePath.exists()){
filePath.createNewFile();
}
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
hssfWorkbook.write(fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
Intent emailIntent = new Intent(Intent.ACTION_SEND);
Uri uri = Uri.fromFile(filePath);
Log.e("FilePath", filePath.toString());
Log.e("Uri", uri.toString());
emailIntent.setType("application/excel");
emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.Email_Subject_Line));
emailIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(emailIntent);
}catch(Exception e){
Log.e("GraphReportDialog", "Creating Excel Sheet File Output Stream Error "+ e.getMessage());
}

清单权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

CommonsWare使用FileProvider是正确的。文档中说Uri.fromFile((不如FileProvider安全。

一旦我添加了3个主要内容,它就如预期的那样起作用了。第一件事是在清单文件中添加提供者:

<provider
android:authorities="com.example.counter"
android:name="androidx.core.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"
/>
</provider>

第二件事是添加路径。我在res文件中创建了另一个名为xml的目录。然后我添加了一个名为provider_paths.xml的xml文件

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path <!-- there are several different types of paths to use see the documentation-->
name="external_files"
path="."  /> <!-- consider changing this to more specific path-->
</paths>

最后,这就是我实现它的方式

String nowDateTime = System.currentTimeMillis()+"";
File filePath = new File(Environment.getExternalStorageDirectory()+"/Download/"+"ExcelFile_"+nowDateTime+".xls");
if(!filePath.exists()){
filePath.createNewFile();
}
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
hssfWorkbook.write(fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
Intent emailIntent = new Intent(Intent.ACTION_SEND);
Uri uri = FileProvider.getUriForFile(this.getContext(),"com.example.counter", filePath);
emailIntent.setType("application/excel");
emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.Email_Subject_Line));
emailIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(emailIntent);