Как написать приложение для android на с
Перейти к содержимому

Как написать приложение для android на с

  • автор:

Разработка мобильных приложений на C++ | UWP, Android и iOS

Создавайте в Visual Studio приложения на C++ непосредственно для устройств с iOS, Android и Windows.

Научитесь создавать кроссплатформенные мобильные приложения.

Начало работы

Общие сведения

Учебник

Обучение

Справка по кроссплатформенной разработке

Ссылка

  • Ссылка на страницу кроссплатформенных свойств C++
  • Документация по универсальной платформе Windows (UWP)
  • Документация по API для iOS
  • Документация по API для Android

Значок отказа согласно Закону Калифорнии о защите конфиденциальности потребителей (CCPA)

  • Светлая
  • Темная
  • Высокая контрастность
  • Предыдущие версии
  • Блог
  • Участие в доработке
  • Конфиденциальность
  • Условия использования
  • Товарные знаки
  • © Microsoft 2023

Значок отказа согласно Закону Калифорнии о защите конфиденциальности потребителей (CCPA)

  • Светлая
  • Темная
  • Высокая контрастность
  • Предыдущие версии
  • Блог
  • Участие в доработке
  • Конфиденциальность
  • Условия использования
  • Товарные знаки
  • © Microsoft 2023

Разработка кроссплатформенных мобильных приложений на языке C++

Вы можете создавать собственные приложения на языке C++ для iOS, Android и Windows устройств, используя кроссплатформенные инструменты, доступные в Visual Studio. Разработка мобильных приложений на языке C++ — это рабочая нагрузка, доступная в программе установки Visual Studio. Она устанавливает пакеты SDK и средства, необходимые для кроссплатформенной разработки общих библиотек и собственных приложений. После ее установки язык C++ можно использовать для создания кода, выполняющегося на устройствах и платформах с iOS и Android, Windows, Windows Store, и Xbox.

Написание кода для различных платформ может часто быть утомительным. Основные языки и средства разработки для iOS, Android и Windows для каждой платформы различны. Однако все платформы поддерживают написание кода на языке C++. Это общий знаменатель, который обеспечивает использование основной части кода на разных платформах. Машинный код, написанный на языке C++, может быть более производительным и устойчивым к реконструированию. Повторное использование кода позволяет сэкономить время и силы при создании приложений для разных платформ.

Использование языка C++ для разработки кроссплатформенных мобильных приложений имеет несколько преимуществ.

  • Простая установка. Установщик Visual Studio получает и устанавливает средства и пакеты SDK сторонних разработчиков, необходимые для создания приложений или библиотек для Android и iOS. Установка и настройка просты и в основном производятся автоматически.
  • Эффективная и привычная среда сборки. Шаблоны Visual Studio позволяют легко создавать общие кроссплатформенные решения и проекты. Управлять свойствами для всех проектов можно с помощью единого интерфейса. Редактируйте весь код в редакторе Visual Studio и используйте встроенную кроссплатформенную функцию IntelliSense для автозавершения и выделения ошибок.
  • Унифицированный процесс отладки. Используйте средства отладки мирового класса в Visual Studio для просмотра и пошагового перехода по коду C++ на всех платформах: устройства и эмуляторы Android, симуляторы iOS и устройства, а также устройства Windows или Магазина Windows и эмуляторы.

Получение инструментов

Разработка мобильных приложений с помощью C++ — это устанавливаемая рабочая нагрузка, поставляемая с Visual Studio. Сведения о необходимых компонентах и инструкции по установке см. в статье Установка Visual C++ для разработки кроссплатформенных мобильных приложений на языке C++. Для создания кода для iOS также требуются компьютер Mac и учетная запись разработчика Apple iOS. Дополнительные сведения см. в статье Установка и настройка средств для разработки с помощью iOS.

Быстрое начало работы

Если у вас есть опыт разработки для Android или iOS, мы можем предложить вам отличные материалы, которые помогут вам приступить к работе. Visual Studio — это выразительная среда разработки с широкими возможностями. Чтобы научиться использовать ее, попробуйте обратиться к руководству по началу работы для разработчиков решений Android или руководству по началу работы для разработчиков решений iOS. В этих статьях вы получите общие сведения о Visual Studio и ознакомитесь с понятиями, которые нужно знать для разработки кроссплатформенных приложений для Windows и Windows Store. Чтобы приступить к созданию первого кроссплатформенного приложения для iOS и Android, обратитесь к разделу Создание приложения OpenGL ES в Android и iOS.

