Get file from storage android

Saving Files

This lesson teaches you to

You should also read

Android uses a file system that’s similar to disk-based file systems on other platforms. This lesson describes how to work with the Android file system to read and write files with the File APIs.

A File object is suited to reading or writing large amounts of data in start-to-finish order without skipping around. For example, it’s good for image files or anything exchanged over a network.

This lesson shows how to perform basic file-related tasks in your app. The lesson assumes that you are familiar with the basics of the Linux file system and the standard file input/output APIs in java.io .

Choose Internal or External Storage

All Android devices have two file storage areas: «internal» and «external» storage. These names come from the early days of Android, when most devices offered built-in non-volatile memory (internal storage), plus a removable storage medium such as a micro SD card (external storage). Some devices divide the permanent storage space into «internal» and «external» partitions, so even without a removable storage medium, there are always two storage spaces and the API behavior is the same whether the external storage is removable or not. The following lists summarize the facts about each storage space.

  • It’s always available.
  • Files saved here are accessible by only your app by default.
  • When the user uninstalls your app, the system removes all your app’s files from internal storage.

Internal storage is best when you want to be sure that neither the user nor other apps can access your files.

  • It’s not always available, because the user can mount the external storage as USB storage and in some cases remove it from the device.
  • It’s world-readable, so files saved here may be read outside of your control.
  • When the user uninstalls your app, the system removes your app’s files from here only if you save them in the directory from getExternalFilesDir() .

External storage is the best place for files that don’t require access restrictions and for files that you want to share with other apps or allow the user to access with a computer.

Tip: Although apps are installed onto the internal storage by default, you can specify the android:installLocation attribute in your manifest so your app may be installed on external storage. Users appreciate this option when the APK size is very large and they have an external storage space that’s larger than the internal storage. For more information, see App Install Location.

Obtain Permissions for External Storage

To write to the external storage, you must request the WRITE_EXTERNAL_STORAGE permission in your manifest file:

Caution: Currently, all apps have the ability to read the external storage without a special permission. However, this will change in a future release. If your app needs to read the external storage (but not write to it), then you will need to declare the READ_EXTERNAL_STORAGE permission. To ensure that your app continues to work as expected, you should declare this permission now, before the change takes effect.

However, if your app uses the WRITE_EXTERNAL_STORAGE permission, then it implicitly has permission to read the external storage as well.

You don’t need any permissions to save files on the internal storage. Your application always has permission to read and write files in its internal storage directory.

Save a File on Internal Storage

When saving a file to internal storage, you can acquire the appropriate directory as a File by calling one of two methods:

getFilesDir() Returns a File representing an internal directory for your app. getCacheDir() Returns a File representing an internal directory for your app’s temporary cache files. Be sure to delete each file once it is no longer needed and implement a reasonable size limit for the amount of memory you use at any given time, such as 1MB. If the system begins running low on storage, it may delete your cache files without warning.

To create a new file in one of these directories, you can use the File() constructor, passing the File provided by one of the above methods that specifies your internal storage directory. For example:

Alternatively, you can call openFileOutput() to get a FileOutputStream that writes to a file in your internal directory. For example, here’s how to write some text to a file:

Читайте также:  Ets 2 android ios

Or, if you need to cache some files, you should instead use createTempFile() . For example, the following method extracts the file name from a URL and creates a file with that name in your app’s internal cache directory:

Note: Your app’s internal storage directory is specified by your app’s package name in a special location of the Android file system. Technically, another app can read your internal files if you set the file mode to be readable. However, the other app would also need to know your app package name and file names. Other apps cannot browse your internal directories and do not have read or write access unless you explicitly set the files to be readable or writable. So as long as you use MODE_PRIVATE for your files on the internal storage, they are never accessible to other apps.

Save a File on External Storage

Because the external storage may be unavailable—such as when the user has mounted the storage to a PC or has removed the SD card that provides the external storage—you should always verify that the volume is available before accessing it. You can query the external storage state by calling getExternalStorageState() . If the returned state is equal to MEDIA_MOUNTED , then you can read and write your files. For example, the following methods are useful to determine the storage availability:

Although the external storage is modifiable by the user and other apps, there are two categories of files you might save here:

Public files Files that should be freely available to other apps and to the user. When the user uninstalls your app, these files should remain available to the user.

For example, photos captured by your app or other downloaded files.

