Android find application data files

Где приложения Android хранят данные?

Не могли бы вы перечислить все возможные каталоги, где приложения Android могут хранить данные, предоставив описание, какие данные хранятся в каждом каталоге?

Все приложения (корневые или нет) имеют каталог данных по умолчанию, который является /data/data/

. По умолчанию базы данных приложений, настройки и все остальные данные находятся здесь. Если приложение ожидает, что будут храниться огромные объемы данных, или по другим причинам хочет «быть хорошо со встроенным хранилищем», на SDCard ( Android/data/

) имеется соответствующий каталог .

Кроме того, все приложения могут хранить данные в любом месте на SDCard, поскольку нет никаких ограничений — и многие приложения делают это. Они могут свободно использовать имена каталогов (и они снова используют), что часто затрудняет решение, для чего предназначен весь этот «мусор» на карте, и что из него можно удалить.

Хотя, как отметил Том , root-приложения могут хранить свои данные практически везде на вашем устройстве, они обычно следуют тем же правилам, что и другие приложения.

Вы можете найти общее объяснение иерархии каталогов Android в моем ответе здесь . Для вашего конкретного вопроса я мог бы добавить более подробную информацию о /data/data/

(и соответствующей SD-части):

  • databases/ : здесь идут базы данных приложения
  • lib/ : библиотеки и помощники для приложения
  • files/ : другие связанные файлы
  • shared_prefs/ : настройки и настройки
  • cache/ : ну кеширует

В этом месте может быть еще несколько каталогов или меньше — все зависит от приложения. В своем собственном «домашнем каталоге» (и это то, чем он в основном является, говоря по Linux), они могут размещать файлы там, где они хотят. Обычно эти файлы и каталоги доступны только для самого приложения (и, конечно, для пользователя root) — кроме тех, которые хранятся на SDCard и доступны всем приложениям.

Источник

Edit data folder on Android 11

Android 11 Limitation

Since Android 11, application data folder is invisible to 3rd party apps according to the storage permission change. You can no longer list files directly:

Since QuickEdit 1.7.9, it supports to read the contents under data folder on Android 11, but needs some additional steps to grant permission to data folder.

Edit Files In Data Folder By QuickEdit

Please upgrade QuickEdit to version 1.7.9 and above, then you can use following way to grant QuickEdit read/write permission to data folder:

Navigate to Data Folder

Using QuickEdit built-in file explorer to locate the data folder under internal storage, the path is similar as: /storage/emulated/0/Android/data

Grant Permission to Data Folder

In latest QuickEdit version, a permission grant dialog will show up, please go to root path to internal storage, and click «use this folder» to grant the permission.

Please choose internal storage root folder in this step, not the Android folder or Data folder. The root folder path is: /storage/emulated/0. Normally when you click OK in grant access dialog, it will guide you to the correct folder, you just need to click «use this folder» button.

Access Data Folder as Normal

After the grant access success, you can access data folder as normal.

If the grant access dialog popup again, it means you did not choose the correct folder to grant access, please repeat previous step and choose the root folder of internal storage and try again.

Edit Files In Data Folder By QuickEdit (Legacy)

If you are using QuickEdit old version before 1.7.9, or previous solution not work for you, please try following guide.

Currently system level file management app can view and edit files under data folder on Android 11. You can use system built-in file manager to open the files and assign QuickEdit to edit the file.

Following is the steps how to do this:

Find System File Manager

Please go to Android system settings, find storage section, click it. From the storage page, find «Files» item, and click it. If there are multiple file managers to open it, please make sure to choose «Open with Files» to open it, which is the system file manager app.

Читайте также:  Poweramp для андроид что это

Please see following screenshot for the steps:

Open Data File By QuickEdit

From the files app, please navigate to Android data folder, navigate to the app and file that you want to edit, and click «Floating Action Button with Edit Icon». From the popup app list, choose QuickEdit to edit the file.

Please see following screenshot for the steps:

Edit and Save Data File using QuickEdit

Now you can edit and save the data file as other local files. If there is permission error popup when you saving your modifications, please double confirm that you choose «edit file with» option instead of «open file with» option in the previous step. Only «edit file with» option can give QuickEdit write permission.

Источник

Где приложения хранят свои данные

Андрей Подкин

При использовании приложений под Android иногда появляются вопросы: «А где приложение хранит созданные файлы?», «Можно ли до них достучаться?» и «Удалятся ли файлы при удалении приложения?» Давайте попробуем посмотреть, где же приложение может хранить свои данные и какие последствия это имеет для пользователя.

Внутреннее хранилище данных

Смысл следует непосредственно из названия. Внутреннее хранилище (internal storage) располагается всегда в памяти смартфона вне зависимости от того, есть ли возможность установки карты памяти (и тем более того, вставлена ли она). Эта область памяти является защищенной. Находится в системном разделе /data. По умолчанию все файлы, которые там располагаются, доступны только тому приложению, которое их создало. Разумеется, можно сделать файлы доступными для других приложений, но это надо делать специально. Если приложение не открывает файлы для доступа извне, достучаться к ним можно будет только получив root.