Рабочая нагрузка Visual C++ для разработки кроссплатформенных мобильных приложений включает несколько шаблонов, которые помогут вам приступить к созданию приложений:

  • Нативное приложение (Android) Создает полнофункциональное приложение C++ OpenGL в форме проекта Android Native Activity.
  • Приложение OpenGLES (Android, iOS) Создает решение с набором проектов для приложения Android Native Activity и приложения iOS. Эти приложения используют библиотеки для конкретных платформ, созданные с помощью общего кода C++ OpenGL ES, с целью отрисовки одинакового вращающегося куба.
  • Общая библиотека (Android, iOS) Создает решение с проектами, предназначенными для создания файлов динамической библиотеки Android (SO) и статической библиотеки iOS (A) с помощью общего кода C++ в общем проекте.
  • Простое приложение (Android, Ant) Создает проект приложения Hello, World для Android, в котором используется только исходный код Java и система сборки Ant.
  • Простое приложение (Android, Gradle) Создает проект приложения Hello, World для Android, в котором используется только исходный код Java и система сборки Gradle.
  • Простая библиотека (Android, Ant) Создает проект библиотеки Hello, World для Android, в котором используется только исходный код Java и система сборки Ant.
  • Простая библиотека (Android, Gradle) Создает проект библиотеки Hello, World для Android, в котором используется только исходный код Java и система сборки Gradle.
  • Динамическая общая библиотека (Android) Создает файл динамической библиотеки Android (SO) с помощью кода C++.
  • Приложение OpenGLES 2 (iOS) Создает решение с набором проектов для сборки приложения iOS OpenGL ES 2. Приложение использует библиотеку кода C++ OpenGL ES для рисования вращающегося куба в приложении iOS. Это приложение может стать хорошей отправной точкой для ознакомления с импортом библиотек C++ в приложение iOS.
  • Статическая библиотека (Android) Создает проект для сборки статической библиотеки для Android. Приложение Android может быть связано только с одной динамической библиотекой, но с любым количеством статических библиотек.
  • Статичная библиотека (iOS) Создает проект для сборки статической библиотеки для iOS.
  • Проект Makefile (Android) Создает оболочку проекта для ваших собственных проектов Android, использующих файл makefile.

Испытайте образец кода

Скачайте образцы, демонстрирующие создание библиотек общего кода, которые можно использовать в приложениях Windows, Android и iOS. См. примеры создания готовых приложений для Android. Чтобы приступить к работе, см. раздел Примеры разработки кроссплатформенных мобильных приложений.

Разработка приложений для Android с C#

Monodroid и Monotouch это фреймворки от xamarin, которые дают возможность разрабатывать приложение на языке C# для Android и iOS соответственно. Так как это относительно новая технология информации в интернете не слишком много (за исключением офф сайта и большого количества тем на stackoverflow.com), на русском языке же я не нашел никаких туториалов и информации вообще.

Что бы устранить это недоразумение решил написать небольшой туториал о том как начать разрабатывать приложения под мобильные платформы при помощи этих фреймворков. В этой статье я рассмотрю только Monodroid.

image

Что нужно для начала разработки?
1) Visual studio C# версии professional и выше (пойдет и крякнутая)
2) Сам фреймворк (а он, в свою очередь установит за нас и джаву, и виртуальную машину и все остальное)

Если с первым все понятно, то со вторым сложнее- как оказалось в процессе использования фришная версия монодроида не умеет компилировать .apk файлы, так что стоит либо его купить, либо воспользоваться кряком из интернета (который лежит далеко не на первой странице гугла).

Запустив после установки всего необходимого студию мы заметим новые типы проектов для создания:

Выбираем Android Application. Будет создано несколько стандартных директорий:

В папке Assets хранятся все используемые программой файлы аля видео, звуков, хтмл файлов и т.д. Изначально в ней ничего нет кроме текстовика с описанием самой директории и для чего она нужна.

В папке Drawable нужно размещать файлы изображений, используемые программой.

Папка Layout содержит файлы графического интерфейса.
В папке Values различные параметры, которые можно создавать и загружать при работе приложения (к примеру можно запомнить логин и пароль туда).

