【发布时间】:2021-03-23 17:52:47
【问题描述】:
我将我的 targetSdkVersion 更新为 30,因此我必须使用 SAF(存储访问框架)更新我的创建文件。
我能够创建文件、选择位置、获取 Uri 结果(格式为 content://),但是当我尝试将文件作为附件发送时,文件未附加。例如,Gmail 会显示一条消息“无法附加文件”。
我错过了什么吗?
任何帮助将不胜感激。谢谢大家
这是我的代码:
int WRITE_REQUEST_CODE = 336;
private void createFile() {
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("application/pdf");
intent.putExtra(Intent.EXTRA_TITLE, "dettaglio_utente.pdf");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(intent, WRITE_REQUEST_CODE);
}
private void alterDocument(Uri uri) {
try {
ParcelFileDescriptor pfd = getContentResolver().
openFileDescriptor(uri, "w");
FileOutputStream fileOutputStream =
new FileOutputStream(pfd.getFileDescriptor());
byte[] pdfAsBytes = Base64.decode(pdfBase64, 0);
fileOutputStream.write(pdfAsBytes);
// Let the document provider know you're done by closing the stream.
fileOutputStream.close();
pfd.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (resultCode == RESULT_OK && requestCode == WRITE_REQUEST_CODE) {
try {
if (data != null && data.getData() != null) {
Uri path = data.getData();
alterDocument(path);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setData(Uri.parse("mailto:")); // only email apps should handle this
intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.privacy_mail_subject));
intent.putExtra(Intent.EXTRA_TEXT, getString(R.string.privacy_mail_body));
intent.putExtra(Intent.EXTRA_STREAM, path);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
} catch (Exception e) {
Toast.makeText(this, "something went wrong" + e.getMessage(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
我还在 Manifest 中添加了 DocumentProvider,如 Android 文档 StorageProvider 所示
<provider
android:name=".MyDocumentProvider"
android:authorities="${applicationId}.documents"
android:enabled="true"
android:exported="true"
android:grantUriPermissions="true"
android:permission="android.permission.MANAGE_DOCUMENTS">
<intent-filter>
<action android:name="android.content.action.DOCUMENTS_PROVIDER" />
</intent-filter>
</provider>
【问题讨论】:
标签: android storage-access-framework