What is native window in android

Создание приложения Android Native Activity

После установки кроссплатформенной рабочей нагрузки Разработка мобильных приложений на языке C++ Visual Studio можно использовать для создания полнофункциональных приложений Android Native Activity. Пакет Android Native Development Kit (NDK) — это набор средств, с помощью которых можно реализовывать большинство возможностей приложения Android, используя чистый код C или C++. Для обеспечения взаимодействия кода C или C++ с Android используется определенный код Java JNI, выступающий в роли связующего. В Android NDK появилась возможность создавать приложения Native Activity с помощью API Android уровня 9. Код Native Activity популярен для создания игровых приложений и приложений с интенсивным использованием графики на основе Unreal Engine или OpenGL. В этом пошаговом руководстве показано создание простого приложения Native Activity, в котором используется OpenGL. В дополнительных разделах последовательно рассматриваются такие этапы жизненного цикла разработки, как редактирование, сборка, отладка и развертывание кода Native Activity.

Требования

Прежде чем создавать приложение Android Native Activity, необходимо убедиться, что вы выполнили все системные требования и установили рабочую нагрузку Разработка мобильных приложений на языке C++ в Visual Studio. Дополнительные сведения см. в статье Установка Visual C++ для разработки кроссплатформенных мобильных приложений на языке C++. Убедитесь, что необходимые сторонние инструменты и пакеты SDK включены в установку, а также что установлен эмулятор Android.

Создание проекта Native Activity

В этом руководстве вы сначала создадите новый проект Android Native Activity, а затем создадите и запустите приложение по умолчанию в эмуляторе Android.

в Visual Studio выберите файл создать Project.

В диалоговом окне Новый проект в меню Шаблоны последовательно выберите Visual C++ Кроссплатформенное приложение, а затем выберите шаблон Приложение Native-Activity (Android).

Присвойте приложению имя, например MyAndroidApp, а затем нажмите OK.

Visual Studio создаст новое решение и откроет обозреватель решений.

в Visual Studio выберите файл создать Project.

В диалоговом окне Создание нового проекта выберите шаблон Приложение Native-Activity (Android), а затем нажмите Далее.

В диалоговом окне Настроить новый проект введите имя, например MyAndroidApp в разделе Имя проекта, а затем выберите Создать.

Visual Studio создаст новое решение и откроет обозреватель решений.

В новое решение приложения Android Native Activity входят два проекта.

MyAndroidApp.NativeActivity содержит ссылки и связующий код для запуска приложения как приложения Native Activity на Android. Реализация точек входа из связывающего кода находится в Main. cpp. Предкомпилированные заголовки находятся в PCH. h. Этот проект приложения с собственным действием компилируется в общую библиотеку . файл, который забирается проектом упаковки.

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

MyAndroidApp.Packaging создает файл с расширением MyAndroidApp.Packaging для развертывания на устройстве или в эмуляторе Android. Он содержит ресурсы и файл AndroidManifest.xml , в которых задаются свойства манифеста. Он также содержит файл build.xml , который управляет процессом сборки Ant. По умолчанию он задан как начальный проект, который можно развернуть и запустить непосредственно из Visual Studio.

Создание и запуск приложения Android Native Activity по умолчанию

Разработайте и запустите приложение, созданное шаблоном, чтобы проверить установку и настройку. Для первоначального теста запустите приложение в одном из профилей устройств, установленных эмулятором Android. Если вы предпочитаете тестировать приложение на другой платформе, загрузите целевой эмулятор или подключите устройство к компьютеру.

Сборка и запуск приложения Native Activity по умолчанию

Выберите x86 из раскрывающегося списка платформы решения , если он еще не выбран.

Если список Платформы решения не отображается, щелкните пункт Платформы решения из раскрывающегося списка Добавить или удалить кнопки и выберите свою платформу.

В строке меню выберите Сборка собрать решение.

В окне «Выходные данные» отобразятся выходные данные процесса сборки для двух проектов в решении.

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

Если вы установили другие эмуляторы или подключили устройство Android, то можете выбрать их в раскрывающемся списке платформы развертывания.

Нажмите клавишу F5 , чтобы начать отладку, или клавишу F5 , чтобы начать без отладки.

Вот как выглядит приложение по умолчанию в эмуляторе Android.