Назначение хранилища понятно: внутренние защищенные данные, к которым не должно быть нерегламентированного доступа. Проблемы (с точки зрения пользователя) могут быть в следующих случаях:

  • Неоправданно большой объем данных. Хочется вынести данные на карту памяти, чтобы сэкономить внутреннее пространство для других нужд, а приложение не дает.
  • По мнению пользователя, регламент доступа к данным должен быть другим, не таким, как предлагает приложение.

Пример: приложение «Лекции по истории России». В приложении хороший контент (и по содержанию, и по качеству звука). Но сохраняется он во внутреннюю память. На бюджетных устройствах, где этой памяти мало, становится затруднительным закачать заранее много лекций, а потом, отключившись от интернета, слушать их. Второй проблемой становится собственно регламент доступа к данным. Даже если ограничиться тематикой истории, у меня есть аудиофайлы, полученные из трех источников: данное приложение, подкасты и аудиоверсии роликов с youtube. Хочется взять и объединить навек в их земной юдоли под владычеством всесильным Властелина Мордора их все в единый плейлист, и слушать его одним аудиоплеером. Но на смартфоне без root это сделать невозможно.

Внешнее хранилище «личных» данных

С точки зрения разработчика, кроме внутреннего хранилища данных, для персональных целей приложения есть еще внешнее хранилище. Оно необязательно размещается на карте памяти. Это может быть и внутренняя память смартфона, но весь раздел с такими данными размещается в общем доступе. В корне раздела есть папка Android/data, а в ней — подпапки с именами пакетов приложений.

Плюсы такого подхода очевидны: данные доступны извне для целей пользователя. А если это карта памяти, то и емкость может быть ограничена только вашими финансами (в продаже уже можно найти карты памяти на 400 гигабайт). Минусы тоже понятны: в любой момент любое приложение (конечно, имеющее разрешение на доступ к «внешним» данным) может взять и стереть чужие файлы. Также файлы будут удалены системой при удалении приложения (или при очистке его данных).

Пример приложения: подкаст-менеджер BeyondPod (более-менее свежей версии, раньше файлы хранились по-другому). Пользователь имеет доступ к скачанным подкастам и может легко удалять их (например, в целях экономии места) или слушать их во внешнем плеере.

Общее внешнее хранилище

Располагается в корне «внешнего» раздела на одном уровне с папкой «Android». Предназначается для хранения данных, разделяемых между разными приложениями. Обычно в документации Google в качестве примера приводят картинки (фото с камеры — папка DCIM). Основная проблема данных файлов: они никогда не удаляются автоматически. Даже если приложение вы удалили.

Пример: мессенджер Telegram. После того, как вы удалили приложение, загруженные файлы никуда не исчезают. Они продолжают спокойно лежать на накопителе данных, занимая драгоценное место.

Как можно удалить файлы, не удаляя приложения

Здесь важно ввести еще одну классификацию файлов приложений. Она справедлива для внутреннего хранилища и для внешнего хранилища личных данных. Все данные делятся на два типа: собственно данные и кэш.

Данные (папка data) — некие файлы, которые, по логике Google, нужны для постоянной работы с ними. Если полностью их удалить, то приложение поведет себя точно так же, как если бы его переустановили (удалили и заново установили). Частичное удаление файлов может не привести ни к каким неприятным последствиям. Но важно понимать, какие конкретно данные вы удаляете (например, очевидно, что скачанные файлы подкастов можно удалять совершенно свободно — это не повлияет на работоспособность подкаст-менеджера).

Читайте также:  Android studio логические или

Кэш — временные данные, которые сформированы в ходе работы приложения и нужны для ускорения этой работы. Например, данные, которые часто нужны в интернете, загружаются и в дальнейшем вместо загрузки открываются локально (разумеется, кэш может обновляться, чтобы не показывать устаревшие данные). Удалять кэш любого приложения можно совершенно спокойно, это штатная операция.

Очистка памяти и кэша вызывается из настроек приложения. Кнопка «Очистить кэш» очищает только кэш, а кнопка «Очистить данные» — и кэш, и данные приложения.

Удаление файлов приложения из общего внешнего хранилища выполняется только вручную. Более того, даже оценка того, от какого приложения эти файлы остались, тоже выполняется вручную.

Источник

Как найти папки data и system на Android: простой путь

Иногда пользователю устройства с системой от Google приходится столкнуться с нетривиальными задачами, решение которых требует сначала найти папки data и system, где находятся важные файлы. Как это сделать на Android, мы расскажем в статье.

В первую очередь, пользователю понадобится файловый менеджер, который показывает не разбивку по мультимедийным данным, а реальное содержание диска. Иногда такие менеджеры встроены в прошивку, в противном же случае можно обратиться в Play Store, где есть и бесплатные варианты.

Далее с помощью него выходим в корень системы, обозначенный как «/». В ряде менеджеров для быстрого доступа к оному есть отдельный пункт в Action Bar, а где-то нужно просто нажать на знак «..» или выбрать «Корень файловой системы». Именно тут на Android и можно обнаружить папки data и system, имена их, кстати, тоже начинаются с косой черты.