Private files Files that rightfully belong to your app and should be deleted when the user uninstalls your app. Although these files are technically accessible by the user and other apps because they are on the external storage, they are files that realistically don’t provide value to the user outside your app. When the user uninstalls your app, the system deletes all files in your app’s external private directory.

For example, additional resources downloaded by your app or temporary media files.

If you want to save public files on the external storage, use the getExternalStoragePublicDirectory() method to get a File representing the appropriate directory on the external storage. The method takes an argument specifying the type of file you want to save so that they can be logically organized with other public files, such as DIRECTORY_MUSIC or DIRECTORY_PICTURES . For example:

If you want to save files that are private to your app, you can acquire the appropriate directory by calling getExternalFilesDir() and passing it a name indicating the type of directory you’d like. Each directory created this way is added to a parent directory that encapsulates all your app’s external storage files, which the system deletes when the user uninstalls your app.

For example, here’s a method you can use to create a directory for an individual photo album:

If none of the pre-defined sub-directory names suit your files, you can instead call getExternalFilesDir() and pass null . This returns the root directory for your app’s private directory on the external storage.

Remember that getExternalFilesDir() creates a directory inside a directory that is deleted when the user uninstalls your app. If the files you’re saving should remain available after the user uninstalls your app—such as when your app is a camera and the user will want to keep the photos—you should instead use getExternalStoragePublicDirectory() .

Regardless of whether you use getExternalStoragePublicDirectory() for files that are shared or getExternalFilesDir() for files that are private to your app, it’s important that you use directory names provided by API constants like DIRECTORY_PICTURES . These directory names ensure that the files are treated properly by the system. For instance, files saved in DIRECTORY_RINGTONES are categorized by the system media scanner as ringtones instead of music.

Query Free Space

If you know ahead of time how much data you’re saving, you can find out whether sufficient space is available without causing an IOException by calling getFreeSpace() or getTotalSpace() . These methods provide the current available space and the total space in the storage volume, respectively. This information is also useful to avoid filling the storage volume above a certain threshold.

However, the system does not guarantee that you can write as many bytes as are indicated by getFreeSpace() . If the number returned is a few MB more than the size of the data you want to save, or if the file system is less than 90% full, then it’s probably safe to proceed. Otherwise, you probably shouldn’t write to storage.

Note: You aren’t required to check the amount of available space before you save your file. You can instead try writing the file right away, then catch an IOException if one occurs. You may need to do this if you don’t know exactly how much space you need. For example, if you change the file’s encoding before you save it by converting a PNG image to JPEG, you won’t know the file’s size beforehand.

Читайте также:  Led часы для андроид

Delete a File

You should always delete files that you no longer need. The most straightforward way to delete a file is to have the opened file reference call delete() on itself.

If the file is saved on internal storage, you can also ask the Context to locate and delete a file by calling deleteFile() :

Note: When the user uninstalls your app, the Android system deletes the following:

  • All files you saved on internal storage
  • All files you saved on external storage using getExternalFilesDir() .

However, you should manually delete all cached files created with getCacheDir() on a regular basis and also regularly delete other files you no longer need.

Источник

Android Storage: Internal, External, Removable. Часть 1/3

Всем, кто, несмотря ни на что, сумел сделать правильный выбор.

Это перевод серии статей от Mark Murphy из CommonsWare, широко известного на stackoverflow, а так же автора книг “The Busy Coder’s Guide to Android Development”, “Android’s Architecture Components”. Некоторые термины оставлены не переведенными специально.

Internal Storage

Существует много путаницы в отношении модели хранилища Android. Путаницы стало значительно больше с изменениями Android 4.4 в Storage Model, и с тех пор ситуация не улучшилась. Есть бесчисленное множество вопросов на Stack Overflow и тому подобных ресурсах, где люди явно не совсем разбираются в различных моделях хранилищ Android.

То, что пользователи считают Internal Storage

В зависимости от модели вашего устройства пользователи в конечном итоге придут в «Настройки» —> «Хранилище на этом устройстве» (Settings —> Storage on their device) или в эквивалентном месте, и могут видеть экран, который описывает «Внутреннее хранилище».

Пользователь думает, что вся встроенная флешка — это «внутреннее хранилище» (Internal Storage). К счастью, Google начал менять этот термин с Android 8.0, перейдя к «general storage» вместо «internal storage».

