Making android app with c

Getting started with C++ and Android Native Activities

Introduction

I would like to walk you through setting up a simple Android Native Activity. I will walk through the basic setup, and try to give you the tools you need to move forward.

Although my focus is on games, I will not be telling you how to write an OpenGL application or how to architect your own game engine. That is a discussion that literally fills up books.

Why C++

On Android, the OS and its supporting infrastructure are designed to support applications written in the Java or Kotlin programming languages. Applications written in these languages benefit from tooling embedded deep into the system’s underlying architecture. Many core Android system features, such as the Android UI and Intent handling, are only exposed through Java interfaces.

By choosing to use C++, you are not being “more native” to Android than using a managed language such as Kotlin or Java. Counter intuitively, you are in some ways writing a foreign application with only a subset of Android features available. For most applications, you’re better off with languages like Kotlin.

There are a few exceptions to this rule. Near and dear to my own heart is game development. Since games typically use custom rendering logic, often written in OpenGL or Vulkan, it’s expected that a game looks different from a standard Android application. When you also consider that C and C++ are near universal to every computing platform, and the relative wealth of C libraries to support games development, it may become reasonable to set off down the path of native development.

If you want to make a game from scratch or port over an existing game, Android’s Native Development Kit (or NDK) and its supporting tooling are ready and waiting. In fact, the native activity I’ll be showing you provides an easy one-stop shop in which you can set up an OpenGL canvas and start gathering user input. You may find that despite C’s cognitive overhead, some common code challenges like building vertex attribute arrays from game data become easier in C++ than higher level languages.

What I won’t Cover

I will stop short of showing you how to initialize a Vulkan or OpenGL context. I recommend reading through the samples Google provides, although I will provide some tips to make your life easier. You may opt instead to use a library like SDL or even Google’s FPLBase instead.

Читайте также:  Управление поворот экрана для андроид

Setup your IDE

First we need to make sure that you have everything installed for native development. For this, we need the Android NDK. Launch Android Studio:

Источник

Создание нативных Android-приложений с использованием компилятора Intel C++ Compiler в Android Studio 1.0.1

На момент написания этого текста текущей версией Android Studio была версия 1.0.1. Компилятор Intel C++ Compiler for Android, будучи частью Intel Integrated Native Developer Experience (Intel INDE), поддерживает Android Studio 1.0.1 в Intel INDE 2015 Update 1. Поскольку Android Studio 1.0.1 не поддерживает Android NDK, в этой статье описаны шаги для создания нативного Android-приложения с использованием Android NDK r10d и компилятора Intel C++ Compiler for Android. Поехали!

Android Studio в качестве системы сборки использует Gradle. На момент написания статьи Gradle в процессе сборки вызывала систему NDK. В Android NDK r10 и более поздней версии после инсталляции Intel INDE компилятор Intel C++ Compiler for Android (ICC) не является более используемым по умолчанию компилятором в системе сборки NDK.

Представленные ниже шаги дают общее описание подготовки, сборки и выполнения нативного приложения в Android Studio 1.0.1.

Если вы используете Android Studio 0.8.6, почитайте статью «Сборка нативных Android-приложений с использованием компилятора Intel C++ Compiler в Android Studio», где рассказывается о применении Intel C++ Compiler.

Требуемые программные инструменты

Успешная инсталляция INDE 2015 Update 1 с Android Studio Integration гарантирует, что вы располагаете всем необходимым программным обеспечением. Детальные требования к программному обеспечению и системе описаны в документе Intel C++ Compiler Release Notes for Intel Integrated Native Developer Experience 2015.

Приведенные в данной статье инструкции предполагают использование следующего ПО для архитектуры IA-32 и Intel-64:

  • Oracle JDK 7 (нативный Intel-64 JDK для систем Windows x64)
  • Android SDK 20 или старше
  • NDK r10d (предполагается инсталляция в [ndk-dir] )
  • Android Studio 1.0.1

Убедитесь, что в переменную среды PATH добавлены следующие директории Android NDK (если они отсутствуют, добавьте):