Стоит обратить внимание, что данные разделы, особенно второй, содержат критически важную информацию. Если у пользователя имеется root‑доступ и он удалит файлы в папках data и system, это может вызвать проблемы с работоспособностью устройства.

Заметили ошибку? Выделите её и нажмите Ctrl+Enter или сообщите здесь.

Источник

How to store data locally in an Android app

Almost every app we use or develop has to store data for one purpose or another. It’s not all the same data, either — some apps need access to settings, images, and much more. The big question is how to manage this data so that your device can grab only what it needs. Luckily for developers, Android is full of ways to store data, and we’re here to run you through how they work.

For this article, we’ll discuss the different data storage techniques available to Android developers, along with sample code to get you started or to refresh your memory.

Ways to store data

Using Shared Preferences

Shared Preferences is the way to go if you’re saving primitive data as key-value pairs. It requires a key, which is a String, and the corresponding value for the said key. The value can be any of the following: a boolean, float, int, long, or another string.

Your Android device stores each app’s Shared Preferences inside of an XML file in a private directory. Apps can also have more than one Shared Preferences file, and they’re ideally used to store app preferences.

Before you can store data with shared preferences, you must first get a SharedPreferences object. There are two Context methods that you can use to retrieve a SharedPreferences object.

For when your app will have a single preferences file, and

for when your app could have multiple preferences files, or if you prefer to name your SharedPreferences instance.

On getting the SharedPreferences object, you then access its Editor using the edit() method. To actually add a value, use the Editor’s putXXX() method, where XXX is one of Boolean, String, Float, Long, Int, or StringSet. You can also remove a key-value preference pair with remove().

Finally, make sure to call the Editor’s commit() method after putting or removing values. If you don’t call commit, your changes will not be persisted.

For our sample app, we allow the user to specify a SharedPreferences filename. If the user specifies a name, we request for the SharedPreferences with that name; if not, we request the default SharedPreference object.

Unfortunately, there is no way to get a single list of all SharedPreferences files stored by your app. Instead, you will need a static list or access to the SharedPreferences name if you’re storing more than one file.

Читайте также:  Force 4x msaa android что это

You could also save your SharedPreferences names in the default file. If you need to store user preferences, you may want to use the PreferenceActivity or PreferenceFragment command. Just remember that they both use Shared Preferences, too.

Using internal storage

There are plenty of times where you may need to persist data, but you find Shared Preferences too limiting. For example, you may need to persist objects or images in Java. You might also need to persist your data logically with the file system hierarchy. This is where internal storage comes in. It is specifically for when you need to store data on the file system, but you don’t want other apps or users to have access.

This data storage is so private, in fact, that it’s deleted from the device as soon as you uninstall your app.

Using internal storage is similar to saving with any other file system. You can get references to File objects, and you can store data of virtually any type using a FileOutputStream. What sets it apart is the fact that its contents are only accessible by your app.

To get access to your internal file directory, use the Context getFilesDir() method. To create (or access) a directory within this internal file directory, use the getDir(directoryName, Context.MODE_XXX) method. The getDir() method returns a reference to a File object representing the specified directory, creating it first if it doesn’t exist.

In the sample above, if the user-specified filename is empty, we get the base internal storage directory. If the user specifies a name, we get the named directory, creating first if needed.

To read files, use your preferred file reading method. For our example, we read the complete file using a Scanner object. To read a file that’s directly within your internal storage directory (not in any subdirectory), you can use the openFileInput(fileName) method.

Similarly, to access a file for writing directly within the Internal Storage directory, use the openFileOutput(fileName) method. To save files, we use the FileOutputStream write.

As you can see in the image above, the file path is in a folder not accessible by the file manager or other apps. The only exception to this will be if you have a rooted device.

External Storage

Google has made a few key changes to external storage, beginning with Android 10 and continuing in Android 11. To give users better control over their files and cut down on clutter, apps now have scoped access to external storage by default. This means that they can tap into the specific directory on external storage and the media that the app creates.

For more information about requesting scoped directory access, check out this Android developer tutorial.

If your app tries to access a file that it did not create, you will have to permit it to do so every single time. Data you store outside of select folders will also disappear if you delete your app.

Apps are expected to store files in one of two app-specific locations designed for the app’s specific persistent files and cached files, respectively. To access these locations, the app must verify the storage is available (which is not guaranteed, as it is for internal storage). The volume’s state can be queried using:

If MEDIA_MOUNTED is returned, that means you can read and write files to external storage. You will find a number of predefined directories that should aid with logical storage and prevent clutter. These include the likes of DIRECTORY_DOCUMENTS and DIRECTORY_MOVIES.

You can read a full explanation of how to use scoped storage here.

SQLite database

Finally, Android provides support for apps to use SQLite databases for data storage. The databases you create remain specific to your app and can only be accessed inside your app. Of course, you should have at least some knowledge of SQL before you attempt to store data with an SQLite database.

We’ll discuss each of these in turn, and we use data binding techniques for our sample code. Android provides complete support for SQLite databases. The recommended way of creating SQLite databases is to subclass the SQLiteOpenHelper class and override the onCreate() method. For this sample, we create a single table.

Источник

Оцените статью