После создания пустого проекта мы можем его скомпилировать, нажав F5 — откроется настройки виртуальной машины с выбором устройства на котором запускать тест программы. Если подсоединить свой девайс на андроиде со включенной функцией отладки по USB (это в настройках, вкладка «для разработчика») то можно запустить и потестить непосредственно на нем. Очень советую проводить тесты на реальном устройстве т.к. многие тач элементы нельзя протестировать на виртуалке, к тому же, лично у меня на виртуальной машине приложение развертывается довольно долго. Между компиляцией и запуском на виртуалке проходит около минуты.

По умолчанию мы имеем кнопку, при нажатии на которую будет выведено сколько раз мы кликнули по оной. Попробуем сделать что-нибудь поинтереснее.

Откроем файл интерфейса и попробуем его поменять.

Снизу 2 вкладки- просмотр кода интерфейса и самого интерфейса. Справа- различные компоненты.
Сразу скажу: пользоваться встроенной формоклепалкой это не для слабонервных. Она на столько лагуча и делает не то, что ожидаешь что просто ужас. Вместо этого можно пользоваться сайтом droiddraw.org после составления интерфейс там и нажатие на кнопку Generate можно скопипастить код во вкладку кода и все будет ок.

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

Есть несколько типов расположения объектов на экране- типов слоев. При этом многие из них могут содержать друг друга и уживаться вместе. Рассмотрим из них:

1) LinearLayout — каждый элемент ниже предыдущего.
2) RelativeLayout — каждый элемент находится по отношению к предыдущему (к примеру, можно задать параметр находиться слева от кнопки1, снизу от текстбокса, в отступе в 40 пикселей снизу от кнопки 2 и т.д.

Настройки каждого компонента у нас в окне свойств- все довольно привычно, а сами свойства схожи с винформ элементами.

Создав более или менее привлекательный интерфейс его надо как то запустить.
Для этого существует Activity. По умолчанию у нас файл с названием Activity1, в котором класс- наследник от класса Activity.

Строка над объявлением класса-
[Activity(Label = «AndroidApplication1», MainLauncher = true, Icon = «@drawable/icon»)]
описывает заголовок окна приложения, иконку и узнает запускать ли эту активити при запуске приложения.
Из основной автозапускаемой активити можно запустить любую другую. После автозагрузки данной активити после старта приложения мы загружаем интерфейс строкой SetContentView(Resource.Layout.Main);

Для получения доступа к любому элементу мы должны воспользоваться функцией FindViewById<>(); при присвоении экземпляру класса таго элемента, который нам нужен. Конкретно в нашем примере мы видим строчку

«MyButton» это название кнопки, посмотреть его можно при создании интерфейса во вкладке код.

Посредством простой конструкции Button button = FindViewById(Resource.Id.MyButton);
мы можем работать с кнопкой и обрабатывать все действия с ней. В данном случае обработчик клика выглядит так:

Спроектировав и написав приложение мы моем скомпилировать apk файл посредством перехода во вкладку построение и нажатии кнопки Package for android. В папке проекта появится 2 файла, один из которых подписан автоматической подписью- его мы и можем использовать для установки па устройство.

На этом, думаю, этот краткий туториал можно закончить. В будущем скорее всего напишу подобный туториал по портированию и разработке на iOS.

  • Разработка мобильных приложений
  • C#

Android and iOS development with C++ in Visual Studio

Content outdated For up-to-date documentation see Mobile development with C++ documentation . For an overview of the Visual Studio capabilities described in this article, see Develop C and C++ applications.

When it comes to building mobile applications, many developers write most or a part of the apps in C++. Why? Those who are building computationally intensive apps such as games and physics simulations choose C++ for its unparalleled performance, and the others choose C++ for its cross-platform nature and the ability to leverage existing C/C++ libraries in their mobile applications. Whether you’re targeting Universal Windows Platform (UWP), Android, or iOS, Visual Studio enables building cross-platform C++ mobile applications with full editing and debugging capabilities all in one single IDE. In this blog post, we will focus on how to build Android and iOS apps with C++ in Visual Studio. First we will talk a look at how to acquire the tools for Android and iOS development, then we will create a few C++ mobile apps using the built-in templates. Next we will use the Visual Studio IDE to write C++ and Java code, then we will use the world-class Visual Studio debugger to catch issues in C++ and Java code. Finally, we will talk about how the C++ mobile solution can be used in conjunction with Xamarin.

Install Visual Studio for Android and iOS development

1-vs-install

First, download Visual Studio 2017 and launch the Visual Studio installer. To build Android or iOS applications, choose the “Mobile development with C++” workload under the “Mobile & Gaming” category. Android development: By default, this workload includes the core Visual Studio editor, the C++ debugger, GCC and Clang compilers, Android SDKs and NDKs, Android build tools, Java SDK, and C++ Android development tools. You could choose to install the Google Android Emulator in the Optional Component list if you don’t have an Android device for testing. This should give you everything you need to start building Android applications. iOS development: if you’re also targeting iOS, check “C++ iOS development tools” in the Optional Component list and you would be good to go.

Create a new Android application using project templates

If you plan to start with targeting Android first and worry about other platforms later, the VS built-in Android project templates including Native-Activity Application, Static Library, Dynamic Shared Library, could be a great starting point. If you’d rather start with a cross-platform solution to target multiple mobile platforms, jump to the next section Build an OpenGLES Application on Android and iOS where we’ll talk about building an app that targets both platforms with shared C++ code. You can find the Android templates under Visual C++ -> Cross Platform -> Android node. 2-templatesHere we’re going to create a new Native Activity Application (Android), which is popular for creating games and graphical-intensive apps. Once the project is created, in the Solution Platforms dropdown, choose the right architecture that matches the Android emulator or device that you’re using, and then press F5 to run the app. 3-solution-platformsBy default, Visual Studio uses the Clang toolchain to compile for Android. The app should build and run successfully, and you should see the app changing colors in the background. This article Create an Android Native Activity App discusses the Native Activity project in more details.

Build an OpenGLES Application on Android and iOS

The OpenGL ES Application project template under Visual C++->Cross Platform node is a good starting point for a mobile app targeting both Android and iOS. OpenGL ES (OpenGL for Embedded Systems or GLES) is a 2D and 3D graphics API that is supported on many mobile devices. This template creates a simple iOS app and an Android Native Activity app which has C++ code in common that uses OpenGL ES to display the same animated rotating cube on each platform. 4-opengles-templateThe created OpenGL ES Application solution includes three library projects in the Libraries folder, one for each platform and the other one for shared C++ code, and two application projects for Android and iOS respectively. 5-solution-explorerNow let’s run this app on both Android and iOS.

Build and run the app on Android

The solution created by the template sets the Android app as the default project. Just like run the Android Native Activity app we discussed earlier, in the Solution Platforms dropdown, select the right architecture that matches the Android emulator or device that you’re using, and then press F5 to run the app. The OpenGL ES app should build and run successfully and you will see a colored 3D spinning cube.

Build and run the app on iOS

6-ios-simulator

The iOS project created in the solution can be edited in Visual Studio, but because of licensing restrictions, it must be built and deployed from a Mac. Visual Studio communicates with a remote agent running on the Mac to transfer project files and execute build, deployment, and debugging commands. You can setup your Mac by following instructions Install And Configure Tools to Build using iOS. Once the remote agent is running on the Mac and Visual Studio is paired to it, we can build and run the iOS app. In the Solution Platforms dropdown in Visual Studio, choose the right architecture for the iOS simulator (x86) or the iOS device. In Solution Explorer, open the context menu for the OpenGLESApp1.iOS.Application project and choose Build. Then choose iOS Simulator on the toolbar to run the app in the iOS Simulator on your Mac. You should see the same colored 3D spinning cube in the iOS Simulator. This article Build an OpenGL ES Application on Android and iOS includes more details about the OpenGLES project.

Visual Studio to target all mobile platforms

7-shared-project

If you’re building an app to target multiple mobile platforms (Android, iOS, UWP) and wish to share the common code in C++, you can achieve this by having one single Visual Studio solution and leverage the same code-authoring and debugging experience all in the same IDE. With Visual Studio, you can easily share and re-use your existing C++ libraries through the shared project component to target multiple platforms. The following screenshot shows a single solution with 4 projects, one for each mobile platform and one shared project for common C++ code. To learn more, please refer to how Half Brick makers of popular mobile games Fruit Ninja and Jetpack Joyride use Visual Studio for a C++ cross-platform mobile development experience.

Write cross-platform C++ code with the full power of Visual Studio IDE

With Visual Studio, you can write cross-platform C++ code using the same powerful IntelliSense and code navigation features, making code writing much more efficient. These editing capabilities not only light up in the common code, but are context-aware of the target platform when you write platform-specific code. Member list and Quick Info, as shown in the following screenshot, are just two examples of the IntelliSense features Visual Studio offers. Member list shows you a list of valid members from a type or namespace. Typing in “->” following an object instance in the C++ code will display a list of members, and you can insert the selected member into your code by pressing TAB, or by typing a space or a period. Quick Info displays the complete declaration for any identifier in your code. IntelliSense is implemented based on the Clang toolchain when targeting the Android platform. In the following screenshot, Visual Studio is showing a list of the available Android-specific functions when the Android Native Activity project is active. 8-editingAuto-complete, squiggles, reference highlighting, syntax colorization, code snippets are some of the other useful productivity features to be of great assistance in code writing and editing. Navigating in large codebases and jumping between multiple code files can be a tiring task. Visual Studio offers many great code navigation features, including Go To Definition, Go To Line/Symbols/Members/Types, Find All References, View Call Hierarchy, Object Browser, and many more, to boost your productivity. The Peek Definition feature, as shown in the following screenshot, brings the definition to the current code file, allows viewing and editing code without switching away from the code that you’re writing. You can find Peek Definition by opening the context menu on right click or shortcut Alt+F12 for a method that you want to explore. In the example in the screenshot, Visual Studio brings in the definition of __android_log_print method that is defined in the Android SDK log.h file as an embedded window into the current cpp file, making reading and writing Android code more efficiently. 9-peek-definition

Debug C++ code with the world-class Visual Studio debugger

10-debugging

Troubleshooting issues in the code can be time-consuming. Use the Visual Studio debugger to help find and fix issues faster. Set breakpoints in your Android C++ code and press F5 to launch the debugger. When the breakpoint is hit, you can watch the value of variables and complex expressions in the Autos and Watch windows as well as in the data tips on mouse hover, view the call stack in the Call Stack window, and step in and step out of the functions easily. In the example in the screenshot below, the Autos window is showing value changed in the Android sensorManager and accelerometerSensor types. The Android debugging experience in Visual Studio also supports for debugging pre-built Android application via other IDE(s), other basic debugger capabilities (tracepoints, conditional breakpoints) and advanced features such as debugger visualizations (Natvis Support) and attaching to a running Android application as well. You can find more information about the C++ debugger in this blog post C++ Debugging and Diagnostics.

Java debugging and language support for Android

Whether you’re writing Java or C++ code in your Android apps, Visual Studio has it covered. Visual Studio includes a Java Debugger that enables debugging Java source files in your Android projects, and with the Visual Studio Java Language Service for Android extension, you can also take advantage of the IntelliSense and browsing capabilities for Java files in the Visual Studio IDE.

Editing Java code

11-java-editing

First, install the Visual Studio Java Language Service for Android extension. It provides colorization (both syntactic and semantic), error and warning squiggles as well as code outlining and semantic highlighting in your Java files. You will also get IntelliSense assistance, such as Member List, Parameter Help, Quick Info, making writing Java code more efficient. In the following screenshot, Visual Studio provides a member list for the android.util.Log class. Another handy feature for larger codebases or for navigating 3rd party libraries for which you have the source code available is Go to definition (F12) which will take you to the symbol definition location if available.

Debugging Java code

To turn on Java debugging for your Android projects in your next debugging session, in the Debug Target toolbar, change Debug Type dropdown to “Java Only” as shown in the following screenshot. 12-java-settingNow you can set line breakpoints, including conditions or hit counts for the breakpoints, anywhere in the Java code. When a breakpoint is hit, you can view variables in the Locals and Autos window, see call stack in the Call Stack window, and check log output in the Logcat window. 13-java-debuggingBlog post Java debugging and language support in Visual Studio for Android has more details on this topic.

Build Xamarin Android Native Applications

Xamarin is a popular cross-platform solution for creating rich native apps using C# across mobile platforms while maximizing code reuse. With Xamarin, you could create apps with native user interfaces and get native performance on each mobile platform. If you want to leverage Xamarin for writing user interfaces in C# while re-using your existing C/C++ libraries, Visual Studio fully supports building and debugging Xamarin Android apps that reference C++ code. This blog post Developing Xamarin Android Native Applications describes this scenario in more details. Referencing C++ libraries in Xamarin iOS apps can be achieved by following this blog post Calling C/C++ libraries from Xamarin code.

Try out Visual Studio 2017 for mobile development with C++

Download Visual Studio 2017, try it out and share your feedback. For problems, let us know via the Report a Problem option in the upper right corner of the VS title bar. Track your feedback on the developer community portal. For suggestions, let us know through UserVoice.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *