首先,我实际上已经阅读了几个有关在 Android 上发送附件的线程。也就是说,我还没有找到解决我的问题的方法。
我的应用相对简单,用户输入数字,使用 openFileOutput(filename, Context.MODE_APPEND); 将它们保存到“values.csv”。
现在,这是我用来将文件附加到电子邮件并发送的代码(我从其他文件线程之一获取它。)
private void sendEmail(String email) {
File file = getFileStreamPath(filename);
Uri path = Uri.fromFile(file);
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("application/octet-stream");
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Test");
String to[] = { email };
intent.putExtra(Intent.EXTRA_EMAIL, to);
intent.putExtra(Intent.EXTRA_TEXT, "Testing...");
intent.putExtra(Intent.EXTRA_STREAM, path);
startActivityForResult(Intent.createChooser(intent, "Send mail..."),
1222);
}
这将打开我的电子邮件客户端,除了附加文件之外,它可以正常执行所有操作,并向我显示一条 Toast 通知,提示“文件不存在。”
我错过了什么吗?顺便说一下,我已经添加了读取和写入外部存储的权限。
任何和所有帮助将不胜感激。
编辑:我可以使用 DDMS 中的文件资源管理器模块并导航到/data/data/com.example.myapp/files/(我的 value.csv 所在的位置),并将其复制到我的计算机,因此该文件确实如此存在。一定是我的代码有问题。
最佳答案
因此,除了使用 MODE_WORLD_READABLE 之外,附加电子邮件的另一种方法是使用 ContentProvider。 here中有一个很好的教程可以做到这一点。
但我也会很快向您解释它,然后您可以阅读该教程。
因此,首先您需要创建一个 ContentProvider
来提供对应用程序内部缓存中的文件的访问。
public class CachedFileProvider extends ContentProvider {
public static final String AUTHORITY = "com.yourpackage.gmailattach.provider";
private UriMatcher uriMatcher;
@Override
public boolean onCreate() {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY, "*", 1);
return true;
}
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
switch (uriMatcher.match(uri)) {
case 1:// If it returns 1 - then it matches the Uri defined in onCreate
String fileLocation = AppCore.context().getCacheDir() + File.separator + uri.getLastPathSegment();
ParcelFileDescriptor pfd = ParcelFileDescriptor.open(new File(fileLocation), ParcelFileDescriptor.MODE_READ_ONLY);
return pfd;
default:// Otherwise unrecognised Uri
throw new FileNotFoundException("Unsupported uri: " + uri.toString());
}
}
@Override public int update(Uri uri, ContentValues contentvalues, String s, String[] as) { return 0; }
@Override public int delete(Uri uri, String s, String[] as) { return 0; }
@Override public Uri insert(Uri uri, ContentValues contentvalues) { return null; }
@Override public String getType(Uri uri) { return null; }
@Override public Cursor query(Uri uri, String[] projection, String s, String[] as1, String s1) { return null; }
}
然后写入临时文件
File tempDir = getContext().getCacheDir();
File tempFile = File.createTempFile("values", ".csv", tempDir);
fout = new FileOutputStream(tempFile);
fout.write(bytes);
fout.close();
然后将其传递给电子邮件Intent
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://" +
CachedFileProvider.AUTHORITY + "/" + tempFile.getName()));
并且不要忘记将其添加到 list 中
<provider android:name="CachedFileProvider" android:grantUriPermissions="true"
android:authorities="yourpackage.provider"></provider>
关于java - 如何从 Android 应用程序发送文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26499380/