File structure on android

Структура и назначение файлов и папок в Андроид

вкл. 12 Апрель 2015 . Опубликовано в Android — Общее

Структура и назначение файлов и папок в Андроид. В данной статье вы узнаете какие папки (директории) в Android существуют, какие файлы в них находятся, за что отвечают данные папки и файлы и зачем они нужны.

Предисловие о структуре

У многих есть компьютер и на них установлена ОС Windows. Все прекрасно знают, что в данной ОС все распределено по дискам:

C: — на данном диске находиться система

D: — для личных файлов (диска может и не быть, если он не «разбит»)

E: — Z: — флешки, переносные жесткие диски, CD или DVD приводы.

В Windwows все рассредоточено по различным дискам. В UNIX/Linux куда входит и Android (а также BSD, куда входит Mac OS X) все выглядит все немного иначе. Файловая структура имеет древовидный вид. Возможно сейчас не понятно, но дальше с прочтением статьи будет более понятно.

Также стоит знать что Android как и в Linux, в отличие от Windows очень чувствительны к регистру. Например папка Name, NaMe, name, NAME — это 4 разных папки, тогда как Windows сможет создать только одну папку с таким именем.

Для того чтобы было более понятно о чем идет речь, рекомендуется установить файловый менеджер Root Browser.

Структура и назначение папок и файлов Android

Как было выше сказано — структура имеет древовидный вид. У любого дерева имеется корень, в UNIX/Linux он также существуют. Корень — это отправной пункт в файловой структуре, с корня система обрастает папками и файлами. Корень в UNIX/Linux отмечается как знак:

Подробно о разделе cache

/cache/ — в данном разделе находятся временные файлы, точней сюда скачиваются обновления системы.

Подробно о разделе dev

/dev/ — в данной разделе содержится информация о устройствах системы и файлов

Подробно о разделе data

/data/ — пользовательский раздел в котором находятся установленные приложения, личные настройки

/data/app — здесь находятся установленные приложения, игры

/data/app-lib — дополнительные библиотеки необходимые для работы определенных приложений (присутствует в новых версиях Android)

/data/dalvik-cache — кеш-память, для работы Java машины Dalvik которая является «двигателем» в Android отвечающая за запуск и работу приложений.

/data/data — в данной папке находятся индивидуальные настройки каждого пользовательского приложения, библиотеки и другие файлы необходимые файлы для их работы.

/data/system/ — в данном разделе находятся глобальные настройки пользовательского окружения, синхронизация, аккаунты, блокировка. Файлы gesture.key, locksettings.db, locksettings.db-shm, locksettings.db-wal — графический ключ, пин-код.

Подробно о разделе efs

/efs/ — находится файлы и папки отвечающие за IMEI (данный раздел имеется не во всех Android)

Подробно о разделе preload

/preload/ — в данном разделе находятся дополнительные файлы и папки, которые зеркалируются в раздел /system/ (данный раздел имеется не во всех Android, преимущественно в Samsung)

Подробно о разделе system

/system/ — данный раздел содержит системные папки и файлы необходимые для функционирования Android

/system/app — здесь находятся системные приложения и сервисы (в новых ОС Android сервисные приложения вынесли в другую папку priv-app)

/system/bin и /system/xbin — папка содержит файлы и ссылки на исполняемые бинарные файлы.

/system/xbin/su — файл отвечающий за Root права

/system/camerdata — в данной папке находятся файлы отвечающие за работу камеры

/system/etc — в данной папке находятся конфигурационные файлы необходимые при загрузке ОС а также необходимые в процессе работы различных программ

/system/init.d — в данной папке находятся скрипты, которые могут влиять на работу системы.

/system/etc/ hosts — файл отвечающий за блокировку, переадресацию веб адресов.

/system/etc/ apns.conf — файл с информацией о точках доступах интернет (APN)

Читайте также:  Русификатор witch trainer silver mod андроид

/system/etc/ gps.conf — настройки GPS

/system/fonts — папка с системными шрифтами

/system/framework — папка с «процессами» Android

/system/lib/ — библиотеки системных приложений и сервисов

/system/lib/modules — драйверы системы

/system/media — папка с системными звуками и анимацией включения

/system/media/ bootanimation.zip — исполняемый архив с загрузочной анимацией

/system/priv-app — папка с сервисами Android

/system/tts — папка с голосовыми движками системы

/system/build.prop — конфигурационный файл с помощью которого можно изменить системные настройки

Подробно о разделе proc

/proc — виртуальный раздел содержащий информацию о ядре и его конфигурации

Подробно о разделе mnt

/mnt — в данный раздел монтируются (добавляются) карты памяти и внутренняя память и другие виртуальные разделы (также в новых версиях можно встретить раздел storage)

Подробно о разделе storage

