![](/img/trans.png)
[英]Android: Cannot read PDF File user selected using BOTH getString() and getPath() from the URI
[英]creating file from uri in android 11 - getPath() not working
我想在 android 11 的 ActivityResultCallback 中從 uri 創建一個文件。我使用uri.getPath()
將傳入的 uri 轉換為文件。 但是,它在 android 11 中不起作用。這是我的代碼:
private void launchGallery (){
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
launcherGallery.launch(intent);
}
ActivityResultLauncher<Intent> launcherGallery = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == RESULT_OK) {
Intent data = result.getData();
if (data != null) {
Uri imageUri = data.getData();
// ---> getPath() won't work in android 11 <---
File file = new File(imageUri.getPath());
// I don't want to display the image in an ImageView.
// I need a file object to pass it to this method to encrypt it
encryptImage(file);
}
}
});
那么,如何從 android 11 中的 uri 創建文件?
簡單地說:你不能。 如果Uri
始終是一個File
,那么 class 的存在就沒有任何意義。 Uri
是指向文件的“指針”,可以作為InputStream
讀取
InputStream inputStream = getContentResolver().openInputStream(uri);
你必須閱讀所有這些字節,如果你真的需要一個File
,那么將這些數據存儲在你的應用Scoped Storage中。 如果您確定這是一個圖像(它在調用 Intent 時聲明) then you may try to convert this data to
Bitmap`。
編輯:我看到你已經添加了encryptImage(..)
方法調用,所以對於舒爾來說,你可以直接從 Uri 而不是File
讀取Uri
Bitmap
占用用戶存儲空間,即使是一段時間
查看這種情況:請注意,當您運行文件選擇器launchGallery()
時,您可以在其中切換文件夾。 可以從例如 Google Drive 中選擇文件,或者如果您已安裝其他網絡存儲(OneDrive、Dropbox 等)。 結果你會得到一個Uri
,但這不是本地存儲上的真實File
。 所以你可以 stream 它(通過網絡/網絡)完全閱讀,它還沒有准備好並且在result
回調調用的那一刻可用(在選擇並返回你的應用程序之后)
順便提一句。 這種可能性不僅限於 Android 11 及更高版本,它更早存在。 只需將Uri
作為“指針”處理,不要假設它指向(本地) File
。 在某些情況下,即使用戶選擇本地文件,您也會通過一些ContentResolver
獲得指向它的Uri
(因此使用 own 讀取數據),因此這不會是文件路徑(不會以file://
開頭)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.