- Assets (Активы)
- Чтение файлов
- Используем собственные шрифты
- Загрузка локальных файлов из активов в WebView
- Получаем список файлов в папке assets
- Ограничение на размер файлов
- 41 Post
- Android: Loading files from the Assets and Raw folders
- Downloads
- Support for APK expansion files (OBB)
- Building the app with expansion files
- How data is split between the APK and OBB
- Downloading the OBB expansion file
- Hosting OBB files on the Google Play Store
- Hosting OBB files without using the Google Play Store
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. При превышении размера у вас может появиться ошибка:
Я не сталкивался, поэтому рецепт решения проблемы не предлагаю.
Источник
41 Post
Game Programming, Android and Retro Games
Android: Loading files from the Assets and Raw folders
Posted by Dimitri | May 24th, 2011 | Filed under Programming
This tutorial will explain how to load files from the res/raw and the Assets folder using a String to specify the file name. Yes, there are a lot of tutorials on this subject, but they all use the automatically generated integer IDs from the R class as inputs and not many of them even mention the possibility of loading files from the Assets folder. As a result of depending on the ID, the file reference must be known beforehand.
Instead, the code featured in this post will explain how to find the reference to the file and then load it at runtime based solely on its name. This means that the reference ID and the file don’t even have to exist in the first place, and can be acquired at run time.
Before looking into the code, it’s important to highlight the main differences between the raw folder and the Assets folder. Since raw is a subfolder of Resources (res), Android will automatically generate an ID for any file located inside it. This ID is then stored an the R class that will act as a reference to a file, meaning it can be easily accessed from other Android classes and methods and even in Android XML files. Using the automatically generated ID is the fastest way to have access to a file in Android.
The Assets folder is an “appendix” directory. The R class does not generate IDs for the files placed there, so its less compatible with some Android classes and methods. Also, it’s much slower to access a file inside it, since you will need to get a handle to it based on a String. There is also a 1MB size limit for files placed inside the Assets folder, however some operations are more easily done by placing files in this folder, like copying a database file to the system’s memory. There’s no (easy) way to create an Android XML reference to files inside the Assets folder.
The first thing the code does is to create two private variables. A Resources object that will act as a handle to the app’s resources and a String, that will be used to output the content of the files to LogCat (lines 16 and 18).
Now let’s jump straight to line 60 where the LoadFile() method is defined. It returns a String and takes two parameters: the first one is the file name and the second is a boolean, that signals the method whether it should load from the res/raw or the Assets folder.
After that, the method creates a InputStream object (line 63). Streams are like handles to read files into buffers (Input Stream) and to write files from these buffers (Output stream).
Line 65 checks if the loadFromRawFolder parameter is true. Case it is, the code at lines 68 and 70 is executed. The former dynamically loads resources from the raw folder. The getIdentifier() method from the resources object returns a resource ID based on the path. This parameter is composed by:
package name:type of resource/file name
Package name is self explanatory; type of resource can be one of the following: raw, drawable, string. File name, in this example, is the fileName parameter, an it’s being concatenated to create one single String. Since all information that this method requires is being passed on the first parameter the other two can be null.
Finally, line 70 feeds this ID to the openRawResource() method, which will return a InputStream from a file located at the res/raw folder.
At the else block, the Assets folder is being opened, by first calling the getAssets() method to return a handle to the Assets folder and right after that, the open() method is called, passing the fileName as the parameter. All that is done to also return the InputStream, although this time, for a file at the Assets folder (line 75).
Now that we have the InputStream, we can create the buffer to read the file into. That’s accomplished by line 79, that creates a byte array that has exactly the same length as iS (the InputStream object). The file is read into the buffer at the next line (line 81).
With the file loaded into the buffer, it’s time to prepare a OutputStream to write the buffer contents into. First, a object of this type is created at line 83. Then, the write() method is called passing the buffer as the parameter (line 85). With that, a handle to the file’s content was created.
There’s nothing left to do with these two streams, so they are closed at lines 87 and 88. Finally, the return for this method is set, by converting the oS object to a String (line 91).
At last, the LoadFile() method is called at line 33 (don’t forget to omit the file extension) and at line 47 (don’t forget to include the file extension). Both method calls are surrounded by a try/catch block since they can throw an exception.
The returned String from the method calls are stored at the output variable. It’s then later used to print the contents of the loaded files into LogCat’s console (lines 35 and 49).
And that’s about it! The method that was declared in the Activity can be easily adapted to load and return anything from these folders, not just a String. Additionally, it can be used to dynamically to acquire a reference, and load files at run time.
Downloads
Want to see more posts like this more often? Please donate by clicking at the button below:
Don’t feel like donating? Alternatively, you can support the site by purchasing the FULL version of the Arrows Live Wallpaper app at the Google Play Store™:
Источник
Support for APK expansion files (OBB)
APK expansion files are used as a solution for the 100MB app size limit in the Google Play Store. If your app is larger than 100MB (which is quite likely for a big game), you have to split your output package into the main part (APK) and the expansion file (OBB). Refer to the Android Developer documentation on expansion files for more information.
Unity automatically splits the output package into APK and OBB. This is not the only way to split the app package (other options include third-party plug-ins and AssetBundles), but it is the only automatic splitting mechanism officially supported by Unity.
Note: Unity only creates the main expansion file. If you want to manually create the patch expansion file, you must include a file named with your build-id; otherwise, the patch expansion file won’t load. The file can be empty, but you must place it in the Assets directory inside the patch expansion file. This file’s name must match the unity.build-id metadata, which Unity automatically adds to the manifest when you build the APK. Alternatively, you can copy this file from the main expansion file into the patch expansion file.
Building the app with expansion files
If you want Unity to split the app output package into APK and OBB for you, open the Player settings (menu: Edit > Project Settings A broad collection of settings which allow you to configure how Physics, Audio, Networking, Graphics, Input and many other areas of your project behave. More info
See in Glossary , then select the Player category), and in the Publishing Settings panel, enable the Split Application Binary property.
The Publishing Settings panel of the Player settings, with the Split Application Binary checkbox highlighted
Both parts of the output package (APK and OBB) are copied to the output directory you specify when building the app. For example, if the APK has the name mygame.apk, the OBB is in the same directory under the name mygame.main.obb.
If you select Build and Run, the APK and OBB files are installed on your device by Unity. If you select Build The process of compiling your project into a format that is ready to run on a specific platform or platforms. More info
See in Glossary and want to install the app manually using the ADB An Android Debug Bridge (ADB). You can use an ADB to deploy an Android package (APK) manually after building. More info
See in Glossary utility, you must first install the APK and then copy the OBB into the correct location on your device. The OBB file name must correspond the format required by Google. Refer to the expansion files section of the Android Developer documentation for more information.
If the app starts and can’t find and load the OBB, only the first Scene A Scene contains the environments and menus of your game. Think of each unique Scene file as a unique level. In each Scene, you place your environments, obstacles, and decorations, essentially designing and building your game in pieces. More info
See in Glossary is available (see documentation on how data is split between the APK and OBB below for more information). Do not use the contents of the OBB separately — always treat the APK and OBB as a unique bundle, the same way as you would treat a single APK.
How data is split between the APK and OBB
When the Split Application Binary option is enabled, the app is split the following way:
APK The Android Package format output by Unity. An APK is automatically deployed to your device when you select File > Build & Run. More info
See in Glossary — Consists of the executables (Java and native), plug-ins A set of code created outside of Unity that creates functionality in Unity. There are two kinds of plug-ins you can use in Unity: Managed plug-ins (managed .NET assemblies created with tools like Visual Studio) and Native plug-ins (platform-specific native code libraries). More info
See in Glossary , scripts A piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info
See in Glossary , and the data for the first Scene (with the index 0).
OBB — Contains everything else, including all of the remaining Scenes, resources, and streaming Assets.
If your APK is still too large for publishing in the Google Play Store (more than 100MB), try reducing the size of your first Scene, making it as small as possible.
Downloading the OBB expansion file
The Unity Asset Store offers a plug-in that allows you to access an adapted version of the Google Play market_downloader library for Unity, which you can use to download the OBB from Google Play Store, or an external source, and move it into the correct directory.
Hosting OBB files on the Google Play Store
OBB expansion files should be published to the Google Play Store along with your APK. Any OBB files published with your APK will be automatically downloaded when a user installs your app from the Google Play Store.
You should include code in your app that downloads missing OBB files in the case of a Google Play Store error, or if a user removes the OBB files from their device. For more information about downloading OBB files, refer to the APK Expansion file section of the Android Developer documentation.
Hosting OBB files without using the Google Play Store
You can also host OBB files yourself if you do not want to use the Google Play Store. However, hosting OBB files without using the Google Play Store is only recommended for advanced users.
Источник