Visual Studio запускает эмулятор, который за несколько секунд загружает и развертывает код. После запуска приложения можно задать точки останова и использовать отладчик для проверки кода, языковых стандартов и контрольных значений.

Для остановки отладки нажмите SHIFT F5.

Эмулятор является отдельным процессом, который продолжает выполняться. Вы можете изменять, компилировать и развертывать код несколько раз в одном эмуляторе.

Источник

Native Window

ANativeWindow represents the producer end of an image queue.

Summary

It is the C counterpart of the android.view.Surface object in Java, and can be converted both ways. Depending on the consumer, images submitted to ANativeWindow can be shown on the display or sent to other consumers, such as video encoders.

Enumerations

ANativeWindowTransform <
ANATIVEWINDOW_TRANSFORM_IDENTITY = 0x00,
ANATIVEWINDOW_TRANSFORM_MIRROR_HORIZONTAL = 0x01,
ANATIVEWINDOW_TRANSFORM_MIRROR_VERTICAL = 0x02,
ANATIVEWINDOW_TRANSFORM_ROTATE_90 = 0x04,
ANATIVEWINDOW_TRANSFORM_ROTATE_180 = ANATIVEWINDOW_TRANSFORM_MIRROR_HORIZONTAL | ANATIVEWINDOW_TRANSFORM_MIRROR_VERTICAL,
ANATIVEWINDOW_TRANSFORM_ROTATE_270 = ANATIVEWINDOW_TRANSFORM_ROTATE_180 | ANATIVEWINDOW_TRANSFORM_ROTATE_90
> enum ANativeWindow_LegacyFormat <
WINDOW_FORMAT_RGBA_8888 = AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
WINDOW_FORMAT_RGBX_8888 = AHARDWAREBUFFER_FORMAT_R8G8B8X8_UNORM,
WINDOW_FORMAT_RGB_565 = AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM
> enum

Typedefs

Functions

ANativeWindow_lock(ANativeWindow *window, ANativeWindow_Buffer *outBuffer, ARect *inOutDirtyBounds) ANativeWindow_setBuffersGeometry(ANativeWindow *window, int32_t width, int32_t height, int32_t format) ANativeWindow_setFrameRate(ANativeWindow *window, float frameRate, int8_t compatibility) ANativeWindow_setFrameRateWithChangeStrategy(ANativeWindow *window, float frameRate, int8_t compatibility, int8_t changeFrameRateStrategy)

Structs

Struct that represents a windows buffer.

Enumerations

ANativeWindowTransform

Transforms that can be applied to buffers as they are displayed to a window.

Supported transforms are any combination of horizontal mirror, vertical mirror, and clockwise 90 degree rotation, in that order. Rotations of 180 and 270 degrees are made up of those basic transforms.

Properties
ANATIVEWINDOW_TRANSFORM_IDENTITY
ANATIVEWINDOW_TRANSFORM_MIRROR_HORIZONTAL
ANATIVEWINDOW_TRANSFORM_MIRROR_VERTICAL
ANATIVEWINDOW_TRANSFORM_ROTATE_180
ANATIVEWINDOW_TRANSFORM_ROTATE_270
ANATIVEWINDOW_TRANSFORM_ROTATE_90
Читайте также:  Pdf сканер документов для android

ANativeWindow_ChangeFrameRateStrategy

Change frame rate strategy value for ANativeWindow_setFrameRate.

Change the frame rate even if the transition is going to be non-seamless, i.e.

with visual interruptions for the user.

Change the frame rate only if the transition is going to be seamless.

ANativeWindow_FrameRateCompatibility

Compatibility value for ANativeWindow_setFrameRate.

Properties
ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS

There are no inherent restrictions on the frame rate of this window.

When the system selects a frame rate other than what the app requested, the app will be able to run at the system frame rate without requiring pull down. This value should be used when displaying game content, UIs, and anything that isn’t video.

This window is being used to display content with an inherently fixed frame rate, e.g. a video that has a specific frame rate.

When the system selects a frame rate other than what the app requested, the app will need to do pull down or use some other technique to adapt to the system’s frame rate. The user experience is likely to be worse (e.g. more frame stuttering) than it would be if the system had chosen the app’s requested frame rate. This value should be used for video content.

