後,我使用此代碼複製使用documentFile.createFile()
ContentResolver的不包含剛創建圖像中的即時查詢創建文件
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++) {
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();
}
}
的圖像,並且這是我的查詢ContentResolver
創建圖像後,對立即刷新我的圖片庫,其查詢結果應包含新創建圖像的信息。
cursorPhotos = MainActivity.this.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projectionsImages,
null,
null,
MediaStore.Images.Media.DATE_TAKEN + " DESC"
);
但是,立即查詢無法找到新創建的圖像。 如果我稍後再次運行查詢,則新創建的圖像會出現在結果中。
它似乎爲新創建的圖像提供信息需要時間爲ContentResolver
(如果ContentResolver負責它),因爲它將在後臺運行,而我運行立即查詢。
是否有任何方法或聽衆知道新創建的圖像何時由ContentResolver
註冊?
您是在複製異步任務內的圖像還是在主UI線程上? – Rahulrr2602
@ Rahulrr2602是的,看到答案。 – Eftekhari
非常感謝。如果我多次循環newcopyFile方法,那麼有時documentFileGoal爲null。 – Rahulrr2602