- Как получить доступ к папке данных / данных на устройстве Android?
- Для резервного копирования с Android на рабочий стол
- Чтобы извлечь файл * .ab
- Random Stuff
- Friday, February 1, 2013
- Access Android app data without root
- Data and file storage overview
- Categories of storage locations
- Permissions and access to external storage
- Scoped storage
- View files on a device
- Additional resources
- Videos
Как получить доступ к папке данных / данных на устройстве Android?
Я занимаюсь разработкой приложения и знаю, что моя база данных *.db появится в data/data/com.****.***
Я могу получить доступ к этому файлу из AVD в Eclipse с помощью диспетчера sqlite
Но я не могу получить доступ к этому файлу на своем телефоне Android.
Я гуглю его, и он говорит, что мне нужно рутировать мой телефон, чтобы сделать это, но я не хочу это делать. (Новый телефон, проблемы с гарантией и проблемы с безопасностью)
Итак, вот мой вопрос: как я могу получить доступ к своему data/data/. каталогу в моем телефоне Android » без рутирования «?
Могу ли я изменить пользовательские разрешения для каталога data/data. без рута?
Доступ к файлам непосредственно на вашем телефоне затруднен, но вы можете скопировать их на свой компьютер, где вы сможете делать с ним все, что захотите. Без рута у вас есть 2 варианта:
Если приложение отлаживаемо, вы можете использовать run-as команду в оболочке adb
В качестве альтернативы вы можете использовать функцию резервного копирования Android.
Теперь вам будет предложено «разблокировать устройство и подтвердить операцию резервного копирования». Лучше НЕ предоставлять пароль, иначе становится сложнее читать данные. Просто нажмите «Резервное копирование моих данных». В результате файл «backup.ab» на вашем компьютере содержит все данные приложения в формате резервной копии Android. По сути это сжатый tar-файл. На этой странице объясняется, как вы можете использовать команду OpenSSL zlib для ее распаковки. Вы можете использовать adb restore backup.db команду для восстановления резервной копии.
Если вы используете Android Studio 3.0 или более позднюю версию, выполните следующие действия.
- Нажмите « Просмотр» > « Инструмент Windows» > « Обозреватель файлов устройства» .
- Разверните / data / data / [имя-пакета] узлы.
Вы можете разворачивать пакеты, которые работают в режиме отладки, только на некорневом устройстве.
Вы также можете попробовать получить базу данных с помощью приложения root explorer. И если это не работает, то вы можете попробовать это:
- Открыть cmd
- Измените каталог и перейдите в «Инструменты платформы»
- Тип ‘ adb shell ‘
- su
- Нажмите «Разрешить» на устройстве
- chmod 777 /data /data/data /data/data/com.application.package /data/data/com.application.package/*
- Откройте представление DDMS в Eclipse и оттуда откройте FileExplorer, чтобы получить нужный файл
После этого вы сможете просматривать файлы на рутированном устройстве.
Чтобы сделать что-либо из вышеперечисленного (например, получить доступ к защищенным папкам из самого телефона), вам все еще нужен root. (Это включает изменение разрешений на монтирование для папки / data и доступ к ней)
Без root невозможно получить /data прямой доступ для чтения, кроме как из вашего приложения через код. Таким образом, вы можете попробовать скопировать этот файл на SDCard или куда-нибудь доступный, и тогда вы сможете получить к нему обычный доступ.
Rooting не аннулирует вашу гарантию, если у вас есть устройство разработчика. Извините, по-другому, AFAIK, нет.
Самый простой способ (всего один простой шаг) извлечь файл из папки отлаживаемого приложения (скажем /data/data/package.name/databases/file ) на некорневом устройстве Android 5.0+ с помощью этой команды:
- Откройте командную строку
- Перейдите в каталог E: \ Android \ adt-bundle-windows-x86_64-20140702 \ adt-bundle-windows-x86_64-20140702 \ sdk \ platform-tools
- Введите ниже команды
- adb -d shell
- run-as com.your.packagename cat databases/database.db > /sdcard/database.db
- Перейдите в каталог, чтобы cd /sdcard убедиться, что database.db он есть.
- adb pull /sdcard/database.db или просто вы можете скопировать database.db с устройства.
Используйте Проводник в затмении. Выберите Windows => Показать представление => Прочее . => Проводник.
Другой способ — извлечь файл через adb:
У меня тоже была одна и та же проблема. Невозможно получить прямой доступ к файлу на устройствах Android, кроме оболочки adb или рутирующего устройства.
Кроме того, здесь есть 2 варианта:
Для резервного копирования с Android на рабочий стол
Откройте командную строку cmd и запустите: adb backup -f C: \ Intel \ xxx.ab -noapk your.app.package . Не вводите пароль и нажмите Резервное копирование моих данных. Убедитесь, что вы не сохранили на диске C root. Вам может быть отказано. Вот почему я сохранил на C: \ Intel.
Чтобы извлечь файл * .ab
- Зайдите сюда и загрузите: https://sourceforge.net/projects/adbextractor/
- Распакуйте загруженный файл и перейдите в папку, в которую вы распаковали.
- запустите его со своими собственными именами файлов: java -jar abe.jar распаковать c: \ Intel \ xxx.ab c: \ Intel \ xxx.tar
На рутованном устройстве правильное решение таково:
Исходное решение работало, но chmod возвращал неизвестный каталог. Изменение команды chmod на / data / data / * дало доступ ко всем подпапкам в каталоге данных из DDMS в Intellij. Я предполагаю, что то же решение верно для Eclipse DDMS.
ОБНОВЛЕНИЕ Итак, то, что я нашел, странно. Я использую Nexus 6, используя DDMS в IntelliJ (Android Device Monitor). Я построил небольшое приложение для начинающих. Указанное приложение сохраняет данные в файл .csv в data / data / com.example.myapp / files
Когда я впервые начал пытаться получить доступ к этому файлу на своем Nexus 6, я обнаружил, что должен рутировать устройство. Я мог видеть папку данных, но попытка открыть ее не сработала. Как упоминалось в Интернете в других местах, расширение + исчезнет, а затем вскоре появится снова (обратите внимание, что в Интернете есть решения, которые утверждают, что разрешают доступ к этим папкам без рутирования, я не нашел их слишком поздно, и я не уверен, предпочитаю ли я в любом случае не получать root-права ((я бы предпочел сделать это вручную, чем полагаться на приложение или командную строку, чтобы дать мне свои решения))). Я рутировал свои 6 и снова попробовал DDMS.
В этот момент он показал мне папку с данными, и я смог развернуть папку и увидеть ком. каталоги, но я не мог открыть ни один из них. Именно тогда я обнаружил вышеуказанное решение. Начальные инструкции не будут работать на этой части:
Именно тогда я попробовал решение, которое я отправил:
Это решение, похоже, работает, но только для определенных папок. Теперь я могу развернуть папку myapp, но не могу развернуть каталог файлов в ней.
В этот момент я немного поигрался, а потом подумал, почему бы просто не попробовать его в нужном мне каталоге, а не попробовать эти подстановочные знаки.
Эти команды позволили мне развернуть и просмотреть файлы в каталоге моего приложения, чтобы убедиться, что файл .csv был сохранен правильно.
Надеюсь, это кому-нибудь поможет. Я боролся с этим часами!
Источник
Random Stuff
Various ramblings of sysadmin, programmer, dancer, coffee snob, food lover and Winnipegger.
Friday, February 1, 2013
Access Android app data without root
Recently I recommended a certain data collecting Android app to my coworker. The application was great, but it was designed to upload collected data to the cloud and didn’t offer any means to export or backup information locally.
This isn’t an issue on my rooted Galaxy Nexus. Usually, I connect my phone to my computer with USB cable, open CLI and do the following, where app.package.name should be replaced with the actual package name of the application:
Update: after I’ve discovered this neat trick, the above can be reduced to one line:
On my coworker’s phone, however, this wouldn’t work since he was using a stock, non-rooted Android OS.
I Googled around for a solution and seemingly found one. If the application, whose data you wish to access, is debuggable, its read-protected folder can be accessed with the help of the run-as command. In essence, we pretend to be the application in question and copy file(s) stored inside the application’s data folder into user readable folder like so:
Unfortunately, in this case the application was not debuggable, so the method above did not work either. It appeared that reading Android application data folder with root access was impossible.
At this point I remembered that starting with Android v4.0 (Ice Cream Sandwich) Google has provided a way to backup data and applications from Android devices without root via adb. So all I had to do in order to pull that application’s data from the device is to run:
This will prompt you to «unlock your device and confirm the backup operation». To keep things simple do not provide a password, otherwise you will have to jump through the hoops to decrypt it later. Just click on «Back up my data» button. The screen will display the name of the package you’re backing up, then close by itself upon successful completion.
The resulting «.ab» file contains application data in android backup format, which, thanks to +Nikolay Elenkov, is very well explained and documented in his excellent blog post. Basically, it’s a tar archive that has been run through deflate and optionally encrypted (in a somewhat peculiar way) by AES-256-CRC cypher. Nikolay even went as far as to write a convenient Java program that can pack and unpack such Android backups with and without encryption.
To quickly extract a simple non-encrypted backup (you did omit the backup password as I suggested, didn’t you?) run:
Update: It was brought to my attention that not all openssl installations are compiled with zlib support. Here’s an alternative one-liner that makes use of python to achieve the same result:
The result is the apps/app.package.name/ folder containing application data, such as SQLite database I was particularly interested in and the application preferences.
Update: A few people mentioned in comments below and on StackOverflow that this method doesn’t work if application developer has explicitly disabled ability to backup his app by setting android:allowBackup="false" in the application manifest.
Источник
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.
Источник