以下代码用于在 sdcard(外部存储)中创建的文件中写入联系人详细信息:
try {
while (phones.isAfterLast() == false) {
String lookupKey = phones.getString(phones
.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(
ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor fd;
fd = mContext.getContentResolver().openAssetFileDescriptor(uri, "r");
FileInputStream fis = fd.createInputStream();
byte[] buf = readBytes(fis);
fis.read(buf);
String VCard = new String(buf);
FileOutputStream mFileOutputStream = new FileOutputStream(
cpath, true);
mFileOutputStream.write(VCard.getBytes());
phones.moveToNext();
}
} catch (Exception e1) {
Applog.e(TAG, e1);
isOk = false;
}
其中,cpath是我的文件在 sd 卡中的路径。
在这里,我在线收到错误:
FileOutputStream mFileOutputStream = new FileOutputStream(
cpath, true);
我得到以下日志: -
java.io.FileNotFoundException: /storage/9016-4EF8/AllBackupDemo/cont20181031050512.vcf (Permission denied)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:287)
at java.io.FileOutputStream.<init>(FileOutputStream.java:223)
at java.io.FileOutputStream.<init>(FileOutputStream.java:142)
文档树选择代码:
private void triggerStorageAccessFramework() {
startActivityForResult(new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE), REQUEST_SAF_PERMISSION);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Log.e(TAG, "onActivityResult(" + requestCode + "," + resultCode + "," + data + ")");
if (resultCode == RESULT_CANCELED) return;
switch (requestCode) {
case REQUEST_SAF_PERMISSION:{
Uri treeUri = data.getData();
if(treeUri != null){
session.setPrefURI(treeUri.toString());
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getContentResolver().takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION
| Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
toast(getString(R.string.permission_granted_saf));
break;
}
}
}
笔记:
- 我只在 android oreo 版本中收到此错误。它在牛轧糖中工作正常。
- 我已经授予运行时权限,并且在清单文件中也提到过。
- 我已经为文档文件权限实现了 SAF。