Использование компилятора Intel C++ Compiler в Android Studio 1.0.1

После инсталляции Intel C++ Compiler 15.0 for Android в папку «[ndk-dir]\toolchains» (директория по умолчанию – «C:\Intel\INDE\IDEintegration\android-ndk-r10d\toolchains») устанавливаются следующие элементы:

  • x86-icc
  • x86-icc15.0.X.YYY
  • x86_64-icc (если NDK поддерживает 64-разрядные цели)
  • x86_64-icc15.0.X.YYY (если NDK поддерживает 64-разрядные цели)

Для NDK до r9d: после инсталляции нативным компилятором C/C++ будет Intel C++ Compiler. Дополнительных шагов для использования Intel C++ Compiler с Android Studio не требуется. Ели вы хотите для построения нативного кода использовать GNU gc, следуйте инструкциям в «Замена компилятора по умолчанию с Intel C++ Compiler на GCC для целевых приложений x86».

Для NDK r10 — r10d: компилятор Intel C++ после инсталляции не является компилятором по умолчанию. Чтобы использовать Intel C++ Compiler из Android Studio, следуйте шагам 3, 4, 5 ниже.

Если у вас установлено несколько Android NDK, следуйте инструкциям в статье «Интеграция Intel C++ Compiler for Android с несколькими Android NDK».

Теперь создадим новый проект Android для Intel-64 с нативным вызовом функции, продемонстрировав тем самым использование компилятора Intel C++ Compiler:

1. Создание нового проекта Android с нативным интерфейсом:

1. Откройте Android Studio, создайте новый Android-проект «nativeDemo» с параметрами по умолчанию, например:

2. Откройте «app\src\main\java\MainActivity.java» и добавьте в конец класса «MainActivity» нативную функцию как показано ниже:

Должно получиться примерно так:

3. Чтобы создать проект «nativeDemo», выберите: «Build > Make Project», после чего можно будет использовать «javah».
4. В «View > Tools Windows > Terminal» откройте терминальное окно и выполните указанные ниже шаги для запуска «javah» и создания заголовка jni:
a) В терминальном окне перейдите в подпапку «src\main»:

Читайте также:  Ворлд соккер чампс андроид

b) Чтобы создать «com_example_nativedemo_app_MainActivit.h» в папке src\main\jni, выполните следующую команду «javah» cmd:

5. В окне Project измените вид на Project, щелкните правой кнопкой мыши на папке «src» и выберите «Synchronize ‘src». Теперь в папке «src\main\jni» можно видеть файл заголовка «com_example_mydemo_nativedemo_MainActivity.h».

2. Добавление нативного исходного кода: main.c

1. Создайте «main.c»: выделите файл «com_example_mydemo_nativedemo_MainActivity.h», используйте волшебные клавиши copy/paste для создания нового «main.c» со следующим кодом:

2. Сохраните изменения
3. Теперь в папке «jni» у вас два файла: com_example_mydemo_nativedemo_MainActivity.h и main.c

3. Добавление make-файла: Android.mk

1. Щелкните правой кнопкой на папке «jni», выберите «New > File»
2. Наберите «Android.mk» и щёлкните на «OK»
3. Добавьте в этот файл следующие строки (обратите внимание, что строка LOCAL_SRC_FILES должна содержать исходные файлы, которые находятся в папке «jni»):

4. Добавление make-файла: Application.mk

1. Щелкните правой кнопкой на папке «jni», выберите «New > File»
2. Наберите «Application.mk» и щёлкните на «OK»
3. Добавьте в этот файл следующие строки:

4. [Опционально] Для изменения параметров компилятора используйте следующее:

5. Сконфигурируйте свое приложение для выполнения ndk-build с помощью make-файлов

1. Откройте файл «app\build.gradle»
2. Добавьте в начало файла следующий импорт:

3. И эти строки после секции «defaultConfig»:

4. А следующие строки – в конец файла:

5. Сохраните изменения
6. Теперь создадим проект: выберите [Build > Make Project]. Вы увидите все выходные папки и файлы «libmain.so» в папках «main\libs» и «main\obj\local».

