我正在尝试使用Storage access Framework在我的应用程序中提供SD卡访问。
这就是我如何调用一个意图,让用户选择SD卡目录。
private void openDocumentTree() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
intent.addFlags(
Intent.FLAG_GRANT_READ_URI_PERMISSION
| Intent.FLAG_GRANT_WRITE_URI_PERMISSION
| Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
| Intent.FLAG_GRANT_PREFIX_URI_PERMISSION);
startActivityForResult(intent, REQUEST_CODE_OPEN_DOCUMENT_TREE);
}下面是我如何管理意图结果来设置权限:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_OPEN_DOCUMENT_TREE:
if (resultCode == Activity.RESULT_OK) {
Uri treeUri = data.getData();
int takeFlags = data.getFlags();
takeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION |
Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
this.getContentResolver().takePersistableUriPermission(treeUri, takeFlags);
}
}
}但是仍然不能在SD卡上保存任何文件。
我的设备上的treeUri的值是:
content://com.android.externalstorage.documents/tree/6921-B9FD%3A
这里我错过了什么,系统仍然不能让用户访问SD卡(在SD卡上保存一个简单的文件)?
发布于 2016-07-25 22:15:49
好的。这就是我如何复制图像在SD卡上提供的权限,调用文件选择器来选择SD卡目录的用户(这可能是用户选择了一个错误的目录,因此为它准备你的代码)。
private void newcopyFile(File fileInput, String outputParentPath,
String mimeType, String newFileName) {
DocumentFile documentFileGoal = DocumentFile.fromTreeUri(this, treeUri);
String[] parts = outputParentPath.split("\\/");
for (int i = 3; i < parts.length; i++) { //ex: parts:{"", "storage", "extSdCard", "MyFolder", "MyFolder", "MyFolder"}
if (documentFileGoal != null) {
documentFileGoal = documentFileGoal.findFile(parts[i]);
}
}
if (documentFileGoal == null) {
Toast.makeText(MainActivity.this, "Directory not found", Toast.LENGTH_SHORT).show();
return;
}
DocumentFile documentFileNewFile = documentFileGoal.createFile(mimeType, newFileName);
InputStream inputStream = null;
OutputStream outputStream = null;
try {
outputStream = getContentResolver().openOutputStream(documentFileNewFile.getUri());
inputStream = new FileInputStream(fileInput);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
if (outputStream != null) {
byte[] buffer = new byte[1024];
int read;
if (inputStream != null) {
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
}
if (inputStream != null) {
inputStream.close();
}
inputStream = null;
outputStream.flush();
outputStream.close();
outputStream = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}注:阅读问题下的所有comments。
如果您想要在新创建的映像在ContentResolver中注册时收到通知,请注意setting a ContentObserver to your ContentResolver,因此是时候查询它了(如果您愿意)。
https://stackoverflow.com/questions/38490719
复制相似问题