Android open asset as file

Assets (Активы)

В Android имеется ещё один каталог, в котором могут храниться файлы, предназначенные для включения в пакет — assets. Этот каталог находится на том же уровне, что и res. Для файлов, располагающихся в assets, в R.java не генерируются идентификаторы ресурсов. Для их считывания необходимо указать путь к файлу. Путь к файлу является относительным и начинается с /assets. Этот каталог, в отличие от подкаталога res, позволяет задавать произвольную глубину подкаталогов и произвольные имена файлов и подкаталогов.

По умолчанию проект в студии не содержит данную папку. Чтобы её создать, выберите меню File | New | Folder | Assets Folder.

Чтение файлов

Для доступа к файлам используется класс AssetManager. Пример для чтения текстового файла.

Сначала на Kotlin.

Для доступа к графическому файлу из актива можно использовать следующий код:

Вы также можете загрузить изображение в Bitmap, используя BitmapFactory.decodeStream(), вместо Drawable.

Функция-расширение для Kotlin, которая вернёт Bitmap.

Используем собственные шрифты

Напишем практический пример создания приложения, в котором будут использоваться собственные шрифты, не входящие в стандартную библиотеку шрифтов Android. Для этого мы упакуем нужные шрифты вместе с приложением. Поместим в каталог assets/fonts файлы шрифтов (можно скачать бесплатные шрифты с сайтов 1001 Free Fonts или Urban Fonts ).

В файл разметки добавим пару текстовых полей с заготовленным текстом для вывода этого текста с нашим шрифтом.

В классе активности загрузим объект EditText из ресурсов, а затем создадим объект Typeface, используя вызов статического метода Typeface.createFromAsset(). Метод createFromAsset() принимает два параметра:

  • объект AssetManager, который можно получить вызовом метода getAssets()
  • путь к файлу актива.

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

Запустив проект, мы увидим в текстовых полях надписи Happy New Year! и Meow!, выводимые нашими собственными шрифтами.

Пример для фрагмента.

Загрузка локальных файлов из активов в WebView

Если нужно загрузить локальные страницы и изображения из активов в WebView, то можно использовать префикс file://android_asset. Подробнее смотрите в статье про WebView.

Получаем список файлов в папке assets

Можно получить список файлов, которые находятся в папке assets. Для быстрой проверки кода я вручную скопировал в папку два файла:

Кроме ваших файлов, также возвращаются странные папки /images, /sounds, /webkit. Учитывайте это в своих проектах. Так как в папке можно создавать собственные подпапки, то можно воспользоваться вспомогательным методом:

Ограничение на размер файлов

По сети гуляет информация, что существует ограничение в 1 Мб на размер файлов в папке assets. При превышении размера у вас может появиться ошибка:

Я не сталкивался, поэтому рецепт решения проблемы не предлагаю.

Источник

Using Android Assets

Assets provide a way to include arbitrary files like text, xml, fonts, music, and video in your application. If you try to include these files as «resources», Android will process them into its resource system and you will not be able to get the raw data. If you want to access data untouched, Assets are one way to do it.

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

Assets added to your project will show up just like a file system that can read from by your application using AssetManager. In this simple demo, we are going to add a text file asset to our project, read it using AssetManager , and display it in a TextView.

Add Asset to Project

Assets go in the Assets folder of your project. Add a new text file to this folder called read_asset.txt . Place some text in it like «I came from an asset!».

Visual Studio should have set the Build Action for this file to AndroidAsset:

Visual Studio for Mac should have set the Build Action for this file to AndroidAsset:

Selecting the correct BuildAction ensures that the file will be packaged into the APK at compile time.

Reading Assets

Assets are read using an AssetManager. An instance of the AssetManager is available by accessing the Assets property on an Android.Content.Context , such as an Activity. In the following code, we open our read_asset.txt asset, read the contents, and display it using a TextView.

Reading Binary Assets

The use of StreamReader in the above example is ideal for text assets. For binary assets, use the following code:

Running the Application

Run the application and you should see the following:

Источник

Asset

Files

Typedefs

typedef struct AAssetManager AAssetManager typedef struct AAssetDir AAssetDir typedef struct AAsset AAsset

Enumerations

Functions

