Print kotlin android studio

Создаём своё первое приложение для Kotlin Multiplatform

Авторизуйтесь

Создаём своё первое приложение для Kotlin Multiplatform

ведущий мобильный разработчик компании Usetech

В настоящее время мы переживаем бум появления новых технологий и подходов к написанию мобильных приложений. Одной из них является развивающийся SDK от компании JetBrains для мультиплатформенной разработки Kotlin Multiplatfrom (KMP) .

Основная идея KMP, как и других кросс-платформенных SDK — оптимизация разработки путем написания кода один раз и последующего его использования на разных платформах.

Согласно концепции JetBrains, Kotlin Multiplatform не является фреймворком. Это именно SDK, который позволяет создавать модули с общим кодом, подключаемые к нативным приложениям.

Написанный на Kotlin модуль компилируется в JVM байткод для Android и LLVM байткод для iOS.

Sportmaster Lab , Москва, Санкт-Петербург, Новосибирск, можно удалённо , По итогам собеседования

Этот модуль (Shared, Common) содержит переиспользуемую бизнес-логику. Платформенные модули iOS/Android, к которым подключен Shared/Common, либо используют написанную логику напрямую, либо имплементируют свою реализацию в зависимости от особенностей платформы.

Общая бизнес-логика может включать в себя:

  • сервисы для работы с сетью;
  • сервисы для работы с БД;
  • модели данных.

Также в нее могут входить архитектурные компоненты приложения, напрямую не включающие UI, но с ним взаимодействующие:

Концепцию Kotlin Multiplatform можно сравнить с реализацией Xamarin Native. Однако, в KMP нет модулей или функционала, реализующих UI. Эта логическая нагрузка ложится на подключенные нативные проекты.

Рассмотрим подход на практике и попробуем написать наше первое приложение Kotlin Multiplatform.

Для начала нам потребуется установить и настроить инструменты:

  1. Android Sdk
  2. Xcode с последним iOS SDK.
  3. Intelij IDEA CE или Android Studio. Обе IDE позволяют создавать и настраивать проекты для Kotlin Multiplatform. Но если в Intelij IDEA проект создается автоматически, то в Android Studio большую часть настроек надо сделать вручную. Если вам привычнее работать именно с Android Studio, то подробное руководство по созданию проекта можно посмотреть в документации на Kotlinlang.org

Мы рассмотрим создание проекта с помощью Intelij IDEA.

Выбираем меню File → New → Create Project:

В появившемся окне выбираем тип проекта Kotlin → Mobile Android/iOS|Gradle

Далее стандартно задаем путь к JDK, имя и расположение проекта

После нажатия кнопки Finish проект сгенерируется и будет почти готов к работе.

Рассмотрим, что у нас получилось:

Мультиплатформенные проекты Kotlin обычно делятся на несколько модулей:

  • модуль переиспользуемой бизнес-логики (Shared, commonMain и т.п);
  • модуль для IOS приложения (iOSMain, iOSTest);
  • модуль для Android приложения (androidMain, androidTest).

В них располагается наша бизнес-логика. Сам код базового примера мы разберем немного позже.

Код нативного Android приложения располагается в каталоге main, как если бы мы создавали проект по шаблону обычного Android.

iOS приложение создается автоматически и располагается в каталоге iOSApp:

Перед тем, как мы проверим работоспособность базового решения, необходимо сделать следующие финальные настройки:

В local.properties зададим путь к SDK Android:

Создадим конфигурацию для работы Android приложения:

Теперь вызовем команду gradle wrapper для сборки нашего модуля общей логики:

После сборки модуль для бизнес-логики для Android приложения доступен в app/build/libs:

Путь к библиотеке прописывается стандартно, в блоке dependencies файла build.gradle:

Теперь наш проект сконфигурирован для запуска Android приложения:

Осталось сделать настройки для запуска приложения iOS.

В файле build.gradle(:app) необходимо изменить настройку архитектура проекта, чтобы наше приложение поддерживало как реальные устройства, так и эмуляторы.

После выполнения сборки создастся фреймворк в app/build/bin/ios:

Intelij IDEA автоматически создает в gradle файле код для генерации, подключения и встраивания фреймворка в IOS проект:

При ручной настройке проекта (например, через Android Studio) этот код потребуется указать самостоятельно.

После синхронизации gradle iOS проект готов к запуску и проверке с помощью XCode.

Проверяем, что у нас получилось. Открываем проект iOS через iosApp.xcodeproj:

