Data and file storage overview
Android uses a file system that’s similar to disk-based file systems on other platforms. The system provides several options for you to save your app data:
- App-specific storage: Store files that are meant for your app’s use only, either in dedicated directories within an internal storage volume or different dedicated directories within external storage. Use the directories within internal storage to save sensitive information that other apps shouldn’t access.
- Shared storage: Store files that your app intends to share with other apps, including media, documents, and other files.
- Preferences: Store private, primitive data in key-value pairs.
- Databases: Store structured data in a private database using the Room persistence library.
The characteristics of these options are summarized in the following table:
Type of content | Access method | Permissions needed | Can other apps access? | Files removed on app uninstall? | |
---|---|---|---|---|---|
App-specific files | Files meant for your app’s use only | From internal storage, getFilesDir() or getCacheDir() From external storage, getExternalFilesDir() or getExternalCacheDir() | Never needed for internal storage Not needed for external storage when your app is used on devices that run Android 4.4 (API level 19) or higher | No | Yes |
Media | Shareable media files (images, audio files, videos) | MediaStore API | READ_EXTERNAL_STORAGE when accessing other apps’ files on Android 11 (API level 30) or higher READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE when accessing other apps’ files on Android 10 (API level 29) Permissions are required for all files on Android 9 (API level 28) or lower | Yes, though the other app needs the READ_EXTERNAL_STORAGE permission | No |
Documents and other files | Other types of shareable content, including downloaded files | Storage Access Framework | None | Yes, through the system file picker | No |
App preferences | Key-value pairs | Jetpack Preferences library | None | No | Yes |
Database | Structured data | Room persistence library | None | No | Yes |
The solution you choose depends on your specific needs:
How much space does your data require? Internal storage has limited space for app-specific data. Use other types of storage if you need to save a substantial amount of data. How reliable does data access need to be? If your app’s basic functionality requires certain data, such as when your app is starting up, place the data within internal storage directory or a database. App-specific files that are stored in external storage aren’t always accessible because some devices allow users to remove a physical device that corresponds to external storage. What kind of data do you need to store? If you have data that’s only meaningful for your app, use app-specific storage. For shareable media content, use shared storage so that other apps can access the content. For structured data, use either preferences (for key-value data) or a database (for data that contains more than 2 columns). Should the data be private to your app? When storing sensitive data—data that shouldn’t be accessible from any other app—use internal storage, preferences, or a database. Internal storage has the added benefit of the data being hidden from users.
Categories of storage locations
Android provides two types of physical storage locations: internal storage and external storage. On most devices, internal storage is smaller than external storage. However, internal storage is always available on all devices, making it a more reliable place to put data on which your app depends.
Removable volumes, such as an SD card, appear in the file system as part of external storage. Android represents these devices using a path, such as /sdcard .
Apps themselves are stored within internal storage by default. If your APK size is very large, however, you can indicate a preference within your app’s manifest file to install your app on external storage instead:
Permissions and access to external storage
On earlier versions of Android, apps needed to declare the READ_EXTERNAL_STORAGE permission to access any file outside the app-specific directories on external storage. Also, apps needed to declare the WRITE_EXTERNAL_STORAGE permission to write to any file outside the app-specific directory.
More recent versions of Android rely more on a file’s purpose than its location for determining an app’s ability to access, and write to, a given file. In particular, if your app targets Android 11 (API level 30) or higher, the WRITE_EXTERNAL_STORAGE permission doesn’t have any effect on your app’s access to storage. This purpose-based storage model improves user privacy because apps are given access only to the areas of the device’s file system that they actually use.
Android 11 introduces the MANAGE_EXTERNAL_STORAGE permission, which provides write access to files outside the app-specific directory and MediaStore . To learn more about this permission, and why most apps don’t need to declare it to fulfill their use cases, see the guide on how to manage all files on a storage device.
Scoped storage
To give users more control over their files and to limit file clutter, apps that target Android 10 (API level 29) and higher are given scoped access into external storage, or scoped storage, by default. Such apps have access only to the app-specific directory on external storage, as well as specific types of media that the app has created.
Use scoped storage unless your app needs access to a file that’s stored outside of an app-specific directory and outside of a directory that the MediaStore APIs can access. If you store app-specific files on external storage, you can make it easier to adopt scoped storage by placing these files in an app-specific directory on external storage. That way, your app maintains access to these files when scoped storage is enabled.
To prepare your app for scoped storage, view the storage use cases and best practices guide. If your app has another use case that isn’t covered by scoped storage, file a feature request. You can temporarily opt-out of using scoped storage.
View files on a device
To view the files stored on a device, use Android Studio’s Device File Explorer.
Additional resources
For more information about data storage, consult the following resources.
Videos
Content and code samples on this page are subject to the licenses described in the Content License. Java is a registered trademark of Oracle and/or its affiliates.
Источник
lopspower / README.md
All Android Directory Path
1) System directories
⚠️ We can’t write to these folers
Method | Result |
---|---|
Environment.getDataDirectory() | /data |
Environment.getDownloadCacheDirectory() | /cache |
Environment.getRootDirectory() | /system |
2) External storage directories
⚠️ Need WRITE_EXTERNAL_STORAGE Permission
Method | Result |
---|---|
Environment.getExternalStorageDirectory() | /storage/sdcard0 |
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_ALARMS) | /storage/sdcard0/Alarms |
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) | /storage/sdcard0/DCIM |
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) | /storage/sdcard0/Download |
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) | /storage/sdcard0/Movies |
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC) | /storage/sdcard0/Music |
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_NOTIFICATIONS) | /storage/sdcard0/Notifications |
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) | /storage/sdcard0/Pictures |
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PODCASTS) | /storage/sdcard0/Podcasts |
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_RINGTONES) | /storage/sdcard0/Ringtones |
3) Application directories
Method | Result |
---|---|
getCacheDir() | /data/data/package/cache |
getFilesDir() | /data/data/package/files |
getFilesDir().getParent() | /data/data/package |
4) Application External storage directories
Источник
android получить реальный путь по Uri.getPath()
Я пытаюсь получить изображение из галереи.
после того, как я вернулся из этой деятельности у меня есть данные, которые содержат Uri. Это выглядит так:
как я могу преобразовать этот путь в реальный (так же, как’ /sdcard/image.png ‘)?
9 ответов:
это действительно необходимо для вас, чтобы получить физический путь?
Например, ImageView.setImageURI() и ContentResolver.openInputStream() позволит вам получить доступ к содержимому файла, не зная его реальный путь.
Примечание: managedQuery() метод устарел, поэтому я его не использую.
последнее редактирование: улучшение. Мы должны закрыть курсор!!
@Rene Juuse-выше в комментариях. Спасибо за эту ссылку !
. код для получения реального пути немного отличается от одного SDK к другому, поэтому ниже мы имеем три метода, которые имеют дело с различными SDK.
getRealPathFromURI_API19 (): возвращает реальный путь для API 19 (или выше, но не протестирован) getRealPathFromURI_API11to18 (): возвращает реальный путь для API 11 в API 18 getRealPathFromURI_below11 (): возвращает реальный путь для API ниже 11
обновление 2016 марта
чтобы исправить все проблемы с путем изображений я пытаюсь создать пользовательскую галерею, как facebook и другие приложения. Это потому, что вы можете использовать только локальные файлы ( реальные файлы , а не виртуальные или временные), я решаю все проблемы с этой библиотекой.
https://github.com/nohana/Laevatein (эта библиотека, чтобы сделать снимок с камеры или выбрать из галереи , если вы выбираете из галереи у него есть ящик с альбомами и просто показать локальные файлы)
Примечание это улучшение в @user3516549 ответ и я должен проверить его на Moto G3 с Android 6.0.1
У меня есть эта проблема, поэтому я попытался ответить на @user3516549, но в некоторых случаях он не работал должным образом. Я обнаружил, что в Android 6.0(или выше) при запуске gallery image pick intent откроется экран, который показывает последние изображения, когда пользователь выбирает изображение из этого списка, мы получим uri как
в то время как если пользователь выбирает галерея из выдвижного ящика вместо недавнего, то мы получим uri как
так что я должен справиться с этим в getRealPathFromURI_API19()
EDIT: если вы пытаетесь получить путь к изображению файла во внешней sdcard в более высокой версии, то проверьте у меня вопрос
нет никакого реального пути.
A Uri с content схема является непрозрачным дескриптором для некоторого содержимого. Если что Uri представляет собой открытый контент, вы можете использовать ContentResolver и openInputStream() для получения InputStream на этот контент. Кроме того, Uri с http или https схема не представляет локальный файл, и вам нужно будет использовать API HTTP-клиента для доступа к нему.
только a Uri с file схема идентифицирует файл (за исключением случаях, когда файл был перемещен или удален после ).
что делают глупые люди, это пытаются получить путь к файловой системе, пытаясь декодировать содержимое Uri , возможно, в сочетании с заклинаниями для вызова $EVIL_DEITY . В лучшем случае, это будет ненадежно, по трем причинам:
правила декодирования Uri значения могут меняться с течением времени, например, с выпусками версий Android, как структура Uri представляет деталь реализации, а не интерфейс
даже если вы получаете путь к файловой системе, у вас может не быть прав доступа к файлу
не все Uri значения могут быть декодированы с помощью фиксированных алгоритмов, так как многие приложения имеют своих поставщиков, а те могут указать на все активы BLOB столбцы для данных, которые должны быть переданы из интернета
если у вас есть некоторые ограниченные API, что требуется файл, используйте InputStream С openInputStream() создать копию этого контента. Является ли это временной копией (например, используется для операции загрузки файла, а затем удаляется) или прочной копией (например, для функции «импорт» вашего приложения) зависит от вас.
во-первых, спасибо за ваше решение @luizfelipetx
Я немного изменил ваше решение. Это работает для меня:
Примечание: таким образом, мы получили документы и изображения, в зависимости от того, если изображение приходит из «recents», «галерея» или что-либо еще. Поэтому я сначала извлекаю идентификатор изображения, прежде чем искать его.
Hii вот мой полный код для получения изображения с камеры или galeery
/ / мое объявление переменной
это помогло мне получить uri из галереи и конвертировать в файл для многоступенчатой загрузки
Попробуй Такое
тем не менее, если вы получаете проблему, чтобы получить реальный путь, вы можете попробовать мои ответы. Выше ответы мне не помогли.
объяснение: — этот метод получает URI, а затем проверить уровень API вашего Android устройства после этого в соответствии с уровнем API он будет генерировать реальный путь. код для генерации реального пути отличается в зависимости от уровней API.
Источник