AAssetDir * AAssetManager_openDir (AAssetManager *mgr, const char *dirName)
AAsset * AAssetManager_open (AAssetManager *mgr, const char *filename, int mode)
const char * AAssetDir_getNextFileName (AAssetDir *assetDir)
void AAssetDir_rewind (AAssetDir *assetDir)
void AAssetDir_close (AAssetDir *assetDir)
int AAsset_read (AAsset *asset, void *buf, size_t count)
off_t AAsset_seek (AAsset *asset, off_t offset, int whence)
off64_t AAsset_seek64 (AAsset *asset, off64_t offset, int whence)
void AAsset_close (AAsset *asset)
const void * AAsset_getBuffer (AAsset *asset)
off_t AAsset_getLength (AAsset *asset)
off64_t AAsset_getLength64 (AAsset *asset)
off_t AAsset_getRemainingLength (AAsset *asset)
off64_t AAsset_getRemainingLength64 (AAsset *asset)
int AAsset_openFileDescriptor (AAsset *asset, off_t *outStart, off_t *outLength)
int AAsset_openFileDescriptor64 (AAsset *asset, off64_t *outStart, off64_t *outLength)
int AAsset_isAllocated (AAsset *asset)
AAssetManager * AAssetManager_fromJava (JNIEnv *env, jobject assetManager)

Detailed Description

Typedef Documentation

AAsset provides access to a read-only asset.

AAsset objects are NOT thread-safe, and should not be shared across threads.

AAssetDir provides access to a chunk of the asset hierarchy as if it were a single directory. The contents are populated by the AAssetManager.

The list of files will be sorted in ascending order by ASCII value.

AAssetManager provides access to an application’s raw assets by creating AAsset objects.

AAssetManager is a wrapper to the low-level native implementation of the java AAssetManager, a pointer can be obtained using AAssetManager_fromJava().

The asset hierarchy may be examined like a filesystem, using AAssetDir objects to peruse a single directory.

A native AAssetManager pointer may be shared across multiple threads.

Enumeration Type Documentation

Available access modes for opening assets with AAssetManager_open

No specific information about how data will be accessed.

Read chunks, and seek forward and backward.

Read sequentially, with an occasional forward seek.

Caller plans to ask for a read-only buffer with all data.

Function Documentation

Close the asset, freeing all associated resources.

Enumerator
AASSET_MODE_UNKNOWN
const void* AAsset_getBuffer ( AAsset * asset )

Get a pointer to a buffer holding the entire contents of the assset.

Returns NULL on failure.

off_t AAsset_getLength ( AAsset * asset )

Report the total size of the asset data.

off64_t AAsset_getLength64 ( AAsset * asset )

Report the total size of the asset data. Reports the size using a 64-bit number insted of 32-bit as AAsset_getLength.

off_t AAsset_getRemainingLength ( AAsset * asset )

Report the total amount of asset data that can be read from the current position.

off64_t AAsset_getRemainingLength64 ( AAsset * asset )

Report the total amount of asset data that can be read from the current position.

Uses a 64-bit number instead of a 32-bit number as AAsset_getRemainingLength does.

int AAsset_isAllocated ( AAsset * asset )

Returns whether this asset’s internal buffer is allocated in ordinary RAM (i.e. not mmapped).

int AAsset_openFileDescriptor ( AAsset * asset,
off_t * outStart,
off_t * outLength
)

Open a new file descriptor that can be used to read the asset data. If the start or length cannot be represented by a 32-bit number, it will be truncated. If the file is large, use AAsset_openFileDescriptor64 instead.

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License.

Get the latest Android developer news and tips that will help you find success on Google Play.

Hooray!

You have successfully signed up for the latest Android developer news and tips.

Источник

Import and preview 3D assets

Learn how to import 3D models, convert them into Sceneform format, and preview them in Android Studio.

Import a new 3D asset

Sceneform supports 3D assets in the following formats:

  • OBJ
  • glTF (animations not supported)
  • FBX, with or without animations.

Follow these steps to import a new 3D asset:

Verify that your project’s app folder contains a sampledata folder.

To create the folder, right-click on the app folder in the Project window, then select New > Sample Data Directory.

The sampledata folder is part of your Android Studio project, but its contents will not be included in your APK.