Тем не менее, пользователи могут по-прежнему видеть «внутреннее хранилище» в таких местах, как окно проводника в Windows, когда их устройство подключено через USB.

Что Google считает Internal Storage

Увы, то, что видят пользователи это не то же самое, что Android SDK считает «внутренним хранилищем», что приводит к некоторой путанице. Если вы читали документацию на Android по внутреннему хранилищу, то это описание … как минимум туманно (прим. текст изменился со времени написания статьи):

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

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

В Context есть несколько базовых методов, которые предоставляют вам доступ к внутреннему хранилищу, в том числе:

  • getCacheDir()
  • getDir()
  • getDatabasePath()
  • getFilesDir()
  • openFileInput()
  • openFileOutput()

Другие методы будут опираться на них, такие как openOrCreateDatabase() . Другие классы также будут полагаться на них, такие как SQLiteOpenHelper и SharedPreferences .

Где хранится Internal Storage … Иногда

Если вы просматриваете различные сообщения в блогах, ответы на StackOverflow и книги, выпущенные в 2012 году или ранее, вам сообщается, что «внутреннее хранилище» вашего приложения находится по адресу: /data/data/your.application.package.name .

Внутри будут некоторые каталоги, автоматически созданные Android, поскольку вы используете некоторые из методов Context. Например, getFilesDir() возвращает объект File , указывающий на каталог files/ во внутреннем хранилище вашего приложения.

Где хранится Internal Storage … Остальное время

Однако не всегда внутреннее хранилище вашего приложения находится в указанном месте. Для разработчиков есть одно правило, которое вы должны усвоить из этой серии сообщений в блоге, это:

NEVER HARDCODE PATHS.

Время от времени я вижу, что разработчики делают что-то вроде этого:

File f=new File(«/data/data/their.app.package.name/files/foo.txt»);

Это не преступление, это хуже, это — ошибка.

Правильный ход, да и писать меньше:

File f=new File(getFilesDir(), «foo.txt»);

Что еще более важно, внутреннее хранилище не всегда находится в одном месте. Примечательно, что у нас есть понятие отдельных профилей пользователей (separate user profiles), начиная с Android 4.2 для планшетов и Android 5.0 для телефонов. Каждый пользователь получает свое собственное «внутреннее хранилище». Хотя вышеупомянутый каталог по-прежнему используется для основного пользователя, не гарантируется, что он же будет использоваться для вторичных учетных записей.

Исследуем Internal Storage

Device File Explorer tool в Android Studio 3.0+ может просматривать все внутренние хранилища на эмуляторе, а также внутреннее хранилище отлаживаемых приложений на продакшн устройствах.

В командной строке вы можете использовать adb с опцией run-as .

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

adb shell ‘run-as your.application.package.name cp /data/data/your.application.package.name/databases/dbname.db /sdcard’

Обратите внимание, что:

  • Вам нужно будет изменить пункт назначения туда, где на вашем устройстве монтируется внешнее хранилище (показано здесь как /sdcard/ , которое не будет одинаковым на всех устройствах)
  • Возможно, вам придется использовать cat вместо cp на старых устройствах
  • После того, как файл будет находиться на внешнем хранилище, вы сможете использовать adb pull , чтобы загрузить его на свой компьютер, или получить доступ к нему другими обычными способами (например, путем монтирования устройства в качестве диска).
Читайте также:  Update android galaxy note

Ограничения внутреннего хранилища

На старых устройствах Android 1.x и 2.x внутреннее хранилище обычно находилось в выделенном разделе файловой системы, и этот раздел обычно был довольно крошечным. HTC Dream (a.k.a., T-Mobile G1), оригинальное Android-устройство, обладал огромными 70 МБ встроенной памяти для использования всеми приложениями (это не опечатка, в то время мы измеряли память в мегабайтах).

К тому времени, когда вышли 2.3 устройства, внутреннее хранилище могло быть размером 1 ГБ.

Android 3.0 изменил модель хранилища, так как внутреннее хранилище стало больше объемом. У устройств, которые рекламируют как имеющее 4 ГБ, 8 ГБ, 16 ГБ и т.д. пространства для хранения, обычно имелось все это (минус существующее содержимое) доступное для внутреннего хранилища. Мы рассмотрим, что изменилось в Android 3.0 и его влияние на модель хранилища в следующих постах про внешнее хранилище.