Проект имеет стандартную структуру, за исключением раздела app, где мы получаем доступ к коду наших модулей на Kotlin.

Фреймворк действительно подключен автоматически во всех соответствующих разделах проекта:

Читайте также:  Добавление шрифта android studio

Запускаем проект на эмуляторе:

Теперь разберем код самого приложения на базовом примере.

Используемую в проекте бизнес-логику можно разделить на:

  • переиспользуемую (общую);
  • платформенную реализацию.

Переиспользуемая логика располагается в проекте commonMain в каталоге kotlin и разделяется на package. Декларации функций, классов и объектов, обязательных к переопределению, помечаются модификатором expect :

Реализация expect -функционала задается в платформенных модулях и помечается модификатором actual :

Вызов логики производится в нативном проекте:

Все очень просто.

Теперь попробуем по тем же принципам сделать что-то посложнее и поинтереснее. Например, небольшое приложение для получения и отображение списка новостей для iOS и Android.

Приложение будет иметь следующую структуру:

В общей части (Common) расположим бизнес-логику:

  • сетевой сервис;
  • сервис для запросов новостей.

В модулях iOS/Android приложений оставим только UI компоненты для отображения списка и адаптеры. iOS часть будет написана на Swift, Android – на Kotlin. Здесь в плане работы не будет ничего нового.

Организуем архитектуру приложений по простому паттерну MVP. Презентер, обращающийся к бизнес-логике, также вынесем в Common часть. Также поступим и с протоколом для связи между презентером и экранами UI:

Начнем с бизнес-логики. Т.к весь функционал будет в модуле common, то мы будем использовать в качестве библиотек решения для Kotlin Multiplatform:

1. Ktor – библиотека для работы с сетью и сериализации.

В build.gradle (:app) пропишем следующие зависимости:

Также добавим поддержку плагина сериализации:

2. Kotlin Coroutines – для организации многопоточной работы.

При добавлении зависимости в iOS проект обратите внимание, что версия библиотеки должна быть обязательно native-mt и совместима с версией плагина Kotlin multiplatform.

При организации многопоточности с помощью Coroutines необходимо передавать контекст потока ( CoroutineContext ), в котором логика будет исполняться. Это платформозависимая логика, поэтому используем кастомизацию с помощью expect / actual .

В commonMain создадим Dispatchers.kt, где объявим переменные:

Реализация в androidMain создается легко. Для доступа к соответствующим потокам используем CoroutineDispatchers Main (UI поток) и Default (стандартный для Coroutine ):

С iOS труднее. Та версия Kotlin Native LLVM компилятора, которая используется в Kotlin Multiplatform, не поддерживает background очереди. Это давно известная проблема, которая к сожалению, еще не исправлена

Поэтому попробуем обходной маневр как временное решение проблемы.

Мы создаем свой CoroutineDispatcher , где прописываем выполнение логики в асинхронной очереди dispatch_async .

Также нам понадобится свой scope для работы сетевого клиента:

iOS

Android

Применим это при реализации сетевого клиента на Ktor:

Парсинг реализуем с помощью сериализатора типа KSerializer . В нашем случае это NewsList.serializer() . Пропишем реализацию в сервисе новостей:

Вызывать бизнес-логику будем в презентере. Для полноценной работы с coroutines нам надо будет создать scope:

и добавить его в презентер. Вынесем в базовый класс:

Теперь создадим презентер NewsListPresenter для нашего модуля. В инициализатор передадим defaultDispatcher :

Обратите внимание! Из-за особенностей текущей работы Kotlin Native с многопоточностью в IOS работа с синглтонами может привести к крашу. Поэтому для корректной работы надо добавить аннотацию @ThreadLocal для используемого объекта:

Осталось подключить логику к нативным IOS и Android модулям и обработать ответ от Presenter:

Запускаем сборку common модуля gradle wrapper, чтобы сборки обновились. Проверяем работу приложений:

Готово. Вы великолепны.

Оба наши приложения работают и работают одинаково.

Информационные материалы, которые использовались:

Источник

Working with Kotlin in Android Studio

With the release of M6, we announced support for Android Studio. Let’s take a deeper look at how to get up and running with Android Studio and Kotlin.

Installing the Kotlin Plugin

Much like with IntelliJ IDEA, to install the Kotlin plugin you need to click on Preferences (Settings) and select the Plugins entry. Easiest way is to just start typing plugin as soon as the dialog pops up.

Although we can download the plugin and install from disk, the easiest way is to click on the Install JetBrains plugin… and select Kotlin from the list. Right-click and choose Download and Install

Follow the instructions to restart the IDE.

Setting up the Project

Android Studio uses Gradle as its build system and part of the effort involved in supporting this environment was adding Gradle support for Kotlin.

Adding Source folder for Kotlin

A typical Android Project has the following layout

where the source code for the project is located under the folder main/java. Since we want to use Kotlin (we can mix and match both Java and Kotlin the same project), we need to create a new folder under main, named kotlin. In the Gradle script we’ll later define this folder as a source root.

Configuring Gradle

We need to set up some dependencies and source folders in the Gradle configuration. Open the build.gradle file and copy the following

Читайте также:  Клавиатура для san andreas android

Update: Replace “0.6.+” with the version of Kotlin plugin you have installed.

The parts relative to Kotlin are highlighted in bold:

  • Select the Kotlin plugin for Gradle and the version we’re using. The M6 release corresponds to 0.6.69.
  • Apply the kotlin-android plugin
  • Import the Kotlin’s standard library
  • Specifiy where the source code files are located

Specifying the sourceSet will automatically mark the folder we created previously (main/kotlin) as a Source Root in Android Studio.

Once we have the Gradle file updated, we should be able to successfully build Android project written in Kotlin.

Hello World with Kotlin

The easiest way to try out Kotlin with Android is to create a default Android project and convert the code to Kotlin, which the IDE can do for us.

    Create a new Android Project (we’ll omit the steps for creating new Android projects).

Add the kotlin folder and update the Gradle file as indicated above.

Select the MainActivity file and from the Code menu select Convert Java File to Kotlin File. We can omit creating a backup.

As soon as we do this, Android Studio automatically detects that this is a Kotlin file and asks us if we want to move it to the kotlin folder. We do so.

Once the project is built we should now be able to run it.

Most likely going to be asked questions

Can I combine Java and Kotlin in the same Android Project?
Absolutely. In fact, check out our GitHub repository for some samples.

Can I use nightly builds of Kotlin?
Yes you can. Just update the Gradle project to point to the snapshots and add the corresponding repository.

Are there any more goodies you forgot to mention?
Now that you ask, we also have some External Annotations for the Android JDK. Android Studio will automatically prompt you to add these to the project.

Although we’ve been using Android Studio in this post, please note that doing Android development with Kotlin is also possible with IntelliJ IDEA and has been available for quite some time. As always, we appreciate any and all feedback.

19 Responses to Working with Kotlin in Android Studio

Martin Krischik says:

What is the overhead? Compile Time, APK size, with or without proguard.

Note that with Scala the cumbersome part is not the language itself but scala-library.jar. Which is why I ask for proguard.

Hadi Hariri says:

We’ve not run specific tests yet for Android, but, unlike Scala, our runtime is small and the code performs as fast as Java on most benchmarks.

fanchao says:

I had an investigation on the potential performance impacts on Android today. What I did is decompiling the .class file generated by Kotlin and some interesting facts I concerned most compared to other framework/language:

Inline functions (lambda expressions) are inlining wherever possible.
For example, no penalty for using forEach expression, it’s just like hand writing a Java loop, no extra inner classes, no extra object allocated. But what I know for Java 8 or similar things that support streaming API will create an anonymous inner class instance and invoke the method each time for a value, which seems to be a unnecessary performance hole on Android.
Of course, if you assign a lambda as Java interface, a new inner class will be generated, it’s not winning over Java but at least it’s not losing (Java will generate one, too).

Auto boxing/unboxing taken care of.
Primitive types will be used wherever possible. Arrays and it’s family seem to be generic (which produces boxing/unboxing) but you always have the choice to use IntArray or sort of things, where it will try to use primitive arrays and values directly.

Optional getter/setters.
Unlike some other JVM languages that generate getter/setter for property, Kotlin can make use of field access if a backing field is declared by ‘private’, no getter/setters will be generated. Android performance guide outlines getter/setters issues, basically the idea is redundant methods or calls should be avoided.

Code generation for extension is clean and direct
For extensions, just an extra static method that takes the injected class’ instance as the first argument will be generated for you, it’s like just writing a Utility method.

