【发布时间】:2017-12-23 19:48:20
【问题描述】:
我创建了一堆我在下面的代码中创建的文本文件。我将这些文件保存在内部存储中。我现在的目标是在 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();
}
}
然后我像这样列出我的所有文件(不在 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());
}
}
现在我想通过例如发送文件来共享其中一个文件。电子邮件。如何通过意图从内部存储发送文本文件?
//编辑:
我创建了一个 Intent,它会从 Gmail 应用程序返回 toast“您无法添加此文件”消息。
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);
【问题讨论】:
-
您可以使用TinyDB将String存储在内部存储中然后可以得到它:TinyDB.class here
-
使用
FileProvider:developer.android.com/reference/android/support/v4/content/… -
@CommonsWare 你能帮我解决这个问题吗?我从不使用 FileProvider。
-
我向您指出了文档和here is some more。 Here is a sample app 来自 one of my books,显示使用
FileProvider表示ACTION_IMAGE_CAPTURE和ACTION_VIEW。如果您对如何使用FileProvider有其他疑虑,并且找不到有关该主题的现有资料,请针对您的具体问题提出单独的 Stack Overflow 问题。 -
对于 Kotlin,你可以试试这个:stackoverflow.com/a/62928442/2462531
标签: android android-intent internal-storage android-internal-storage