6. Добавьте ID «hello_textview» в виджет textview

Откройте «res\layout\activity_main.xml» и измените виджет «textview» как показано ниже:

7. Обновите «MainActivity.java», чтобы UI textview вызов нативной библиотеки:

Для импорта виджета TextView и сохранения изменений нажмите ALT+Enter.

8. Запустите виртуальную машину Android Virtual Machine «Intel-Nexus 7 x64» и выполните приложение, щёлкнув кнопку «Run».

Это означает, что был использован компилятор Intel C++ Compiler for Android.

Источник

Create an Android Native Activity App

When you install the cross-platform Mobile development with C++ workload, Visual Studio can be used to create fully functional Android Native Activity apps. The Android Native Development Kit (NDK) is a toolset that allows you to implement the majority of your Android app using pure C/C++ code. Some Java JNI code acts as glue to allow your C/C++ code to interact with Android. The Android NDK introduced the ability to create Native Activity apps with Android API Level 9. Native Activity code is popular for creating gaming and graphic intensive apps that use Unreal Engine or OpenGL. This topic will guide you through creation of a simple Native Activity app that uses OpenGL. Additional topics walk through the developer lifecycle of editing, building, debugging and deploying Native Activity code.

Requirements

Before you can create an Android Native Activity app, you must make sure you’ve met all system requirements, and installed the Mobile development with C++ workload in Visual Studio. For more information, see Install cross-platform mobile development with C++. Make sure that the required third-party tools and SDKs are included in the installation, and that an Android emulator is installed.

Читайте также:  Proxy handler андроид что это

Create a new Native Activity project

In this tutorial, you’ll first create a new Android Native Activity project and then build and run the default app in an Android emulator.

In Visual Studio, choose File > New > Project.

In the New Project dialog box, under Templates, choose Visual C++ > Cross Platform, and then choose the Native-Activity Application (Android) template.

Give the app a name like MyAndroidApp, and then choose OK.

Visual Studio creates the new solution and opens Solution Explorer.

In Visual Studio, choose File > New > Project.

In the Create a new project dialog box, select the Native-Activity Application (Android) template, and then choose Next.

In the Configure your new project dialog box, enter a name like MyAndroidApp in Project name, and then choose Create.

Visual Studio creates the new solution and opens Solution Explorer.

The new Android Native Activity app solution includes two projects:

MyAndroidApp.NativeActivity contains the references and glue code for your app to run as a Native Activity on Android. The implementation of the entry points from the glue code are in main.cpp. Precompiled headers are in pch.h. This Native Activity app project is compiled into a shared library .so file which is picked up by the Packaging project.

MyAndroidApp.Packaging creates the .apk file for deployment on an Android device or emulator. This contains the resources and AndroidManifest.xml file where you set manifest properties. It also contains the build.xml file that controls the Ant build process. It’s set as the startup project by default, so that it can be deployed and run directly from Visual Studio.

Build and run the default Android Native Activity app

Build and run the app generated by the template to verify your installation and setup. For this initial test, run the app on one of the device profiles installed by the Android emulator. If you prefer to test your app on another target, you can load the target emulator or connect the device to your computer.

To build and run the default Native Activity app

If it is not already selected, choose x86 from the Solution Platforms dropdown list.

If the Solution Platforms list isn’t showing, choose Solution Platforms from the Add/Remove Buttons list, and then choose your platform.

On the menu bar, choose Build > Build Solution.

The Output window displays the output of the build process for the two projects in the solution.

Choose one of the Android emulator profiles as your deployment target.

If you have installed other emulators or connected an Android device, you can choose them in the deployment target dropdown list.

Press F5 to start debugging, or Shift+F5 to start without debugging.

Here’s what the default app looks like in an Android emulator.

Visual Studio starts the emulator, which takes a few seconds to load and deploy your code. Once your app has started, you can set breakpoints and use the debugger to step through code, examine locals, and watch values.

Press Shift+F5 to stop debugging.

The emulator is a separate process that continues to run. You can edit, compile, and deploy your code multiple times to the same emulator.

Источник

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