che*_*bad 1 android android-intent internal-storage android-internal-storage
我创建了一堆文本文件,就像下面的代码一样。我将这些文件保存在内部存储器中。我现在的目标是在ListView中显示它,如果用户单击某个项目,它应该打开或通过意图(例如电子邮件)发送文件。
static void createFile (Context context) {
mTimeStamp = String.valueOf(System.currentTimeMillis()/1000);
try {
String fileName = "File_" + mTimeStamp + ".txt";
mContext = context;
mOutputStreamWriter = new
OutputStreamWriter(context.openFileOutput(fileName ,Context.MODE_PRIVATE));
String path = mContext.getFilesDir().getAbsolutePath();
Toast.makeText(mContext, "Creating file: " + path,
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
Log.e(TAG,"Error with creating file writer...");
e.printStackTrace();
}
}
static void writeToFileData(String dataToSave) {
try {
Toast.makeText(mContext, "Saving data to file: " + dataToSave, Toast.LENGTH_SHORT).show();
mOutputStreamWriter.write(dataToSave);
} catch (IOException e) {
Log.e(TAG,"Error with writing to file...");
e.printStackTrace();
}
}
static void closeFileWriter() {
try {
Toast.makeText(mContext, "Closing file... ", Toast.LENGTH_SHORT).show();
mOutputStreamWriter.close();
} catch (IOException e) {
Log.e(TAG,"Error with closing file writer...");
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
然后我列出我的所有文件,如下所示(不在ListView中,仅用于测试):
static void testDispFiles (Context context) {
mContext = context;
String path = mContext.getFilesDir().getAbsolutePath();
Log.v(TAG, "testDisp path: " + path);
File dirFile = new File(path);
File[] files = dirFile.listFiles();
Log.v(TAG, "testDisp length: " + files.length);
for (File f: files) {
Log.v(TAG, "testDisp file: " + f.getName());
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我想通过例如电子邮件发送来共享文件之一。如何通过意图从内部存储发送文本文件?
//编辑:
我创建了一个Intent,它会从Gmail应用返回吐司消息“您无法添加此文件”。
String path = mContext.getFilesDir().getAbsolutePath();
File f = new File(path);
File[] files = f.listFiles();
Uri data = Uri.fromFile(files[0]);
Intent i = new Intent(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_STREAM,data);
i.setType("plain/text");
i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
i.setFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
startActivity(i);
Run Code Online (Sandbox Code Playgroud)
我找到了解决该问题的方法之一。@CommonsWare如何建议我使用了FileProvider。我按照这个例子。但是在provider_paths.xml中,我放了这段代码,因为我使用了内部存储。
<Paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="files" path="."/>
</Paths>
Run Code Online (Sandbox Code Playgroud)
然后在活动中,我通过这样的意图发送文件:
Uri path = FileProvider.getUriForFile(this,"same_authoritory_which_was_in_manifest", new File(FILE_TO_SAVE.getPath()));
Intent i = new Intent(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_TEXT, "Test");
i.putExtra(Intent.EXTRA_STREAM, path);
i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
i.setType("plain/*");
startActivity(i);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1994 次 |
| 最近记录: |