As a neat freak of generated codes, anything that is more than plain Java looks scare to me. A good compiler should not compromise performance and expressiveness . I think from what I observed, one can expect a same performance level with Java, even you use the Kotlin specified idioms (lambda, , not a Kotlin version of Java code.

Читайте также:  Poweramp для андроид что это

evilbloodydemon says:

Why app and kotlin library sources is placed to resulting .apk?

Stuart Rackham says:

I also had to set the kotlin folder as belonging to project sources otherwise you’ll get a “default activity not found” error message (I’m using Studio 0.2.8 with Kotlin plugin 0.6.350 on Linux), the plugin did not do this automatically as the article suggests. Right-click on the kotlin directory (in the Project Tool window) and select the ‘Mark Directory As->Sources Root’ menu command (you can also manage this from the ‘Project Structure’ dialog.

Stuart Rackham says:

Mark the kotlin folder as a source root at step 2 (in ‘Hello World with Kotlin’ above) to ensure you get automatically prompted to move the converted Kotlin file to the kotlin folder.

Marcin Koziński says:

Wouldn’t it be possible for kotlin-android plugin to add src/main/kotlin to sourceSets?

I was thinking of writing a gradle code snippet to add kotlin source set for each java source set. It seems to be possible. And the best place for such code would inside the first party plugin 🙂

Natalia Ukhorskaya says:

kotlin-android plugin already add src/main/kotlin to sourceSets. The only reason why you need to do this is to make IDE know that src/main/kotlin is a source directory. And we are going to fix it.

Lemuel Adane says:

I just update my Android Studio, and for the first time install the latest Kotlin plugin, and followed what the article said on my Mac. After several wasted hours of figuring out, I still had 3 errors, Its saying that ‘it was compiled with incompatible version of Koltlin.’ and ABI was this version but expected was this version. Wow! I don’t even have an older version of Kotlin. And what’s ABI? Are they talking to themselves? Im sorry but I got disapointed.

Andrey Breslav says:

I am sorry you got disappointed. What class was the error reported on?

Igor says:

I’v hat this error when syncing hradle project:

What it is and what I need to do?

Natalia Ukhorskaya says:

You are using SNAPSHOT version of kotlin. Have you added http://oss.sonatype.org/content/repositories/snapshots url to your repositories list? If yes, could you report us an issue with your build.gradle file attached? Thanks!

Igor says:

Thank you so much, It works but I’v take new error:

Natalia Ukhorskaya says:

Could you provide you build.gradle file please?

Igor says:

buildscript <
ext.kotlin_version = ‘0.11.91’
repositories <
mavenCentral()
maven <
url ‘http://oss.sonatype.org/content/repositories/snapshots’
>
>
dependencies <
classpath ‘org.jetbrains.kotlin:kotlin-gradle-plugin:0.6.+’
classpath ‘com.android.tools.build:gradle:1.0.+’
classpath “org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version”
>
>
apply plugin: ‘kotlin-android’
dependencies <
compile ‘org.jetbrains.kotlin:kotlin-stdlib:0.6.+’
compile “org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version”
>

android <
compileSdkVersion 17
buildToolsVersion “17.0.0”

Igor says:

Thank you, It worked but now I’v take new error:

Natalia Ukhorskaya says:

Looks like you forgot to apply android plugin.
apply plugin: ‘com.android.application’

Andrew says:

Well, it took me for good 1 hours to fix this error, i thought it was some bug. I really hope you guys can create forum for this. Thanks

Andrey Breslav says:

Discover more

Gradle Kotlin DSL 1.0

This is a guest blog post from Paul Merlin software engineer for Gradle The recently released Gradle 5.0 includes the Gradle Kotlin DSL v1.0 which is now ready for widespread use. We want you to enjoy a build authoring experience with the benefits provided by Kotlin’s static type system in Intellij IDEA and Android Studio: auto-completion, smart content assist, quick access to documentation,

Kotlin 1.3 Released with Coroutines, Kotlin/Native Beta, and more

You can read this blog post in other languages: Today we are releasing Kotlin 1.3 together with a set of accompanying libraries, build tools, and learning materials! We develop Kotlin to be a good tool for all application developers, at all scales and on all platforms. In Kotlin 1.3 coroutines graduated to stable, making non-blocking code easy to read and write. Scalability ha

KotlinConf 2018 Announcements

In today’s keynote at KotlinConf 2018 we made a series of announcements around releases, resources, and other things we’ve made available. For your convenience below is a brief summary of the announcements with the corresponding links for more information. Kotlin 1.3 hits RC Version 1.3 hits RC and brings a ton of new features and functionality. Coroutines Kotlin Coroutines are no longer ex

Kotlin/Native 0.8.2 Released

We are happy to announce the 0.8.2 release of Kotlin/Native. In addition to the bug fixes and improvements, we have introduced support for Kotlin/Native Gradle projects directly in CLion! (more…)

Источник

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