Для Android 1.x и 2.x внутреннее хранилище было действительно только для небольших файлов, и вам нужно было использовать внешнее хранилище для всего остального. Android 3.0+ означает, что для большинства устройств и большинства пользователей внутреннее хранилище отлично подходит для файлов, которые не предназначены для обычного использования другими приложениями или доступны пользователю независимо от вашего приложения. Однако некоторые опытные пользователи обнаруживают, что даже on-board flash недостаточна для того, что они хотят хранить, поэтому они переходят на съемные хранилища… которые представляют собой банку с червями (прим. имеются в виду ἕλμινς) — источник многих непредсказуемых и сложных проблем.

F.A.Q. по Internal Storage

Должен ли я делать файлы во внутреннем хранилище World-Readable или World-Writeable?

О, $БОГИ, нет. Используйте FileProvider и обслуживайте этот контент с помощью реализации ContentProvider . После этого вы, по крайней мере, имеете возможность использовать систему разрешений Android для управления доступом к этим файлам, в отличие от вашего варианта, когда любое приложение в системе может испортить эти файлы.

Ну, а как насчет android:sharedUserId ?

android: sharedUserId — это атрибут, который вы можете поместить в манифест, который указывает логический идентификатор пользователя, который будет использоваться для вашего приложения. Любое другое приложение, которое установлено, которое подписывается одним и тем же ключом подписи и запрашивает тот же android:sharedUserId будет использовать одного и того же пользователя Linux с точки зрения безопасности. Эффект заключается в том, что эти два приложения смогут безнаказанно работать с файлами друг друга, так как эти файлы принадлежат одному и тому же пользователю Linux.

Этот атрибут реально предназначен для предварительно установленных приложений, таких как software suite предварительно загруженный производителем устройства, мобильным оператором или разработчиком модифицированной ROM прошивки. В частности, как только вы единожды установите свое приложение, вы не сможете затем безболезненно изменить свое значение android:sharedUserId не заблокировав при этом доступ пользователю к любым существующим файлам… поскольку Android не изменяет права владельца на существующие файлы при изменении учетной записи пользователя Linux, под которой запускается приложение.

Существуют различные риски при одновременном доступе нескольких процессов к файлам. Некоторые подсистемы, такие как SQLite, имеют встроенную логику для решения этой проблемы. Но если вы сами организуете свой собственный доступ к файлу (например, через File и Java I/O), вам нужно что-то делать с одновременным доступом, а это сложно.

Вам также нужно обрабатывать ситуацию, когда одно приложение деинсталлируется, удаляя файлы, которые использовало другое приложение. В модели hub-and-spoke, например, с приложением и набором плагинов, возможно, это не так рискованно. В других моделях, где приложения более равноправны, вы не можете позволить себе потерять данные своего приложения только потому, что пользователь решил удалить какое-то отдельное приложение.

Наконец, вы не знаете, что может принести будущее. Прямо сейчас вы можете рассматривать свой набор приложений в виде набора с тесной связью. Кто-то, кто приобретает эти приложения или приобретает вашу фирму, может пожелать пойти другим путем. Использование возможностей совместного доступа к данным, которые более слабо связаны, например ContentProvider , дает вам большую гибкость. В идеальном мире ваше приложение должно относиться к другим приложениям как к достаточно надежному, но не всегда доступному ресурсу, так же, как к вашему собственному веб-сервису.

Как запретить пользователям rooted устройств доступ к моим файлам во внутреннем хранилище?

Просто не помещайте файлы во внутреннее хранилище. Пользователи rooted устройств могут получить доступ к тому, что им нужно на устройстве, поэтому единственный способ предотвратить их доступ к вашим данным — не иметь их на устройстве.

Некоторые разработчики попытаются зашифровать свои файлы с помощью жестко запрограммированного пароля, чтобы пользователи rooted устройств не могли использовать эти файлы. Это создаст эффект «лежачего полицейского» на короткое время. Все, что требуется, — это один заинтересованный в реверс-инжиниринге вашего приложения человек, определивший, как расшифровать эти файлы, а затем написавший сообщение в блоге или форуме о том, как это сделать.

В целом, относительно мало людей с rooted устройствами — я оцениваю их на уровне менее 1%. ИМХО, вы преуспеете больше, сосредоточив свою инженерную работу на написании лучшего приложения, вместо того, чтобы тратить время на защиту от рутованных устройств.

Источник

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