Copy your 3D model source asset file ( *.obj , *.fbx , or *.gltf ), and all of its dependencies ( *.mtl , *.bin , *.png , *.jpg , etc.) into the sampledata folder.

Do not copy these source files into your project’s assets or res folder, as this will cause them to be included in your APK unnecessarily.

Right click the 3D model source asset and select Import Sceneform Asset to begin the import process.

The values are used by the sceneform.asset() entry in the app’s build.gradle , and determine where the *.sfa and *.sfb files will be generated in your project.

If you’re importing a model for the first time, use the default values.

Field Description
Source Asset Path Filename of the OBJ, FBX, or glTF 3D model asset to import.
Material Path default tells Sceneform’s to use the built-in default material or the path to a custom material *.mat file.
.sfa Output Path Use the default, or specify another path under the sampledata folder.

The .sfa file is generated if missing. It can be modified to control some aspects of the import process.

This ensures that *.sfa isn’t included in your APK unncessarily.

.sfb Output Path By default the src/main/assets/ folder is used, which allows the use of arbitrary asset filenames.

If the filename (without file extension) is a valid resource identifier (e.g. R.raw.filename ), then you can instead use the src/main/res/raw/ folder if you prefer.

See Android’s App resources overview for more on using the assets/ and res/ folders in your app.

If you are importing *.fbx animation files, click the plus sign (+) and add the rest of the files individually.

Click Finish to begin the import process.

To import your asset, the plugin does the following:

Adds the Sceneform gradle plugin to your project’s build.gradle if it doesn’t already exist:

Updates your app’s build.gradle file to include an apply plugin line, and a sceneform.asset() entry for the newly imported asset:

These new entries in the app’s build.gradle create two gradle tasks:

createAsset- creates a Sceneform asset definition ( *.sfa ) file if it does not yet exist.

This task will not overwrite an existing *.sfa file, which means any modifications you make to the SFA file after import won’t be overwritten.

The *.sfa file is a text file that contains a complete, human-readable description of the asset’s import settings. It references the models and textures in your source asset, and also defines materials by providing material parameters for Sceneform’s physically based materials.

compileAsset- compiles the *.sfa file into a Sceneform binary asset ( *.sfb ) file.

This *.sfb file gets built into your app’s APK and is loaded at runtime to create the renderable.

Opens the *.sfa in a text window and the *.sfb in a Viewer window.

Update a previously imported 3D asset

When you update a previously imported OBJ, FBX, or glTF model source asset file ( *.obj , *.fbx , or *.gltf ), the corresponding sceneform.asset() entry in your app’s build.gradle causes the plugin to automatically generate an updated *.sfb file, based on the current *.sfa parameters.

To iterate on the parameters for an already imported asset:

  • Modify the *.sfa text file, using the SFA file format reference as a guide.
  • Save your changes. This causes the asset to be recompiled and updates the *.sfb file.
  • Preview the updated asset by double-clicking the *.sfb file to open the asset Viewer window.

If you are updating a previously imported asset that includes animation data, import each of the updated *.fbx files individually using the plus (+) sign in the Animation Files section of the import dialog.

Gradle asset definitions

The import process adds any *.fbx animation files at the end of the build.gradle file.

Create the Renderable

Once the asset is compiled into *.sfb format, you can build a ModelRenderable and attach it to a node in the scene as follows:

Using custom materials

Sceneform’s default materials make it easy for developers to get great looking results. You can also use custom materials to deeply customize the way your assets look.

To assign a custom material to your asset:

Create a custom material definition ( *.mat ) file, using the [Custom Material Reference](/sceneform/develop/custom-material as a guide.

Apply the custom material to the asset:

When importing a new asset:

  • Specify the custom material *.mat file during the import process.

To update a previously imported asset:

If the *.sfa contents have not been customized, delete the existing *.sfa and *.sfb files and the sceneform.asset() entry in the app’s build.gradle , then reimport the asset. This ensures that the regenerated *.sfa attributes and material parameters will match the ones supported by your custom material.

To preserve any *.sfa customizations you’ve made, open the *.sfa file and change the source attribute to the path to your custom material *.mat file, then manually adjust the *.sfa attributes and material parameters to match your custom material.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Источник

Читайте также:  Лечение сд карты андроид
Оцените статью