在我的应用程序中,我有一个自定义对话框,我可以从其中获取用户输入(如文本编辑器、spinner、日期选择器)。我在对话框中还有一个“发送”按钮。我希望在用户按下发送按钮后填写对话框中的字段后,他/她可能填写的数据应该 bundle 为 .csv 并附加到电子邮件并直接通过电子邮件发送,而无需打开默认电子邮件屏幕。
任何帮助将不胜感激。
姆拉纳
最佳答案
从 EditText、Spinner 和 DatePicker 获取数据,并使用 csv 所需的分隔符(例如逗号、分号、制表符、空格等)将其存储在字符串中。
接下来保存文件,然后使用 Intent.Action_SEND 和 Intent.CreateChooser 将文件作为附件发送。如果您的文件存储在内部(即,它是私有(private)的),那么您还需要使用 ContentProvider(请参阅此 link )。
这是一个例子:
//For simplicity's sake let's say you have three methods
//to get the value of your EditText, Spinner,
//and DatePicker and these methods return a String
String editTextValue = getEditTextValue();
String spinnerTextValue = getSpinnerTextValue();
String datePickerTextValue = getDPTextValue();
//Create a String in csv format with the String values obtained
//from the above fictitious methods. The delimiter in this case is the semicolon ";"
String myFileContentString = editTextValue + ";" +
spinnerTextValue + ";" +
datePickerTextValue + "\n";
//Save file to internal storage
FileOutputStream fos = openFileOutput("myfilename.csv", Context.MODE_WORLD_WRITEABLE);
fos.write(myFileContentString.getBytes());
fos.close();
//Send the file as an attachment
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "A CSV File");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "See attachment...");
emailIntent.putExtra(android.content.Intent.EXTRA_STREAM,
Uri.parse("content://" + MyContentProviderClass.AUTHORITY + "/" + "myfilename.csv"));
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
不要忘记使用 try/catch 捕获异常
您需要子类化 ContentProvider 类并重写 openFile 方法。请参阅链接here和 here了解如何实现您自己的内容提供程序。
在您的 ContentProvider 子类中,您将需要在 openFile 方法中执行以下操作:
String fileLocation = getContext().getFilesDir() + File.separator + "myfilename.csv";
ParcelFileDescriptor pfd = ParcelFileDescriptor.open(new File(fileLocation),
ParcelFileDescriptor.MODE_READ_ONLY);
return pfd;
并且不要忘记使用以下内容更新您的 AndroidManifest.xml:
<provider android:name="my.package.content.provider.Class"
android:authorities="my.package.content.provider"></provider></application>
list 文件中的提供程序声明位于应用程序声明中。
关于android - 如何将从自定义对话框(edittext、datepicker、spinner 等)捕获的数据 bundle 在 .csv 中并附加到 android 中的电子邮件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9645211/