- Общие сведения о разработке для Android в Windows Overview of Android development on Windows
- Нативные приложения для Android Native Android
- Поддержка разных платформ Cross-platform
- Выбор кросс-платформенной платформы Choosing a cross-platform framework
- Разработка игр Game development
- Get started developing for Android using Xamarin.Android
- Requirements
- Create a new Xamarin.Android project
- Create a UI with XAML
- Add logic code with C#
- Set the current time
- Update the current time once every second
- Add HourOffset
- Create the button Click event handlers
- Wire up the up and down buttons to their corresponding event handlers
- Completed MainActivity.cs file
- Run your app
Общие сведения о разработке для Android в Windows Overview of Android development on Windows
Существует несколько путей для разработки приложения для устройств Android с помощью операционной системы Windows. There are multiple paths for developing an Android device app using the Windows operating system. Эти пути делятся на три основных типа: Разработка собственных Android, Разработка на разных платформах и Разработка игр Android. These paths fall into three main types: Native Android development, Cross-platform development, and Android game development. Этот обзор поможет вам выбрать путь разработки для разработки приложения Android, а затем выполнить дальнейшие действия , которые помогут приступить к работе с Windows для разработки с помощью: This overview will help you decide which development path to follow for developing an Android app and then provide next steps to help you get started using Windows to develop with:
Кроме того, в этом руководство будут представлены советы по использованию Windows для: In addition, this guide will provide tips on using Windows to:
Нативные приложения для Android Native Android
Собственная разработка Android в Windows означает, что ваше приложение предназначено только для Android (а не для устройств iOS или Windows). Native Android development on Windows means that your app is targeting only Android (not iOS or Windows devices). Для разработки в экосистеме, разработанной специально для операционной системы Android, можно использовать Android Studio или Visual Studio . You can use Android Studio or Visual Studio to develop within the ecosystem designed specifically for the Android operating system. Производительность будет оптимизирована для устройств Android, внешний вид интерфейса пользователя будет соответствовать другим собственным приложениям на устройстве, а все функции или возможности устройства пользователя будут перенаправлены на доступ и использование. Performance will be optimized for Android devices, the user-interface look and feel will be consistent with other native apps on the device, and any features or capabilities of the user’s device will be straight-forward to access and utilize. Разработка приложения в собственном формате поможет ему просто «правильно», так как она соответствует всем шаблонам взаимодействия и стандартам пользователя, установленным специально для устройств Android. Developing your app in a native format will help it to just ‘feel right’ because it follows all of the interaction patterns and user experience standards established specifically for Android devices.
Поддержка разных платформ Cross-platform
Межплатформенные платформы предоставляют единую базу кода, которая может (в основном) совместно использоваться устройствами Android, iOS и Windows. Cross-platform frameworks provide a single codebase that can (mostly) be shared between Android, iOS, and Windows devices. Использование кросс-платформенной платформы позволяет приложению поддерживать одинаковый вид, впечатление и работу на разных платформах устройств, а также использовать преимущества автоматического развертывания обновлений и исправлений. Using a cross-platform framework can help your app to maintain the same look, feel, and experience across device platforms, as well as benefiting from the automatic rollout of updates and fixes. Вместо того, чтобы понимать различные языки кода для конкретных устройств, приложение разрабатывается в общей базе кода, как правило, на одном языке. Instead of needing to understand a variety of device-specific code languages, the app is developed in a shared codebase, typically in one language.
Хотя межплатформенные платформы ориентированы на удобство работы с собственными приложениями, они никогда не будут полностью интегрированы как приложения, разработанные в машинном код, и могут снизить производительность и снижение производительности. While cross-platform frameworks aim to look and feel as close to native apps as possible, they will never be as seamlessly integrated as a natively developed app and may suffer from reduced speed and degraded performance. Кроме того, средства, используемые для создания кросс-платформенных приложений, могут не иметь всех функций, предлагаемых на разных платформах устройств, которые могут потребовать решений. Additionally, the tools used to build cross-platform apps may not have all of the features offered by each different device platform, potentially requiring workarounds.
База кода обычно состоит из кода пользовательского интерфейса, предназначенного для создания пользовательского интерфейса, такого как страницы, кнопки, метки, списки и т. д., и кода логики для вызова веб-служб, доступа к базе данных, вызова возможностей оборудования и управления состоянием. A codebase is typically made up of UI code, for creating the user interface like pages, buttons controls, labels, lists, etc., and logic code, for calling web services, accessing a database, invoking hardware capabilities and managing state. В среднем 90% этого можно использовать повторно, хотя обычно требуется настроить код для каждой платформы устройства. On average, 90% of this can be reused, though there is typically some need to customize code for each device platform. Этот процесс обобщения во многом зависит от типа создаваемого приложения, но в нем есть несколько контекстов, которые помогут принять решение. This generalization largely depends on the type of app you’re building, but provides a bit of context that hopefully will help with your decision-making.
Выбор кросс-платформенной платформы Choosing a cross-platform framework
- Код пользовательского интерфейса: XML с Android Designer и темой материалов UI code: XML with Android Designer, and Material Theme
- Код логики: C# или F # Logic code: C# or F#
- По-прежнему можно коснуться некоторых собственных элементов Android, но лучше использовать базу кода для других платформ (iOS, Windows). Still able to tap into some native Android elements, but good for reuse of the code base for other platforms (iOS, Windows).
- На разных платформах совместно используются только логические коды, а не код пользовательского интерфейса. Only logic code is shared across platforms, not UI code.
- Отлично подходит для более сложных приложений с помощью пользовательского интерфейса для конкретного устройства. Great for more complex apps with a device-specific user interface.
- Код пользовательского интерфейса: XAML и .NET (с Visual Studio) UI code: XAML and .NET (with Visual Studio)
- Код логики: C # Logic code: C#
- Предоставляет общий доступ к 60 – 90% логики и коду пользовательского интерфейса в приложениях для устройств Android, iOS и Windows. Shares around 60–90% of the logic and UI code across Android, iOS, and Windows device apps.
- Использует общие пользовательские элементы управления, такие как кнопка, метка, запись, ListView, StackLayout, календарь, Таббедпаже и т. д. Создание кнопки и Xamarin Forms. будет показано, как вызывать собственную кнопку для каждой платформы с помощью библиотеки привязки для вызова кода Java или SWIFT из C#. Uses common user controls like Button, Label, Entry, ListView, StackLayout, Calendar, TabbedPage, etc. Create a Button and Xamarin Forms will figure out how to call the native button for each platform using the Binding Library to call Java or Swift code from C#.
- Отлично подходит для простых приложений, таких как внутренние или бизнес-приложения, прототипы или специалисты MVP. Great for simple apps, like internal or Line Of Business (LOB) apps, prototypes or MVPs. Любое приложение, которое может выглядеть довольно стандартным или универсальным, используя простой пользовательский интерфейс. Any app that can look somewhat standard or generic, utilizing a simple user interface.
- Код пользовательского интерфейса: JavaScript UI code: JavaScript
- Код логики: JavaScript Logic code: JavaScript
- Целью реагирования на себя является написание кода один раз и его запуск на любой платформе, а не однократное изучение (реагирование) и запись в любом месте. The goal of React Native isn’t to write the code once and run it on any platform, rather to learn-once (the React way) and write-anywhere.
- Сообщество добавило такие средства, как экспозиции, и создает реагирование на собственное приложение, чтобы помочь им в создании приложений без использования Xcode или Android Studio. The community has added tools such as Expo and Create React Native App to help those wanting to build apps without using Xcode or Android Studio.
- Аналогично Xamarin (C#), реагирующий машинный код (JavaScript) вызывает собственные элементы пользовательского интерфейса (без необходимости написания Java/Котлин или SWIFT). Similar to Xamarin (C#), React Native (JavaScript) calls native UI elements (without the need for writing Java/Kotlin or Swift).
- Код пользовательского интерфейса: HTML, CSS, JavaScript UI code: HTML, CSS, JavaScript
- Код логики: JavaScript Logic code: JavaScript
- Пвас — это веб-приложения, созданные с помощью стандартных шаблонов, позволяющие им воспользоваться преимуществами веб-и встроенных функций приложения. PWAs are web apps built with standard patterns to allow them to take advantage of both web and native app features. Они могут быть созданы без платформы, но несколько популярных платформ, которые следует учитывать, — это ионные и PhoneGap. They can be built without a framework, but a couple of popular frameworks to consider are Ionic and PhoneGap.
- Пвас может быть установлен на устройстве (Android, iOS или Windows) и может работать в автономном режиме благодаря неработающей службе-исполнителю. PWAs can be installed on a device (Android, iOS, or Windows) and can work offline thanks to the incorporation of a service-worker.
- Пвас можно распространять и устанавливать без магазина приложений, используя только URL-адрес. PWAs can be distributed and installed without an app store using only a web URL. Microsoft Store и Google Play Маркет допускают Пвас, магазин Apple в настоящее время не работает, хотя они по-прежнему можно установить на любое устройство iOS под управлением 12,2 или более поздней версии. The Microsoft Store and Google Play Store allow PWAs to be listed, the Apple Store currently does not, though they can still be installed on any iOS device running 12.2 or later.
- Чтобы узнать больше, ознакомьтесь с этим введением в пвас на MDN. To learn more, check out this introduction to PWAs on MDN.
Разработка игр Game development
Разработка игр для Android часто является уникальной от разработки стандартного приложения Android, так как игры обычно используют специальную логику отрисовки, часто написанную на OpenGL или вулкан. Game development for Android is often unique from developing a standard Android app since games typically use custom rendering logic, often written in OpenGL or Vulkan. По этой причине, и из-за наличия многих библиотек C, поддерживающих разработку игр, разработчики часто используют C/C++ с Visual Studioвместе с пакетом Android Native Development Kit (NDK)для создания игр для Android. For this reason, and because of the many C libraries available that support game development, it’s common for developers to use C/C++ with Visual Studio, along with the Android Native Development Kit (NDK), to create games for Android. Приступая к работе с C/C++ для разработки игр. Get started with C/C++ for game development.
Get started developing for Android using Xamarin.Android
This guide will help you to get started using Xamarin.Android on Windows to create a cross-platform app that will work on Android devices.
In this article, you will create a simple Android app using Xamarin.Android and Visual Studio 2019.
Requirements
To use this tutorial, you’ll need the following:
- Windows 10
- Visual Studio 2019: Community, Professional, or Enterprise (see note)
- The «Mobile development with .NET» workload for Visual Studio 2019
This guide will work with Visual Studio 2017 or 2019. If you are using Visual Studio 2017, some instructions may be incorrect due to UI differences between the two versions of Visual Studio.
You will also to have an Android phone or configured emulator in which to run your app. See Configuring an Android emulator.
Create a new Xamarin.Android project
Start Visual Studio. Select File > New > Project to create a new project.
In the new project dialog, select the Android App (Xamarin) template and click Next.
Name the project TimeChangerAndroid and click Create.
In the New Cross Platform App dialog, select Blank App. In the Minimum Android Version, select Android 5.0 (Lollipop). Click OK.
Xamarin will create a new solution with a single project named TimeChangerAndroid.
Create a UI with XAML
In the Resources\layout directory of your project, open activity_main.xml. The XML in this file defines the first screen a user will see when opening TimeChanger.
TimeChanger’s UI is simple. It displays the current time and has buttons to adjust the time in increments of one hour. It uses a vertical LinearLayout to align the time above the buttons and a horizontal LinearLayout to arrange the buttons side-by-side. The content is centered in the screen by setting android:gravity attribute to center in the vertical LinearLayout .
Replace the contents of activity_main.xml with the following code.
At this point you can run TimeChangerAndroid and see the UI you’ve created. In the next section, you will add functionality to your UI displaying the current time and enabling the buttons to perform an action.
Add logic code with C#
Open MainActivity.cs. This file contains the code-behind logic that will add functionality to the UI.
Set the current time
First, get a reference to the TextView that will display the time. Use FindViewById to search all UI elements for the one with the correct android:id (which was set to «@+id/timeDisplay» in the xml from the previous step). This is the TextView that will display the current time.
UI controls must be updated on the UI thread. Changes made from another thread may not properly update the control as it displays on the screen. Because there is no guarantee this code will always be running on the UI thread, use the RunOnUiThread method to make sure any updates display correctly. Here is the complete UpdateTimeLabel method.
Update the current time once every second
At this point, the current time will be accurate for, at most, one second after TimeChangerAndroid is launched. The label must be periodically updated to keep the time accurate. A Timer object will periodically call a callback method that updates the label with the current time.
Add HourOffset
The up and down buttons adjust the time in increments of one hour. Add an HourOffset property to track the current adjustment.
Now update the UpdateTimeLabel method to be aware of the HourOffset property.
Create the button Click event handlers
All the up and down buttons need to do is increment or decrement the HourOffset property and call UpdateTimeLabel.
Wire up the up and down buttons to their corresponding event handlers
To associate the buttons with their corresponding event handlers, first use FindViewById to find the buttons by their ids. Once you have a reference to the button object, you can add an event handler to its Click event.
Completed MainActivity.cs file
When you’re finished, MainActivity.cs should look like this:
Run your app
To run the app, press F5 or click Debug > Start Debugging. Depending on how your debugger is configured, your app will launch on a device or in an emulator.