我创建了一堆文本文件,就像下面的代码一样。我将这些文件保存在内部存储中。现在我的目标是在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());
}
}
我想通过发送电子邮件等方式分享一个文件。如何通过意图从内部存储发送文本文件?
//编辑:
我创建了一个意图,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);
FileProvider
:https://developer.android.com/reference/android/support/v4/content/FileProvider.html - CommonsWareACTION_IMAGE_CAPTURE
和ACTION_VIEW
中使用FileProvider
。如果您对如何使用FileProvider
有其他疑问,并且找不到相关的资料,请在Stack Overflow上提出单独的问题,说明您的具体问题。 - CommonsWare