/storage — в данный раздел монтируются только реальные (существующие, то есть не виртуальные) карты памяти и внутренняя память

Подробно о разделе mnt и storage

Все файлы которые существуют у вас на Android (картинки, мелодии, видео, документы) записаны либо на внутренней памяти или карте памяти. Если в Android присутствует собственная память (внутренняя память) то она имеет монтируется под именем

/mnt/sdcard или /storage/sdcard

Да, я прекрасно понимаю что многие считают давать название собственной памяти таким именем, но что поделаешь…

Если же внутренней памяти нет, то это имя занимает карта памяти. Если же есть и внутренняя память и карта памяти, то внутренней так и остается под именем sdcard, а карта памяти берет одно из имен

sdcard2
external_sd
sdcard1
extSdCard

Источник

Android File System And Directory Structure Explained

Last Updated: November 7, 2014

Most people are familiar with the file layout on Windows and are happy navigating the Windows file System.

Windows uses a drive letter for each physical drive or partition.e.g. C: drive

Note: A Physical drive will have at least 1 partition but can have more than one. This is true for both Windows and Android.

[outline style=”yellow”]What is a Disk Partition? – Disks can be subdivided into smaller disks called partitions. Partitions appear and can be used as if they were separate physical disks. [/outline]

If you insert a USB drive into your windows machine in shows up as a disk with an assigned drive letter.

Although windows shows a disk icon the disks could be partitions of a single physical disk.

Each disk partition has a root directory which contains files and folders (directories).

The root of the C drive is C:\ and of the F drive is F:\ etc

Android File System Structure

Android uses the Linux file system structure which has a single root .

The diagram below shows the structure

The system partitions and directories are protected and unless your device is rooted you don’t normally have access to these although some file managers will display them.

Physical disks and partitions appear under the root as a directories , and do not have a drive letter as in Windows.

Android doesn’t normally come with a default file manager, and so you will need to install a file manager App like Astro file manager, to locate and manage files and folders.

The sdcard and ext-sdcard Partitions

The sdcard partition is the main storage area for user data and files. It also contains App settings and data.

The sdcard partition exists even though you may not have an external sd card.

It is the internal partition.

If you open the sdcard directory you will see something like this:

Note: partial listing only

These files and directories contain your pictures,films,downloads etc as well as App data and settings.

You can view these files from your PC by connecting your device to a PC using a USB cable.

The ext-sdcard partition will only be visible if your device supports external storage, usually using a microSD slot.

External sd cards use either the FAT,FAT32 or exFAT file system formats.

Most devices support FAT and FAT32, but support for exFAT is limited.

The choice of file system is governed by the partition size as follows:

Card Type

Card Type File System

Max Capacity

Читайте также:  Как раздать инет андроид
SD FAT 2GB SDHC FAT32 32GB see Note SDXC exFAT 2TB

Note: Windows format size limit of 32GB. Can be larger but need to format using external tools. Windows XP could fomat FAT32 Volumes upto 128 GB

Android File Associations

Just as with other operating systems like Windows, Android will use an App to open a particular file type,denoted by the extension.

For example if you try to open a pdf file it will normally use Adobe reader (if installed) to open the file.

To open a file you will normally need to located the file using a file manager.

Just press the file to open it.


If the file type doesn’t already have an App associated with it you should be prompted to choose between the available Apps.

The option to always use that App sets it as the default App for that file type.

If you set it as the default App you will not be prompted again unless you remove the association.

To remove an association you need to remove it from the App itself.

So if the pdf files open with adobe reader and you want to change that:

  1. Go to Settings>Apps>Select Adobe reader,
  2. Then go to the Launch by default section
  3. and Clear defaults

The next time you try to open a pdf file you will be promoted to choose an App.

Android File Managers

If you search the Google play store you will find many file managers.

Which App is the most suitable depends on what you want to do. You should bear in mind that more features/functionality isn’t always better.

File managers like ESF have lots of functionality including:

  • Built in FTP client
  • Task Manager
  • Cloud storage client
  • etc

However for many this is a bit of an overkill, and so you might consider installing one of the simpler file managers like file manager and Astro file manager.

File Downloads

When you download a file using Google chrome or another browser App the file it is stored in the download directory.

You can access the directory contents through a shortcut in the Apps folder (if provided).

You can also use a file manager to locate it the folder called download. It is under your primary storage (called sdcard)

Summary

Android uses the Linux File and Directory Structure which consists of a single root.

All drives and partitions are displayed as directories in this tree like structure.

Источник

Organizing your Source Files

Android applications should always be neatly organized with a clear folder structure that makes your code easy to read. In addition, proper naming conventions for code and classes are important to ensure your code is clean and maintainable.

Be sure to check out the Ribot Code and Style Guidelines for a more extensive breakdown of suggested style and naming guidelines.

