- Правильная работа с БД в Android
- Об открытости данных в Android-приложениях
- Access media files from shared storage
- Kotlin
- Request necessary permissions
- Storage permission
- Scoped storage enabled
- Scoped storage unavailable
- Media location permission
- Check for updates to the media store
- Query a media collection
- Kotlin
- Load file thumbnails
- Kotlin
- Open a media file
- File descriptor
- Kotlin
- File stream
- Kotlin
- Direct file paths
- Considerations when accessing media content
- Cached data
- Performance
- DATA column
- Storage volumes
- Kotlin
- Location where media was captured
- Photographs
- Kotlin
- Videos
- Kotlin
- Sharing
- App attribution of media files
- Add an item
- Kotlin
- Toggle pending status for media files
- Kotlin
- Give a hint for file location
- Update an item
- Kotlin
- Update in native code
- Kotlin
- Update other apps’ media files
- Kotlin
- Remove an item
- Kotlin
- Detect updates to media files
- Manage groups of media files
- Kotlin
- Kotlin
- Media management permission
- Use cases that require an alternative to media store
- Work with other types of files
- File sharing in companion apps
- Additional resources
- Samples
- Videos
Правильная работа с БД в Android
Приветствую всех дроидеров в эти непростые для нас времена.
Честно говоря, заколебала эта шумиха о патентах, войнах и т.д., но в данной статье речь пойдет не об этом.
Я не собирался писать статью на данную тему, так как везде всего полно о работе с базой данных в Android и вроде бы все просто, но уж очень надоело получать репорты об ошибках, ошибках специфичных и связанных с БД.
Поэтому, я рассматрю пару моментов с которыми я столкнулся на практике, чтобы предостеречь людей, которым только предстоит с этим разбираться, а дальше жду ваших комментариев на тему решения указанных проблем после чего внесу изменения в пост и мы сделаем отличный туториал, который будет образцом работы с SQLite в Android не только для начинающих, но и для тех, кто уже знаком с основами и написал простые приложения.
Способы работы с БД
Существует три способа работы с данными в БД, которые сразу бросаются на ум:
1) Вы создаете пустую структуру базы данных. Пользователь работает с приложением(создает заметки, удаляет их) и база данных наполняется. Примером может служить приложение NotePad в демо-примерах developer.android.com или на вашем дроид-девайсе.
2) Вы уже имеете готовую БД, наполненную данными, которую нужно распространять с приложением, либо парсите данные из файла в assets.
3) Получать данные из сети, по мере необходимости.
Если есть какой-то еще один или два способа, то с радостью дополню данный список с вашей помощью.
Все основные туториалы расчитаны как раз на первый случай. Вы пишите запрос на создание структуры БД и выполняете этот запрос в методе onCreate() класса SQLiteOpenHelper, например так:
Примерно так. Более полный вариант класса и других составляющих можно посмотреть по ссылке внизу статьи.
Дополнительно можно переопределить методы onOpen(), getReadableDatabase()/getWritableDatаbase(), но обычно хватает того, что выше и методов выборки данных.
Далее, экземпляр этого класса создаем в нашем приложении при его запуске и выполняем запросы, то бишь проблемная часть пройдена. Почему она проблемная? Потому что, когда пользователь качает приложения с маркета, то не задумывается о вашей базе данных и может произойти что угодно. Скажем сеть пропала или процесс другой запустился, или вы написали уязвимый к ошибкам код.
Кстати, есть еще один момент, на который стоит обратить внимание. Переменную экземпляра нашего класса можно создать и хранить в объекте Application и обращаться по мере необходимости, но нужно не забывать вызывать метод close(), так как постоянный коннект к базе — это тяжелый ресурс. Кроме того могут быть коллизии при работе с базой из нескольких потоков.
Но есть и другой способ, например, создавать наш объект по мере необходимости обращения к БД. Думаю это вопрос предпочтения, но который также необходимо обсудить.
А теперь самое главное. Что, если нам понадобилось использовать уже сушествующую БД с данными в приложении?
Немного погуглив, Вы сразу наткнетесь на такую «замечательную статью» — www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications в которой, как покажется, есть нужная панацея. Но не тут то было. В ней еще и ошибок несколько.
Вот они:
1) В методе createDataBase() строка:
SQLiteDatabase dbRead = getReadableDatabase();
и далее код… содержит crash приложения на НТС Desire, потому что получаем БД для чтения(она создается), но не закрывается.
Добавляем строкой ниже dbRead.close() и фикс готов, но момент спорный.
Вот что говорит дока на тему метода getReadableDatabase():
Create and/or open a database. This will be the same object returned by getWritableDatabase() unless some problem, such as a full disk, requires the database to be opened read-only. In that case, a read-only database object will be returned. If the problem is fixed, a future call to getWritableDatabase() may succeed, in which case the read-only database object will be closed and the read/write object will be returned in the future.
Like getWritableDatabase(), this method may take a long time to return, so you should not call it from the application main thread, including from ContentProvider.onCreate().
И так. Данный метод не стоит вызывать в главном потоке приложения. В остальном все понятно.
2) Ошибка: No such table android_metadata. Автор поста выкрутился, создав данную таблицу заранее в БД. Не знаю на сколько это правильный способ, но данная таблица создается в каждой sqlite-бд системой и содержит текущую локаль.
3) Ошибка: Unable to open database file. Здесь много мнений, разных мнений, которые Вы можете прочесть по ссылкам ниже.
Возможно, что проблемы связаны с тем, что один поток блокирует БД и второй не может к ней обратиться, возможно проблема в правах доступа к приложению(было замечено, что чаще проблемы с БД проявляются на телефонах марки НТС именно на тех моделях, которые нельзя рутануть, хотя не только на них, например на планшетах Асер), но как бы то ни было проблемы эти есть.
Я склоняюсь к варианту, что проблема в потоках, не зря ведь нам не рекомендуют вызывать методы создания базы в главном потоке.
Возможно выходом из этого будет следующее решение(рассматривается вариант №2). Используя первый вариант работы с базой, наполнить ее данными после создания, например:
Данный подход еще нужно проверить на практике, но так как этот пост нацелен на выработку верного коллективного решения по данной тематике, то комментарии и пробы на даннную тему только приветствуются.
Мораль истории такова: если вы нашли какой-то хороший кусок кода для вашего решения, то проверьте его, не поленитесь, прежде чем копипастить в свой проект.
Вцелом, данный пост показывает(касательно способа №2) как делать не надо, но и также содержит пару любопытных мыслей.
Метод getReadableDatabase() можно переопределить например так:
Кстати: следуя практике самой платформы, поле первичного ключа стоит называть «_id».
Пишите в комментарии свои используемые практики. Мы сделаем данный пост лучше для всех, а может и мир станет чуточку добрее.
UPD Только что проверил свой подход. Все работает в эмуляторе, но будьте осторожны.
Файлик data.txt лежит в assets такой:
Zametka #1
Zametka #2
Zametka #3
Zametka #4
И класс приложения:
Отмечу, что данный класс используется только для демонстрации и проверки того, что произойдет при вызове методов getReadableDatabase()/getWritableDatabase() и создании базы. В реальных проектах код нужно адаптировать.
Кроме того в базе появилась табличка android_metadata(без моего участия), поэтому указанная выше ошибка решена.
Надеюсь кому-то пригодится.
Любопытные дополнения №1(от хабраюзера Kalobok)
Источник
Об открытости данных в Android-приложениях
Немного информации о том, какие данные в вашем приложении могут быть доступны для других программ и какие меры можно предпринять, чтобы это предотвратить.
Компоненты
Архитектуру Android-приложения можно представить в виде набора компонент (activities, services и пр.) и связей между ними. Android API предоставляет несколько стандартных способов общения между компонентами приложения: старт активити/сервис через контекст, отправка сообщений-интентов, использование ServiceConnection или ContentProvider’а и другое. Обо всём этом можно почитать в любом туториале о передаче данных в Android. Однако, есть один нюанс, о котором, как правило, умалчивается. Речь идет о доступности ваших компонент и данных, передаваемых между ними, для других приложений.
Activity
Для запуска одной из своих активити вы, наверняка, используете специально подготовленный intent:
Используя Context и Class, которые вы передали в конструктор интента, Android определяет package приложения и сам класс нужной активити, после чего запускает её.
Вы также можете попробовать запустить чужую активити, зная ее package name и class name:
Результат — запущенная активити.
Значит ли это, что все активити могут быть запущены сторонним приложением? Нет. Если заменить в предыдущем примере classname на
то мы получим java.lang.SecurityException.
На самом деле разработчик приложения сам решает, какие активити будут доступны, а какие нет, указывая для каждой активити в манифесте тэг android:exported равным true или false соответственно. Значение по умолчанию для этого тега ‒ false, т.е. все активити в AndroidManifest.xml, не имеющие этого тега, доступны только внутри приложения.
Однако, посмотрев на манифест приложения Контакты (например, тут) можно заметить, что у PeopleActivity нет тега android:exported=«true», почему же нам удалось её запустить? Ответ можно найти в официальной документации: если активити содержит какой-либо интент-фильтр, то значением по умолчанию для android:exported будет true.
Разработчику приложения не нужно беспокоиться о видимости своих activity вне приложения до тех пор, пока в какой-либо активити не появляется intent-filter. Как только вы объявляете intent-filter, спросите себя, готовы ли вы к тому, что эта активити может быть запущена кем-либо еще. Если нет — не забудьте указать .
Service
Видимость сервиса определяется также как и видимость активити, и мы бы не стали уделять сервисам отдельный пункт, если бы не одно “но”. В случае с сервисом, его видимость может завести куда дальше, чем незапланированный старт, как в случае с активити. Если в вашем сервисе предусмотрена возможность биндинга, то этой возможностью могут воспользоваться и другие и получить ссылку на ваш сервис через ServiceConnection. Давайте рассмотрим пример подключения к стандартному сервису воспроизведения музыки.
Примечание: следующий пример актуален только на достаточно старых версиях плеера. В свежей версии разработчики разобрались с флагом exported и установили его в false 🙂
После биндинга в переменной boundService будет храниться ссылка на сервис. Далее вы можете воспользоваться java reflection или Android Interface Definition Language (AIDL), чтобы иметь возможность вызывать методы сервиса напрямую, в результате чего можно, например, остановить воспроизведение, если стандартный плеер уже что-то играет.
ContentProvider
Основное предназначение ContentProvider’а — предоставление данных другим приложениям. Именно поэтому по умолчанию значение тега для этого компонента приложения равно true. Но основное предназначение — не единственное. ContentProvider часто используется:
- при реализации подсказок при поиске
- при обмене данных через Sync Adapter
- как уровень абстракции над базой данных
Во всех этих случаях вам, скорее всего, не нужно предоставлять данные вне приложения. Если это действительно так, то не забудьте указать провайдеру .
BroadCast
Общение с помощью широковещательных сообщений можно разделить на 3 этапа:
- Создание intent’а
- Отправка intent’а через Context#sendBroadcast(. )
- Получение intent’а всеми зарегистрированными BroadcastReceiver’ами.
Каждый приёмник (receiver) при регистрации указывает некий IntentFilter, и сообщения будут доставляться этому приёмнику в соответствии с этим фильтром. Как можно догадаться, приёмник сообщения может удовлетворять фильтру и находиться вне нашего приложения. Вы можете добиться приватности рассылаемых сообщений, указав интенту нужный package:
или воспользоваться LocalBroadcastManager (доступен в support library), который также не даст улететь сообщению за границы приложения (на самом деле процесса):
Более того, LocalBroadcastManager позволяет регистрировать приёмники, так что вы можете быть уверены, что получаемые такими приёмниками интенты тоже являются локальными, а не прилетают извне.
Ресурсы
Если коротко, то все используемые в приложении ресурсы доступны для чтения вне приложения. Для получения некоторых из них достаточно знать только package name целевого приложения:
Если вам известна информация об активити внутри приложения, вы можете проделать подобные операции для каждой из них отдельно.
Узнав имя конкретного ресурса, можно получить и его:
Этим способом мы смогли отобразить картинку-превью для виджета Youtube внутри собственного приложения.
Главная загвоздка с ресурсами в том, что здесь нет способа их скрыть. Хранение приватных данных в ресурсах — плохая идея, но если у вас есть такая необходимость, лучше хранить их в зашифрованном виде.
В завершении статьи хотелось бы сказать еще несколько слов о файловой системе в Android. Этот вопрос уже хорошо освещен, многие знают, что в Android для каждого приложения создается собственная директория /data/data/«app package name», доступ к которой имеет только само приложение (или группа приложений c одним sharedUserId). В этой директории находятся файлы настроек SharedPreferences, файлы базы данных приложения, кэш и многое другое, однако, не стоит полагаться на защищенность этого хранилища. Файлы в этой директории недоступны только до тех пор, пока:
Источник
Access media files from shared storage
To provide a more enriched user experience, many apps allow users to contribute and access media that’s available on an external storage volume. The framework provides an optimized index into media collections, called the media store, that allows for retrieving and updating these media files more easily. Even after your app is uninstalled, these files remain on the user’s device.
To interact with the media store abstraction, use a ContentResolver object that you retrieve from your app’s context:
Kotlin
The system automatically scans an external storage volume and adds media files to the following well-defined collections:
- Images, including photographs and screenshots, which are stored in the DCIM/ and Pictures/ directories. The system adds these files to the MediaStore.Images table.
- Videos, which are stored in the DCIM/ , Movies/ , and Pictures/ directories. The system adds these files to the MediaStore.Video table.
- Audio files, which are stored in the Alarms/ , Audiobooks/ , Music/ , Notifications/ , Podcasts/ , and Ringtones/ directories. Additionally, the system recognizes audio playlists that are in the Music/ or Movies/ directories, as well as voice recordings that are in the Recordings/ directory. The system adds these files to the MediaStore.Audio table. The recordings directory isn’t available on Android 11 (API level 30) and lower.
- Downloaded files, which are stored in the Download/ directory. On devices that run Android 10 (API level 29) and higher, these files are stored in the MediaStore.Downloads table. This table isn’t available on Android 9 (API level 28) and lower.
The media store also includes a collection called MediaStore.Files . Its contents depend on whether your app uses scoped storage, available on apps that target Android 10 or higher:
- If scoped storage is enabled, the collection shows only the photos, videos, and audio files that your app has created. Most developers won’t need to use MediaStore.Files to view media files from other apps, but if you have a specific requirement to do so, you can declare the READ_EXTERNAL_STORAGE permission. It’s recommended, however, that you use the MediaStore APIs to open files that your app hasn’t created.
- If scoped storage is unavailable or not being used, the collection shows all types of media files.
Request necessary permissions
Before performing operations on media files, make sure your app has declared the permissions that it needs to access these files. Keep in mind, however, that your app shouldn’t declare permissions that it doesn’t need or use.
Storage permission
The permissions model for accessing media files in your app depends on whether your app uses scoped storage, available on apps that target Android 10 or higher.
Scoped storage enabled
If your app uses scoped storage, it should request storage-related permissions only for devices that run Android 9 (API level 28) or lower. You can apply this condition by adding the android:maxSdkVersion attribute to the permission declaration in your app’s manifest file:
Don’t unnecessarily request storage-related permissions for devices that run Android 10 or higher. Your app can contribute to well-defined media collections, including the MediaStore.Downloads collection, without requesting any storage-related permissions. If you’re developing a camera app, for example, you don’t need to request storage-related permissions because your app owns the images that you’re writing to the media store.
To access files that other apps have created, the following conditions must each be true:
If your app wants to access a file within the MediaStore.Downloads collection that your app didn’t create, you must use the Storage Access Framework. To learn more about how to use this framework, see the guide on how to access documents and other files.
Scoped storage unavailable
If your app is used on a device that runs Android 9 or lower, or if your app has temporarily opted out of scoped storage, you must request the READ_EXTERNAL_STORAGE permission to access media files. If you want to modify media files, you must request the WRITE_EXTERNAL_STORAGE permission, as well.
Media location permission
If your app targets Android 10 (API level 29) or higher, in order for your app to retrieve unredacted Exif metadata from photos, you need to declare the ACCESS_MEDIA_LOCATION permission in your app’s manifest, then request this permission at runtime.
Check for updates to the media store
To access media files more reliably, particularly if your app caches URIs or data from the media store, check whether the media store version has changed compared to when you last synced your media data. To perform this check for updates, call getVersion() . The returned version is a unique string that changes whenever the media store changes substantially. If the returned version is different from the last synced version, rescan and resync your app’s media cache.
Complete this check at app process startup time. There’s no need to check the version each time you query the media store.
Don’t assume any implementation details regarding the version number.
Query a media collection
To find media that satisfies a particular set of conditions, such as a duration of 5 minutes or longer, use an SQL-like selection statement similar to the one shown in the following code snippet:
Kotlin
When performing such a query in your app, keep the following in mind:
- Call the query() method in a worker thread.
- Cache the column indices so that you don’t need to call getColumnIndexOrThrow() each time you process a row from the query result.
- Append the ID to the content URI, as shown in the code snippet.
- Devices that run Android 10 and higher require column names that are defined in the MediaStore API. If a dependent library within your app expects a column name that’s undefined in the API, such as «MimeType» , use CursorWrapper to dynamically translate the column name in your app’s process.
Load file thumbnails
If your app shows multiple media files and requests that the user choose one of these files, it’s more efficient to load preview versions—or thumbnails—of the files instead of the files themselves.
To load the thumbnail for a given media file, use loadThumbnail() and pass in the size of the thumbnail that you want to load, as shown in the following code snippet:
Kotlin
Open a media file
The specific logic that you use to open a media file depends on whether the media content is best represented as a file descriptor, a file stream, or a direct file path:
File descriptor
To open a media file using a file descriptor, use logic similar to that shown in the following code snippet:
Kotlin
File stream
To open a media file using a file stream, use logic similar to that shown in the following code snippet:
Kotlin
Direct file paths
To help your app work more smoothly with third-party media libraries, Android 11 (API level 30) and higher allow you to use APIs other than the MediaStore API to access media files from shared storage. You can instead access media files directly using either of the following APIs:
- The File API.
- Native libraries, such as fopen() .
If you don’t have any storage-related permissions, you can access files in your app-specific directory, as well as media files that are attributed to your app, using the File API.
If your app tries to access a file using the File API and it doesn’t have the necessary permissions, a FileNotFoundException occurs.
To access other files in shared storage on a device that runs Android 10 (API level 29), it’s recommended that you temporarily opt out of scoped storage by setting requestLegacyExternalStorage to true in your app’s manifest file. In order to access media files using native files methods on Android 10, you must also request the READ_EXTERNAL_STORAGE permission.
Considerations when accessing media content
When accessing media content, keep in mind the considerations discussed in the following sections.
Cached data
If your app caches URIs or data from the media store, periodically check for updates to the media store. This check allows your app-side, cached data to stay in sync with the system-side, provider data.
Performance
When you perform sequential reads of media files using direct file paths, the performance is comparable to that of the MediaStore API.
When you perform random reads and writes of media files using direct file paths, however, the process can be up to twice as slow. In these situations, we recommend using the MediaStore API instead.
DATA column
When you access an existing media file, you can use the value of the DATA column in your logic. That’s because this value has a valid file path. However, don’t assume that the file is always available. Be prepared to handle any file-based I/O errors that could occur.
To create or update a media file, on the other hand, don’t use the value of the DATA column. Instead, use the values of the DISPLAY_NAME and RELATIVE_PATH columns.
Storage volumes
Apps that target Android 10 or higher can access the unique name that the system assigns to each external storage volume. This naming system helps you efficiently organize and index content, and it gives you control over where new media files are stored.
The following volumes are particularly useful to keep in mind:
- The VOLUME_EXTERNAL volume provides a view of all shared storage volumes on the device. You can read the contents of this synthetic volume, but you cannot modify the contents.
- The VOLUME_EXTERNAL_PRIMARY volume represents the primary shared storage volume on the device. You can read and modify the contents of this volume.
You can discover other volumes by calling MediaStore.getExternalVolumeNames() :
Kotlin
Location where media was captured
Some photographs and videos contain location information in their metadata, which shows the place where a photograph was taken or where a video was recorded.
To access this location information in your app, use one API for photograph location information and another API for video location information.
Photographs
If your app uses scoped storage, the system hides location information by default. To access this information, complete the following steps:
- Request the ACCESS_MEDIA_LOCATION permission in your app’s manifest.
From your MediaStore object, get the exact bytes of the photograph by calling setRequireOriginal() and pass in the URI of the photograph, as shown in the following code snippet:
Kotlin
Videos
To access location information within a video’s metadata, use the MediaMetadataRetriever class, as shown in the following code snippet. Your app doesn’t need to request any additional permissions to use this class.
Kotlin
Sharing
Some apps allow users to share media files with each other. For example, social media apps give users the ability to share photos and videos with friends.
To share media files, use a content:// URI, as recommended in the guide to creating a content provider.
App attribution of media files
When scoped storage is enabled for an app that targets Android 10 or higher, the system attributes an app to each media file, which determines the files that your app can access when it hasn’t requested any storage permissions. Each file can be attributed to only one app. Therefore, if your app creates a media file that’s stored in the photos, videos, or audio files media collection, your app has access to the file.
If the user uninstalls and reinstalls your app, however, you must request READ_EXTERNAL_STORAGE to access the files that your app originally created. This permission request is required because the system considers the file to be attributed to the previously-installed version of the app, rather than the newly-installed one.
Add an item
To add a media item to an existing collection, call code similar to the following. This code snippet accesses the VOLUME_EXTERNAL_PRIMARY volume on devices that run Android 10 or higher. That’s because, on these devices, you can only modify the contents of a volume if it’s the primary volume, as described in the storage volumes section.
Kotlin
Toggle pending status for media files
If your app performs potentially time-consuming operations, such as writing to media files, it’s useful to have exclusive access to the file as it’s being processed. On devices that run Android 10 or higher, your app can get this exclusive access by setting the value of the IS_PENDING flag to 1. Only your app can view the file until your app changes the value of IS_PENDING back to 0.
The following code snippet builds upon the previous code snippet. The following snippet shows how to use the IS_PENDING flag when storing a long song in the directory corresponding to the MediaStore.Audio collection:
Kotlin
Give a hint for file location
When your app stores media on a device running Android 10, the media is organized based on its type by default. For example, new image files are placed by default in the Environment.DIRECTORY_PICTURES directory, which corresponds to the MediaStore.Images collection.
If your app is aware of a specific location where files should be stored, such as a photo album called Pictures/MyVacationPictures, you can set MediaColumns.RELATIVE_PATH to provide the system a hint for where to store the newly-written files.
Update an item
To update a media file that your app owns, run code similar to the following:
Kotlin
If scoped storage is unavailable or not enabled, the process shown in the preceding code snippet also works for files that your app doesn’t own.
Update in native code
If you need to write media files using native libraries, pass the file’s associated file descriptor from your Java-based or Kotlin-based code into your native code.
The following code snippet shows how to pass a media object’s file descriptor into your app’s native code:
Kotlin
Update other apps’ media files
If your app uses scoped storage, it ordinarily cannot update a media file that a different app contributed to the media store.
It’s still possible to get user consent to modify the file, however, by catching the RecoverableSecurityException that the platform throws. You can then request that the user grant your app write access to that specific item, as shown in the following code snippet:
Kotlin
Complete this process each time your app needs to modify a media file that it didn’t create.
Alternatively, if your app runs on Android 11 or higher, you can allow users to grant your app write access to a group of media files. Call the createWriteRequest() method, as described in the section on how to manage groups of media files.
If your app has another use case that isn’t covered by scoped storage, file a feature request and temporarily opt out of scoped storage.
Remove an item
To remove an item that your app no longer needs in the media store, use logic similar to what’s shown in the following code snippet:
Kotlin
If scoped storage is unavailable or isn’t enabled, you can use the preceding code snippet to remove files that other apps own. If scoped storage is enabled, however, you need to catch a RecoverableSecurityException for each file that your app wants to remove, as described in the section on updating media items.
If your app runs on Android 11 or higher, you can allow users to choose a group of media files to remove. Call the createTrashRequest() method or the createDeleteRequest() method, as described in the section on how to manage groups of media files.
If your app has another use case that isn’t covered by scoped storage, file a feature request and temporarily opt out of scoped storage.
Detect updates to media files
Your app might need to identify storage volumes containing media files that apps added or modified, compared to a previous point in time. To detect these changes most reliably, pass the storage volume of interest into getGeneration() . As long as the media store version doesn’t change, the return value of this method monotonically increases over time.
In particular, getGeneration() is more robust than the dates in media columns, such as DATE_ADDED and DATE_MODIFIED . That’s because those media column values could change when an app calls setLastModified() , or when the user changes the system clock.
Manage groups of media files
On Android 11 and higher, you can ask the user to select a group of media files, then update these media files in a single operation. These methods offer better consistency across devices, and the methods make it easier for users to manage their media collections.
The methods that provide this «batch update» functionality include the following:
createWriteRequest() Request that the user grant your app write access to the specified group of media files. createFavoriteRequest() Request that the user marks the specified media files as some of their «favorite» media on the device. Any app that has read access to this file can see that the user has marked the file as a «favorite». createTrashRequest()
Request that the user place the specified media files in the device’s trash. Items in the trash are permanently deleted after a system-defined time period.
Request that the user permanently delete the specified media files immediately, without placing them in the trash beforehand.
After calling any of these methods, the system builds a PendingIntent object. After your app invokes this intent, users see a dialog that requests their consent for your app to update or delete the specified media files.
For example, here is how to structure a call to createWriteRequest() :
Kotlin
Evaluate the user’s response. If the user provided consent, proceed with the media operation. Otherwise, explain to the user why your app needs the permission:
Kotlin
Media management permission
Users might trust a particular app to perform media management, such as making frequent edits to media files. If your app targets Android 11 or higher and isn’t the device’s default gallery app, you must show a confirmation dialog to the user each time your app attempts to modify or delete a file.
If your app targets Android 12 (API level 31) or higher, you can request that users grant your app access to the Media management special permission. This permission allows your app to do each of the following without needing to prompt the user for each file operation:
To do so, complete the following steps:
Declare the MANAGE_MEDIA permission and the READ_EXTERNAL_STORAGE permission in your app’s manifest file.
In order to call createWriteRequest() without showing a confirmation dialog, declare the ACCESS_MEDIA_LOCATION permission as well.
In your app, show a UI to the user to explain why they might want to grant media management access to your app.
Invoke the ACTION_REQUEST_MANAGE_MEDIA intent action. This takes users to the Media management apps screen in system settings. From here, users can grant the special app access.
Use cases that require an alternative to media store
If your app primarily performs one of the following roles, consider an alternative to the MediaStore APIs.
Work with other types of files
If your app works with documents and files that don’t exclusively contain media content, such as files that use the EPUB or PDF file extension, use the ACTION_OPEN_DOCUMENT intent action, as described in the guide on how to store and access documents and other files.
File sharing in companion apps
In cases where you provide a suite of companion apps—such as a messaging app and a profile app—set up file sharing using content:// URIs. We also recommend this workflow as a security best practice.
Additional resources
For more information about how to store and access media, consult the following resources.
Samples
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.
Источник