【发布时间】:2017-10-21 20:08:08
【问题描述】:
我目前正在寻找一种方法来将文件保存在设备的内部存储器中,然后通过邮件发送。为此,我使用 FileProvider
所以在 Android Manifest 中,我将这些行添加到我的清单中:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="exploration.syte.fr.sendbymail4.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/paths" />
</provider>
在 res/xml 路径上我添加了这个文件路径:paths.xml
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="files" path="files/"/>
</paths>
这是我用来创建文件的代码 - 一个非常简单的文本文件,其中包含“test”一词。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String textToWrite = "test";
try {
File path = this.getFilesDir();
File file = new File(path, "myfile.txt");
String chemin = file.getAbsolutePath().toString();
Log.i("MainActivity", chemin);
Toast.makeText(this, chemin, Toast.LENGTH_LONG).show();
FileOutputStream fos = new FileOutputStream(file);
fos.write(textToWrite.getBytes());
fos.close();
//Toast.makeText(this, "File correctly saved", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Log.d("Main", "Exception", e);
}
try {
sendFile(this);
} catch (Exception e) {
Log.d("Main", "Exception", e);
}
}
以及我用来通过电子邮件发送文件的代码
public static void sendFile(Context context){
Intent intent=new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
String directory=(String.valueOf(context.getFilesDir())/*+File.separator+"directory"*/);
File file=new File(directory+File.separator+"myfile.txt");
Uri uri = FileProvider.getUriForFile(context, "exploration.syte.fr.sendbymail4.fileprovider", file);
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
context.startActivity(intent);
}
**我目前遇到的问题是:**
- 我的文件没有保存在正确的目录:它保存在
/data/user/0/exploration.syte.fr.sendbymail4/files/myfile.txt
我希望我的文件保存在:/data/data/exploration.syte.fr.sendbymail4/files/myfile.txt
如果文件保存正确,如何设置路径?
提前致谢!
【问题讨论】:
-
我的文件没有保存在正确的目录中 嗯,它是一个正确的路径...如果你是,为什么你想要路径使用 FileProvider?
-
也许有一些我当时不明白的东西......如何使用 FileProvider 保存我的文件?
-
这一切都在文档中......你没有忘记路径中的“文件”吗?路径应该是“files/files/myfile.txt”当您查看文档时很明显:from xml
files-path表示应该使用getFilesDir()(app/files) 但 xml 中还有另一个文件path="files/"(应用程序/文件/文件) -
问题出在...我将路径从“files/”更改为“/”,并且成功了。谢谢您的帮助:)
标签: android email-attachments android-fileprovider