The following naming and casing conventions are important for your Java code:

Type Example Description Link
Variable incomeTaxRate All variables should be camel case Read More
Constant DAYS_IN_WEEK All constants should be all uppercase Read More
Method convertToEuroDollars All methods should be camel case Read More
Parameter depositAmount All parameter names should be camel case Read More

See this naming guide for more details.

Android classes should be named with a particular convention that makes their purpose clear in the name. For example all activities should end with Activity as in MoviesActivity . The following are the most important naming conventions:

Name Convention Inherits
Activity CreateTodoItemActivity AppCompatActivity , Activity
List Adapter TodoItemsAdapter BaseAdapter , ArrayAdapter
Database Helper TodoItemsDbHelper SQLiteOpenHelper
Network Client TodoItemsClient N/A
Fragment TodoItemDetailFragment Fragment
Service FetchTodoItemService Service , IntentService

Use your best judgement for other types of files. The goal is for any Android-specific classes to be identifiable by the suffix.

There are several best practices for organizing your app’s package structure.

The way to do this is to group things together by their category. Each component goes to the corresponding package:

  • com.example.myapp.activities — Contains all activities
  • com.example.myapp.adapters — Contains all custom adapters
  • com.example.myapp.models — Contains all our data models
  • com.example.myapp.network — Contains all networking code
  • com.example.myapp.fragments — Contains all fragments
  • com.example.myapp.utils — Contains all helpers supporting code.
  • com.example.myapp.interfaces — Contains all interfaces

Keeping these folders in each app means that code is logically organized and scanning the code is a pleasant experience. You can see a slight variation on this structure as suggested by Futurice on their best-practices repo.

Alternatively, we can package-by-feature rather than layers. This approach uses packages to reflect the feature set. Consider the following package structure as outlined in this post:

  • com.example.myapp.service.* — Is a subpackage for all background related service packages/classes
  • com.example.myapp.ui.* — Is a subpackage for all UI-related packages/classes
  • com.example.myapp.ui.mainscreen — Contains classes related to some app’s Main Screen
  • com.example.myapp.ui.detailsscreen — Contains classes related to some app’s Item Details Screen

This feature allows you to place DetailsActivity , DetailsFragment , DetailsListAdapter , DetailsItemModel in one package, which provides comfortable navigation when you’re working on «item details» feature.

DetailsListAdapter and DetailsItemModel classes and/or their properties can be made package-private, and thus not exposed outside of the package. Within the package you may access their properties directly without generating tons of boilerplate «setter» methods.

This can make object creation really simple and intuitive, while objects remain immutable outside the package.

Resources should be split up into the following key files and folders:

Name Path Description
XML Layouts res/layout/ This is where we put our XML layout files.
XML Menus res/menu/ This is where we put our AppBar menu actions.
Drawables res/drawable This is where we put images and XML drawables.
Colors res/values/colors.xml This is where we put color definitions.
Dimensions res/values/dimens.xml This is where we put dimension values.
Strings res/values/strings.xml This is where we put strings.
Styles res/values/styles.xml This is where we put style values.

See the full list of resources here and note the following:

  • Don’t hardcode color hex values in the layout. Instead of hardcoding these values, be sure to move all colors into res/values/colors.xml and reference the colors in layouts with @color/royal_blue .
  • Don’t hardcode margin / padding dimensions in the layout. Instead of hardcoding these values, be sure to move all dimension values into res/values/dimens.xml and reference these in layouts with @dimen/item_padding_left .
  • To support multiple devices, we can then use the alternative resources system to provide different colors, strings, dimens, styles, etc based on the device type, screen size, API version and much more.

Be sure to start properly organizing your resources early on in the development of an application. Be sure to check out the Ribot Code and Style Guidelines for a more extensive breakdown of suggested style and naming guidelines.

Often there are questions about organizing not just the source files but also better organizing the application resources. In a modern app, there are often hundreds of different layout files, drawables, styles, etc and by default these are all grouped together in a flat list within a single subdirectory (i.e res/layout ). For now, keep the layout resource files in the same directory.

Refer to stackoverflow post for a discussion of explored options. The main problem is that if you try to use the nested resource layout approach, the current logic for the Android Studio’s Gradle plug-in will not update the resource files after they have changed for nested resource sets. The current implementation attempts to check the resource directories using startsWith(), so a directory structure that is nested (i.e. src/main/res/layout/layouts and src/main/res/layout/layouts_category2) will choose src/main/res/layout/layouts consistently and never actually update the changes. A result, you will you have to rebuild/clean the project each time whenever making layout file changes.

It is up to you to decide which of the aforementioned approaches suits your project best.

However, in general Java programming, packaging apps by feature is considered preferable and makes a lot of sense.

Источник

Читайте также:  Microsoft office android полная версия 4pda
Оцените статью