ANativeWindow_LegacyFormat

Legacy window pixel format names, kept for backwards compatibility.

New code and APIs should use AHARDWAREBUFFER_FORMAT_*.

Properties
ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT

Red: 8 bits, Green: 8 bits, Blue: 8 bits, Alpha: 8 bits.

Red: 8 bits, Green: 8 bits, Blue: 8 bits, Unused: 8 bits.

Red: 5 bits, Green: 6 bits, Blue: 5 bits.

Typedefs

ANativeWindow

Opaque type that provides access to a native window.

A pointer can be obtained using ANativeWindow_fromSurface().

ANativeWindow_Buffer

Struct that represents a windows buffer.

A pointer can be obtained using ANativeWindow_lock().

Functions

ANativeWindow_acquire

Acquire a reference on the given ANativeWindow object.

This prevents the object from being deleted until the reference is removed.

ANativeWindow_getBuffersDataSpace

Get the dataspace of the buffers in window.

Available since API level 28.

Properties
WINDOW_FORMAT_RGBA_8888

ANativeWindow_getFormat

Return the current pixel format (AHARDWAREBUFFER_FORMAT_*) of the window surface.

Details
Returns

ANativeWindow_getHeight

Return the current height in pixels of the window surface.

Details
Returns

ANativeWindow_getWidth

Return the current width in pixels of the window surface.

Details
Returns

ANativeWindow_lock

Lock the window’s next drawing surface for writing.

inOutDirtyBounds is used as an in/out parameter, upon entering the function, it contains the dirty region, that is, the region the caller intends to redraw. When the function returns, inOutDirtyBounds is updated with the actual area the caller needs to redraw this region is often extended by ANativeWindow_lock.

Details
Returns

ANativeWindow_release

Remove a reference that was previously acquired with ANativeWindow_acquire().

ANativeWindow_setBuffersDataSpace

All buffers queued after this call will be associated with the dataSpace parameter specified.

dataSpace specifies additional information about the buffer. For example, it can be used to convey the color space of the image data in the buffer, or it can be used to indicate that the buffers contain depth measurement data instead of color images. The default dataSpace is 0, ADATASPACE_UNKNOWN, unless it has been overridden by the producer.

Available since API level 28.

Details
Returns
Details
Parameters

ANativeWindow_setBuffersGeometry

Change the format and size of the window buffers.

The width and height control the number of pixels in the buffers, not the dimensions of the window on screen. If these are different than the window’s physical size, then its buffer will be scaled to match that size when compositing it to the screen. The width and height must be either both zero or both non-zero.

For all of these parameters, if 0 is supplied then the window’s base value will come back in force.

window
Details
Parameters

ANativeWindow_setBuffersTransform

Set a transform that will be applied to future buffers posted to the window.

Available since API level 26.

window
Details
Parameters

ANativeWindow_setFrameRate

Same as ANativeWindow_setFrameRateWithChangeStrategy(window, frameRate, compatibility, ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS).

Available since API level 30.

ANativeWindow_setFrameRateWithChangeStrategy

Sets the intended frame rate for this window.

On devices that are capable of running the display at different refresh rates, the system may choose a display refresh rate to better match this window’s frame rate. Usage of this API won’t introduce frame rate throttling, or affect other aspects of the application’s frame production pipeline. However, because the system may change the display refresh rate, calls to this function may result in changes to Choreographer callback timings, and changes to the time interval at which the system releases buffers back to the application.

Note that this only has an effect for windows presented on the display. If this ANativeWindow is consumed by something other than the system compositor, e.g. a media codec, this call has no effect.

You can register for changes in the refresh rate using AChoreographer_registerRefreshRateCallback.

Available since API level 31.

window
Details
Parameters

ANativeWindow_tryAllocateBuffers

Provides a hint to the window that buffers should be preallocated ahead of time.

Note that the window implementation is not guaranteed to preallocate any buffers, for instance if an implementation disallows allocation of new buffers, or if there is insufficient memory in the system to preallocate additional buffers

Available since API level 30.

ANativeWindow_unlockAndPost

Unlock the window’s drawing surface after previously locking it, posting the new buffer to the display.

window

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.

Источник

Читайте также:  Найти мой девайс андроид
Оцените статью
Details
Returns