St. Pölten University of Applied SciencesSt. Pölten University of Applied Sciences Platzhalter für möglichen Bildeinsatz Android Development with Kotlin, Part 1 Introduction Andreas Jakl Digital Healthcare FH St. Pölten Platzhalter für möglichen Bildeinsatz Version 1.3
Andreas Jakl ▪ Focus areas ▪ AR / VR, mobile apps, sensors, interaction technology, software architecture, open source developer (NFC, Bluetooth Beacons) ▪ Microsoft MVP (Most Valuable Professional) ▪ mobility.builders community: Mobile Developer After-Work Events ▪ Previous Experience ▪ Tieto, Start-up (Mopius), Nokia (Finland), Siemens Mobile (Munich), FH Hagenberg (Mobile Computing) Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten https://www.andreasjakl.com/ @andijakl andreas.jakl@fhstp.ac.at 2
Contents ▪ Hybrid & Native Apps ▪ Native Android Development ▪ Android & SDK Versions ▪ Hello World ▪ Emulators, Devices & ADB ▪ Android Emulators & Build Process ▪ Kotlin Android Extensions ▪ App Lifecycle ▪ Saving App State ▪ Debugging ▪ Code Style + Documentation ▪ Activities & Intents ▪ Implicit Intents Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 3
Android Studio ▪ If you have not already: ▪ Install Android Studio now! ▪ It’ll take some time … ▪ https://developer.android.com/studio/index.html ▪ Already includes JDK ▪ Troubleshooting ▪ https://docs.google.com/document/d/1w1Xn_hnSAODAAtdRDp7haYPBtEwX _l7Htpf8Wpgbu6w/pub?embedded=true Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 4
NATIVE APPS Web vs Hybrid vs Native Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 5
Web vs Hybrid vs Native Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 6 Web Apps Multi-platform Web UI / UX Run in browser (can be offline) Slower performance Less system integration Native Apps Single platform Native UI / UX Run directly on OS Fast performance, best system integration. More expensive. Hybrid Apps Multi-platform Hybrid UI / UX Parts in HTML, parts native
Web vs Hybrid vs Native Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 7 Web Apps Native Apps Hybrid Apps Cost User Experience
Additional Materials ▪ Free Android Courses by Google & Udacity ▪ Java Programming Basics: https://www.udacity.com/course/java-programming- basics--ud282# ▪ Android Basics: User Interface: https://www.udacity.com/course/android-basics- user-interface--ud834# ▪ Developing Android Apps: https://www.udacity.com/course/new-android- fundamentals--ud851# ▪ Kotlin for Android Developers: https://www.udacity.com/course/kotlin-for- android-developers--ud888 ▪ Quick Kotlin overview for Java Android devs: https://developer.android.com/kotlin/index.html Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 8
NATIVE ANDROID DEVELOPMENT Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 9
Android Development Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 10 Java Kotlin C++ Frame- works (Unity, Xamarin, Qt, …) Web Android Studio Visual Studio Specific tools Visual Studio Code, WebStorm, etc. IntelliJ IDEA
Android Web / Hybrid Apps Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 11 Image source: Google, https://developer.android.com/guide/webapps/index.html
Android Web / Hybrid Apps Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 12 Cordova Native functionality (Java, C++, …) Image source: Google, https://developer.android.com/guide/webapps/index.html
Cross-Platform Engines ▪ Usually specialized for app types ▪ Unity ▪ Games, 2D / 3D graphical apps ▪ Cross-platform ▪ Graphical editor, code with C# ▪ Xamarin ▪ Apps ▪ iOS, Android, Windows ▪ Cross-platform C# APIs, with Xamarin.Forms also UI. Specific native code possible ▪ Qt ▪ Apps and embedded ▪ Cross-platform ▪ UI with JavaScript / QML, native code with C++ Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 13 Image sources: Unity Logo, by Unity Technologies Public domain, https://en.wikipedia.org/wiki/File:Unity_Technologies_Logo.svg Xamarin Logo, by Xamarin Inc. / Microsoft Public domain, https://en.wikipedia.org/wiki/File:Xamarin-logo.svg Qt Logo, by The Qt Company Public domain, https://en.wikipedia.org/wiki/File:Qt_logo_2016.svg
Android C++ ▪ Native Development Kit (NDK) ▪ C and C++ code ▪ Why? ▪ Reuse existing C++ code & libraries ▪ Extra performance, less latency ▪ Combine: communication Java <> C++ ▪ Java Native Interface (JNI) ▪ https://developer.android.com/ndk/guides/index.html Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 14 Image credits: logo for C++ created by Jeremy Kratz Licensed for use of any purpose by the Standard C++ Foundatino https://en.wikipedia.org/wiki/File:ISO_C%2B%2B_Logo.svg
Java (for Android) ▪ Java: Source code > Byte code > executed by Java Virtual Machine (JVM) ▪ License ▪ OpenJDK ▪ GPL v2 license ▪ De-facto reference implementation of Java by Oracle / Sun, basis for Oracle JDK ▪ Used in Android since Nougat ▪ Android uses recent Java. By default part of Android Studio: C:android-studiojre ▪ Trial Google vs. Oracle ▪ Use of Java = fair use? Switch to OpenJDK as a result (before: Apache Harmony, re-implementation of copyrighted Java APIs) ▪ http://www.zdnet.com/article/oracle-vs-google-just-as-you-thought-java-android-row-was-over-it-all-kicks-off-again/ Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 15 Image credits: Duke, the mascot used by Java. Copyright Sun Microsystems Inc., BSD license https://en.wikipedia.org/wiki/File:Duke_(Java_mascot)_waving.svg
Kotlin ▪ Programming language, “improved Java” ▪ Runs on Java JVM ▪ Interoperable with Java code + libraries ▪ Possible to mix Kotlin + Java in same project ▪ But can also be compiled to JavaScript + native (C) ▪ Created by JetBrains ▪ Open source language (Apache 2 license): https://github.com/JetBrains/kotlin ▪ https://kotlinlang.org/ Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 16 Image credits: Kotlin Logo, by JetBrains. https://commons.wikimedia.org/wiki/File:Kotlin-logo.svg
Kotlin & Android ▪ Android ▪ Integrated in Android Studio 3+ ▪ Fully supported programming language for Android ▪ Kotlin Android Extensions: https://kotlinlang.org/docs/tutorials/android- plugin.html Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 17 Image credits: Kotlin Logo, by JetBrains. https://commons.wikimedia.org/wiki/File:Kotlin-logo.svg
Android Studio ▪ Official IDE ▪ Customized from JetBrain’s IntelliJ IDEA ▪ Windows, Mac OS, Linux Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 18
ANDROID PLATFORM Versions & Structure Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 19
Android Versions ▪ Version Distribution: https://developer.android.com/about/dashboards/index.html#Platform ▪ More features in newer versions ▪ But: partly backported ▪ Reduces fragmentation ▪ Support Library (AppCompat) ▪ Google Play Services Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 20
Android Versions Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 21
SDK Versions ▪ MinSDK ▪ Lowest OS your app can run on ▪ Restricts features and APIs you can use ▪ TargetSDK ▪ Version you tested the app on ▪ Generally forward compatible: if behavior changes in new version, new Android will still “simulate” behavior of old TargetSDK version (e.g., Runtime permissions with Android M) ▪ https://developer.android.com/reference/android/os/Build.VERSION_CODES.html ▪ Use the latest version when starting a new project ▪ CompileSDK ▪ Not part of the manifest, only relevant for developer ▪ Generally use latest version -> allows using latest APIs if needed Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 22
HELLO WORLD Your First Android App Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 23
Create New Project Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 24
Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 25
Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 26
Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 27
Project Structure Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 28 See: https://developer.android.com/studio/build/index.html
Views ▪ Android user interface (UI) composed of views ▪ TextView ▪ ImageView ▪ Button ▪ Etc. ▪ All managed by a layout ▪ Positioning of views on the screen Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 29
Design Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 30 TextView ImageView Button Toggle: Design / Text (XML)
XML Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 31 <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.andreasjakl.helloworld.MainActivity" tools:layout_editor_absoluteY="81dp"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginEnd="8dp" android:layout_marginStart="8dp" android:layout_marginTop="8dp" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="8dp" android:layout_marginStart="8dp" android:layout_marginTop="8dp" app:layout_constraintEnd_toEndOf="@+id/textView" app:layout_constraintStart_toStartOf="@+id/textView" app:layout_constraintTop_toBottomOf="@+id/textView" app:srcCompat="@android:drawable/btn_star_big_on" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="8dp" android:layout_marginTop="8dp" android:text="Button" app:layout_constraintEnd_toEndOf="@+id/imageView" app:layout_constraintStart_toStartOf="@+id/imageView" app:layout_constraintTop_toBottomOf="@+id/imageView" /> </android.support.constraint.ConstraintLayout> TextView ImageView Button
Activity & Views ▪ Activity’s onCreate(): ▪ R class ▪ Dynamically identify contents in res folder ▪ setContentView() ▪ Inflates the layout XML file Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 32 setContentView(R.layout.activity_main)
SDK Manager ▪ Android Studio > File > Settings > Appearance & Behavior > System Settings > Android SDK, or: ▪ Install all “SDK platforms” you need ▪ SDK Tools: ensure you have at least ▪ Android SDK Build-Tools ▪ Android Emulator ▪ Android SDK Platform-Tools ▪ Android SDK Tools ▪ Google Play Services ▪ Google USB Driver (on Windows) ▪ Intel x86 Emulator Accelerator (HAXM installer) ▪ Support Repository Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 33
Running the App ▪ Press “Play” arrow ▪ Select deployment target ▪ Connected phones or emulator ▪ “Create New Virtual Device” Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 34
Android Debug Bridge (ADB) ▪ ADB manages connections to phones & emulators ▪ Debugging ▪ Installing apps ▪ Windows: add to path (next slide) ▪ “adb.exe” usually in C:Androidplatform-tools ▪ Powershell: “adb devices –l” to show all connected devices Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 35 Emulator + phone connected
Windows: Add ADB to Environment Variables Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 36
Android Emulators ▪ Freely choose device configuration ▪ Screen size, OS, memory, etc. ▪ Hardware Acceleration ▪ Intel HAXM, but only for Intel. Conflict with Hyper-V https://developer.android.com/studio/run/emulator- acceleration.html#accel-vm ▪ Alternative: Microsoft Android emulator https://www.visualstudio.com/vs/msft-android- emulator/ Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 37
Deploy to Android Phone ▪ Enable Developer Options ▪ Settings > (System) > About Phone > tap 7x on “Build Number” ▪ Enable “USB debugging” ▪ Connect phone via USB ▪ Ensure debugging is active ▪ Device shows up in “adb devices” Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 38
Gradle ▪ Build automation system ▪ Used by Android Studio ▪ Can be run manually from command line ▪ Converts code to installable package ▪ Configuration: build.gradle ▪ You define: dependencies, versions, etc. ▪ https://developer.android.com/studio/build /index.html Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 39 Image credits: Gradle Logo copyright Gradle, Inc. Build process copyright Google, https://developer.android.com/studio/build/index.html
Android Build Process ▪ Gradle settings ▪ settings.gradle (project root directory) ▪ Which modules to include. Usually only one line Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 40 include ':app'
Android Build Process ▪ Top-level build file ▪ build.gradle (project root directory) ▪ Applies to all modules ▪ buildscript: Gradle repositories & dependencies Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 41 buildscript { ext.kotlin_version = '1.2.10' repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.0.1' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } }
Android Build Process ▪ Module-level build file ▪ project/module/settings.gradle ▪ Only apply to this module ▪ Custom packaging options: Android options, module-level dependencies, product flavors (free / paid, …) Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 42
ADDING INTERACTIVITY Hello World 2.0 Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 43
Adapt Size & Color ▪ Check Google Material Design guidelines ▪ https://material.io/guidelines/ ▪ Size ▪ View: use “dp” for device-independent pixels. Same physical view size no matter the pixel density of the screen. ▪ Text: use “sp” for scale-independent pixels. Also considers user’s settings. ▪ Color ▪ Use color tool: https://material.io/color/ Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 44
Improving XML Definitions ▪ Collect text in “res/values/strings.xml” ▪ Reference from TextView & Button ▪ Easier to localize and change ▪ Give useful IDs to elements ▪ Start with “@+id/” ▪ + indicates it’s a new resource ID ▪ Rename e.g., “@+id/textView” -> “@+id/tv_hello” Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 45 <TextView android:id="@+id/tv_hello"
Interactivity with Kotlin for Android ▪ MainActivity.kt > Change TextView text when Button is clicked ▪ Create member variables to access UI elements ▪ In onCreate(), find views: ▪ Set click listener and change TextView text Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 46 private lateinit var mChangeTextButton : Button private lateinit var mHelloTextView : TextView mHelloTextView = findViewById(R.id.tv_hello) mChangeTextButton = findViewById(R.id.bt_change) mChangeTextButton.setOnClickListener { mHelloTextView.text = "Welcome!" }
Interactivity with Kotlin for Android ▪ Define “Welcome!” text in strings.xml and load from Kotlin code: Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 47 mChangeTextButton.setOnClickListener { mHelloTextView.text = getText(R.string.welcome_text) }
Kotlin Android Extensions ▪ findViewById() – easy to make errors, lots of code to write ▪ Kotlin Android Extensions make accessing views easier ▪ build.gradle: ensure the plugin is loaded ▪ MainActivity.kt: Add import with name of xml file ▪ Directly access View elements: Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 48 apply plugin: 'kotlin-android-extensions' import kotlinx.android.synthetic.main.activity_main.* bt_change.setOnClickListener { tv_hello.text = getText(R.string.welcome_text) }
Rotating the Screen? Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 49 ? Text switches back to original
ANATOMY OF ANDROID APPS Lifecycle Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 50
Android Application Components 1. Activity ▪ “Single focused thing the user can do” ▪ Creates view (to draw, based on XML layout file) and receives events (touch) 2. Service 3. Content Provider 4. Broadcast Receiver Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 51
Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 52 Source:https://developer.android.com/guide/components/activities/activity-lifecycle.html
Task: Check Lifecycle ▪ Override all lifecycle methods of the activity ▪ Log status message (Log.d) ▪ Create TAG to recognize your log messages ▪ Example ▪ Check output in logcat Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 53 private val TAG = MainActivity::class.java.simpleName override fun onStart() { super.onStart() Log.d(TAG, "onStart") }
Task: Check Lifecycle ▪ Rotate screen! Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 54 Rotation
Saving the State ▪ Bundle for storing small amount of data ▪ Only used when resuming apps, not for re-starts ▪ Built-in for activity: save key-value pairs ▪ Key definition ▪ Save state ▪ Restore in onCreate() + default if not set Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 55 private val KEY_TEXT = "uiText" override fun onSaveInstanceState(outState: Bundle?) { outState?.putString(KEY_TEXT, tv_hello.text.toString()) super.onSaveInstanceState(outState) } if (savedInstanceState != null) { tv_hello.text = savedInstanceState.getString(KEY_TEXT, getText(R.string.hello_text).toString()) }
DEBUGGING Finding and Fixing Errors Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 56
Trigger Error ▪ Create unhandled exception in onCreate() ▪ App crashes on startup ▪ Check logcat (set log level to “Error”) Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 57 throw Exception("Error!")
Debugging Android Apps ▪ Set Breakpoints & use debugging tools ▪ Run app with “Debug” mode ▪ Break on any exception ▪ Run > View Breakpoints … > Activate “Any Exception” ▪ may include lots of others too Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 58
Android Lint ▪ Static Code Analysis: Analyze > Inspect Code… Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 59
Issues with R Class / Unknown Error Source ▪ Recheck XML in your resource files (layouts, …) ▪ Android Studio might not highlight everything, e.g. some typos ▪ Clean project to rebuild from scratch ▪ Build > Clean Project ▪ Re-Sync project with Gradle ▪ Tools > Android > Sync Project with Gradle Files ▪ Run Android Lint Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 60
Exercise: Guess-a-Number ▪ Create UI with at least 3 views: ▪ EditText (“Plain Text” or “Number”), Button, TextView ▪ Put all user-visible text in strings.xml resource ▪ Phone thinks of random number [1..100] ▪ User enters number and taps button ▪ Phone tells if number was too low, too high or correct ▪ Bonus: also add number of tries to message ▪ Bonus: reset game and create new random number ▪ Bonus: handle screen rotation Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 61
CODE STYLE Documentation & Naming Conventions Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 62
Naming Conventions ▪ Android naming conventions & more: ▪ https://android.github.io/kotlin-guides/style.html ▪ Generic Kotlin ▪ https://kotlinlang.org/docs/reference/coding-conventions.html Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 63
Naming Conventions ▪ Package names ▪ Always lowercase ▪ Classes / Objects ▪ Start with upper case letter, camel humps Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 64 package com.andreasjakl.helloworld class MainActivity : AppCompatActivity() {
Naming Conventions ▪ Functions, properties, local variables ▪ Start with lower case letter, camel humps, no underscores ▪ Exception: constructors (-> same name as class, uppercase starting letter) ▪ Constants ▪ Uppercase, underscore-separated Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 65 var myCounter = 3 override fun onSaveInstanceState(outState: Bundle?) { private val KEY_TEXT = "uiText"
Documenting Code ▪ Code comments ▪ Important for classes, methods and properties (especially public) ▪ Java: JavaDoc ▪ Kotlin: KDoc – https://kotlinlang.org/docs/reference/kotlin-doc.html Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 66
KDoc Syntax ▪ Add comment directly above class / function ▪ Starts with /** , ends with */ ▪ Every documentation line has * at the beginning – not part of comment ▪ Block tags ▪ Parameters: @param <name> ▪ Returns: @return Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 67
Generate Documentation: Dokka ▪ Add dokka-android plugin to app build.gradle ▪ Add gradle task “dokka” to configure documentation ▪ See: https://github.com/Kotlin/dokka/blob/master/README.md Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 68 apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' apply plugin: 'org.jetbrains.dokka-android' dokka { outputFormat = 'html' outputDirectory = "$buildDir/javadoc" }
Generate Documentation: Dokka ▪ Configure docker version and dependency in module’s build.gradle ▪ Run gradle task “dokka” in terminal ▪ gradlew dokka Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 69 buildscript { ext.kotlin_version = '1.2.10' ext.dokka_version = '0.9.15' repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.0.1' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath "org.jetbrains.dokka:dokka-android-gradle-plugin:${dokka_version}" } }
Generate Documentation: Dokka ▪ Generated HTML documentation in app/build/javadoc directory: Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 70
ACTIVITIES Adding multiple pages to your app Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 71
Our Task: Passing Data Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 72
Navigation Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 73 Activity Activity not called directly
Indirect Triggering Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 74 Activity Activity Intents
Flexibility: Launch Various Tasks Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 75 Activity Activity Start new Intents Take picture Open browser
What is an Intent? Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 76 - Message object - Request action from other app component - Can include data (extras) Image source: Android Developer Guide https://developer.android.com/guide/components/intents-filters.html
Exercise: Create Main Activity ▪ Name: GreetingApp ▪ UI ▪ TextView, EditText, Button ▪ Use helpful ids ▪ Externalize text to strings.xml ▪ Ensure proper dynamic layout ▪ Use setOnClickListener() on button ▪ Display entered text with a toast ▪ Search for documentation! Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 77
Exercise: Create Greeting Activity Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 78
Exercise: UI for Greeting Activity ▪ UI ▪ 2x TextView with helpful IDs ▪ Check AndroidManifest.xml ▪ Shows second activity ▪ It’s not configured for MAIN / LAUNCHER Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 79
Context ▪ Global information about app environment ▪ Provided by Android system ▪ Access app-specific resources ▪ App-level operations (e.g., launching activities) Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 80
Create & Launch Intent Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 81 val welcomeIntent = Intent(this, GreetingActivity::class.java) startActivity(welcomeIntent) Context Activity to start Start!
Passing Data ▪ Intents support extended data ▪ Key / Value-based ▪ Default Intent.EXTRA_TEXT for passing basic String data Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 82 welcomeIntent.putExtra(Intent.EXTRA_TEXT, et_name.text.toString()) Text from EditText
Receiving Extra Data ▪ Activity has intent property ▪ Provides access to details about Intent Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 83 // Check if the calling intent actually provided EXTRA_TEXT data if (intent.hasExtra(Intent.EXTRA_TEXT)) { // Retrieve String contents from EXTRA_TEXT data var userName = intent.getStringExtra(Intent.EXTRA_TEXT) // Apply the String to the UI tv_name.text = userName }
Enable Back Navigation Arrow ▪ Specify parent activity in manifest ▪ Add meta-data if targeting Android 4.0 ▪ For newer versions, the parentActivityName is enough Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 84 <activity android:name=".GreetingActivity" android:parentActivityName=".MainActivity"> <meta-data android:name="android.support.PARENT_ACTIVITY" android:value=".MainActivity" /> </activity>
Implicit Intent ▪ Action to be done + (optional) data ▪ Take picture ▪ Call contact ▪ Show web page ▪ … ▪ Multiple apps can handle intent? ▪ Android lets user choose Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 85 Activity Start new Take picture Open browser
Open Web Site ▪ Common Intents ▪ https://developer.android.com/guide/components/ intents-common.html ▪ -> Web Browser ▪ Extend UI ▪ Second button ▪ Click listener Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 86
Resolving Intents Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 87 // Target address, converted from String to URI val webPage = Uri.parse("https://www.andreasjakl.com/") // Create an intent. ACTION_VIEW is generic to show data to the user // Apps can subscribe to handle specific URIs // See: https://developer.android.com/reference/android/content/Intent.html#ACTION_VIEW val webIntent = Intent(Intent.ACTION_VIEW, webPage) // Check if at least one app is installed to handle our intent if (webIntent.resolveActivity(packageManager) != null) { // If yes, start the activity! startActivity(webIntent) }
URI? Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 88 scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment] https://www.andreasjakl.com/ mailto:andreas.jakl@fhstp.ac.at?subject=Android geo:48.214643,15.6224716 spotify:album:3hrSH1h42tH4W1ods3Cm7o
Exercise ▪ Launch another common intent ▪ https://developer.android.com/guide/components/intents-common.html ▪ Examples ▪ Map ▪ Share ▪ Email ▪ Camera ▪ Note: some activities need extra permissions in your manifest! Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 89
THANK YOU! Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 90

Android Development with Kotlin, Part 1 - Introduction

  • 1.
    St. Pölten Universityof Applied SciencesSt. Pölten University of Applied Sciences Platzhalter für möglichen Bildeinsatz Android Development with Kotlin, Part 1 Introduction Andreas Jakl Digital Healthcare FH St. Pölten Platzhalter für möglichen Bildeinsatz Version 1.3
  • 2.
    Andreas Jakl ▪ Focusareas ▪ AR / VR, mobile apps, sensors, interaction technology, software architecture, open source developer (NFC, Bluetooth Beacons) ▪ Microsoft MVP (Most Valuable Professional) ▪ mobility.builders community: Mobile Developer After-Work Events ▪ Previous Experience ▪ Tieto, Start-up (Mopius), Nokia (Finland), Siemens Mobile (Munich), FH Hagenberg (Mobile Computing) Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten https://www.andreasjakl.com/ @andijakl andreas.jakl@fhstp.ac.at 2
  • 3.
    Contents ▪ Hybrid &Native Apps ▪ Native Android Development ▪ Android & SDK Versions ▪ Hello World ▪ Emulators, Devices & ADB ▪ Android Emulators & Build Process ▪ Kotlin Android Extensions ▪ App Lifecycle ▪ Saving App State ▪ Debugging ▪ Code Style + Documentation ▪ Activities & Intents ▪ Implicit Intents Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 3
  • 4.
    Android Studio ▪ Ifyou have not already: ▪ Install Android Studio now! ▪ It’ll take some time … ▪ https://developer.android.com/studio/index.html ▪ Already includes JDK ▪ Troubleshooting ▪ https://docs.google.com/document/d/1w1Xn_hnSAODAAtdRDp7haYPBtEwX _l7Htpf8Wpgbu6w/pub?embedded=true Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 4
  • 5.
    NATIVE APPS Web vsHybrid vs Native Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 5
  • 6.
    Web vs Hybridvs Native Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 6 Web Apps Multi-platform Web UI / UX Run in browser (can be offline) Slower performance Less system integration Native Apps Single platform Native UI / UX Run directly on OS Fast performance, best system integration. More expensive. Hybrid Apps Multi-platform Hybrid UI / UX Parts in HTML, parts native
  • 7.
    Web vs Hybridvs Native Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 7 Web Apps Native Apps Hybrid Apps Cost User Experience
  • 8.
    Additional Materials ▪ FreeAndroid Courses by Google & Udacity ▪ Java Programming Basics: https://www.udacity.com/course/java-programming- basics--ud282# ▪ Android Basics: User Interface: https://www.udacity.com/course/android-basics- user-interface--ud834# ▪ Developing Android Apps: https://www.udacity.com/course/new-android- fundamentals--ud851# ▪ Kotlin for Android Developers: https://www.udacity.com/course/kotlin-for- android-developers--ud888 ▪ Quick Kotlin overview for Java Android devs: https://developer.android.com/kotlin/index.html Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 8
  • 9.
    NATIVE ANDROID DEVELOPMENT AndroidDevelopment with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 9
  • 10.
    Android Development Android Developmentwith Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 10 Java Kotlin C++ Frame- works (Unity, Xamarin, Qt, …) Web Android Studio Visual Studio Specific tools Visual Studio Code, WebStorm, etc. IntelliJ IDEA
  • 11.
    Android Web /Hybrid Apps Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 11 Image source: Google, https://developer.android.com/guide/webapps/index.html
  • 12.
    Android Web /Hybrid Apps Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 12 Cordova Native functionality (Java, C++, …) Image source: Google, https://developer.android.com/guide/webapps/index.html
  • 13.
    Cross-Platform Engines ▪ Usuallyspecialized for app types ▪ Unity ▪ Games, 2D / 3D graphical apps ▪ Cross-platform ▪ Graphical editor, code with C# ▪ Xamarin ▪ Apps ▪ iOS, Android, Windows ▪ Cross-platform C# APIs, with Xamarin.Forms also UI. Specific native code possible ▪ Qt ▪ Apps and embedded ▪ Cross-platform ▪ UI with JavaScript / QML, native code with C++ Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 13 Image sources: Unity Logo, by Unity Technologies Public domain, https://en.wikipedia.org/wiki/File:Unity_Technologies_Logo.svg Xamarin Logo, by Xamarin Inc. / Microsoft Public domain, https://en.wikipedia.org/wiki/File:Xamarin-logo.svg Qt Logo, by The Qt Company Public domain, https://en.wikipedia.org/wiki/File:Qt_logo_2016.svg
  • 14.
    Android C++ ▪ NativeDevelopment Kit (NDK) ▪ C and C++ code ▪ Why? ▪ Reuse existing C++ code & libraries ▪ Extra performance, less latency ▪ Combine: communication Java <> C++ ▪ Java Native Interface (JNI) ▪ https://developer.android.com/ndk/guides/index.html Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 14 Image credits: logo for C++ created by Jeremy Kratz Licensed for use of any purpose by the Standard C++ Foundatino https://en.wikipedia.org/wiki/File:ISO_C%2B%2B_Logo.svg
  • 15.
    Java (for Android) ▪Java: Source code > Byte code > executed by Java Virtual Machine (JVM) ▪ License ▪ OpenJDK ▪ GPL v2 license ▪ De-facto reference implementation of Java by Oracle / Sun, basis for Oracle JDK ▪ Used in Android since Nougat ▪ Android uses recent Java. By default part of Android Studio: C:android-studiojre ▪ Trial Google vs. Oracle ▪ Use of Java = fair use? Switch to OpenJDK as a result (before: Apache Harmony, re-implementation of copyrighted Java APIs) ▪ http://www.zdnet.com/article/oracle-vs-google-just-as-you-thought-java-android-row-was-over-it-all-kicks-off-again/ Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 15 Image credits: Duke, the mascot used by Java. Copyright Sun Microsystems Inc., BSD license https://en.wikipedia.org/wiki/File:Duke_(Java_mascot)_waving.svg
  • 16.
    Kotlin ▪ Programming language,“improved Java” ▪ Runs on Java JVM ▪ Interoperable with Java code + libraries ▪ Possible to mix Kotlin + Java in same project ▪ But can also be compiled to JavaScript + native (C) ▪ Created by JetBrains ▪ Open source language (Apache 2 license): https://github.com/JetBrains/kotlin ▪ https://kotlinlang.org/ Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 16 Image credits: Kotlin Logo, by JetBrains. https://commons.wikimedia.org/wiki/File:Kotlin-logo.svg
  • 17.
    Kotlin & Android ▪Android ▪ Integrated in Android Studio 3+ ▪ Fully supported programming language for Android ▪ Kotlin Android Extensions: https://kotlinlang.org/docs/tutorials/android- plugin.html Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 17 Image credits: Kotlin Logo, by JetBrains. https://commons.wikimedia.org/wiki/File:Kotlin-logo.svg
  • 18.
    Android Studio ▪ OfficialIDE ▪ Customized from JetBrain’s IntelliJ IDEA ▪ Windows, Mac OS, Linux Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 18
  • 19.
    ANDROID PLATFORM Versions &Structure Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 19
  • 20.
    Android Versions ▪ VersionDistribution: https://developer.android.com/about/dashboards/index.html#Platform ▪ More features in newer versions ▪ But: partly backported ▪ Reduces fragmentation ▪ Support Library (AppCompat) ▪ Google Play Services Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 20
  • 21.
    Android Versions Android Developmentwith Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 21
  • 22.
    SDK Versions ▪ MinSDK ▪Lowest OS your app can run on ▪ Restricts features and APIs you can use ▪ TargetSDK ▪ Version you tested the app on ▪ Generally forward compatible: if behavior changes in new version, new Android will still “simulate” behavior of old TargetSDK version (e.g., Runtime permissions with Android M) ▪ https://developer.android.com/reference/android/os/Build.VERSION_CODES.html ▪ Use the latest version when starting a new project ▪ CompileSDK ▪ Not part of the manifest, only relevant for developer ▪ Generally use latest version -> allows using latest APIs if needed Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 22
  • 23.
    HELLO WORLD Your FirstAndroid App Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 23
  • 24.
    Create New Project AndroidDevelopment with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 24
  • 25.
    Android Development withKotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 25
  • 26.
    Android Development withKotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 26
  • 27.
    Android Development withKotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 27
  • 28.
    Project Structure Android Developmentwith Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 28 See: https://developer.android.com/studio/build/index.html
  • 29.
    Views ▪ Android userinterface (UI) composed of views ▪ TextView ▪ ImageView ▪ Button ▪ Etc. ▪ All managed by a layout ▪ Positioning of views on the screen Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 29
  • 30.
    Design Android Development withKotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 30 TextView ImageView Button Toggle: Design / Text (XML)
  • 31.
    XML Android Development withKotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 31 <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.andreasjakl.helloworld.MainActivity" tools:layout_editor_absoluteY="81dp"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginEnd="8dp" android:layout_marginStart="8dp" android:layout_marginTop="8dp" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="8dp" android:layout_marginStart="8dp" android:layout_marginTop="8dp" app:layout_constraintEnd_toEndOf="@+id/textView" app:layout_constraintStart_toStartOf="@+id/textView" app:layout_constraintTop_toBottomOf="@+id/textView" app:srcCompat="@android:drawable/btn_star_big_on" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="8dp" android:layout_marginTop="8dp" android:text="Button" app:layout_constraintEnd_toEndOf="@+id/imageView" app:layout_constraintStart_toStartOf="@+id/imageView" app:layout_constraintTop_toBottomOf="@+id/imageView" /> </android.support.constraint.ConstraintLayout> TextView ImageView Button
  • 32.
    Activity & Views ▪Activity’s onCreate(): ▪ R class ▪ Dynamically identify contents in res folder ▪ setContentView() ▪ Inflates the layout XML file Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 32 setContentView(R.layout.activity_main)
  • 33.
    SDK Manager ▪ AndroidStudio > File > Settings > Appearance & Behavior > System Settings > Android SDK, or: ▪ Install all “SDK platforms” you need ▪ SDK Tools: ensure you have at least ▪ Android SDK Build-Tools ▪ Android Emulator ▪ Android SDK Platform-Tools ▪ Android SDK Tools ▪ Google Play Services ▪ Google USB Driver (on Windows) ▪ Intel x86 Emulator Accelerator (HAXM installer) ▪ Support Repository Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 33
  • 34.
    Running the App ▪Press “Play” arrow ▪ Select deployment target ▪ Connected phones or emulator ▪ “Create New Virtual Device” Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 34
  • 35.
    Android Debug Bridge(ADB) ▪ ADB manages connections to phones & emulators ▪ Debugging ▪ Installing apps ▪ Windows: add to path (next slide) ▪ “adb.exe” usually in C:Androidplatform-tools ▪ Powershell: “adb devices –l” to show all connected devices Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 35 Emulator + phone connected
  • 36.
    Windows: Add ADBto Environment Variables Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 36
  • 37.
    Android Emulators ▪ Freelychoose device configuration ▪ Screen size, OS, memory, etc. ▪ Hardware Acceleration ▪ Intel HAXM, but only for Intel. Conflict with Hyper-V https://developer.android.com/studio/run/emulator- acceleration.html#accel-vm ▪ Alternative: Microsoft Android emulator https://www.visualstudio.com/vs/msft-android- emulator/ Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 37
  • 38.
    Deploy to AndroidPhone ▪ Enable Developer Options ▪ Settings > (System) > About Phone > tap 7x on “Build Number” ▪ Enable “USB debugging” ▪ Connect phone via USB ▪ Ensure debugging is active ▪ Device shows up in “adb devices” Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 38
  • 39.
    Gradle ▪ Build automationsystem ▪ Used by Android Studio ▪ Can be run manually from command line ▪ Converts code to installable package ▪ Configuration: build.gradle ▪ You define: dependencies, versions, etc. ▪ https://developer.android.com/studio/build /index.html Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 39 Image credits: Gradle Logo copyright Gradle, Inc. Build process copyright Google, https://developer.android.com/studio/build/index.html
  • 40.
    Android Build Process ▪Gradle settings ▪ settings.gradle (project root directory) ▪ Which modules to include. Usually only one line Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 40 include ':app'
  • 41.
    Android Build Process ▪Top-level build file ▪ build.gradle (project root directory) ▪ Applies to all modules ▪ buildscript: Gradle repositories & dependencies Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 41 buildscript { ext.kotlin_version = '1.2.10' repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.0.1' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } }
  • 42.
    Android Build Process ▪Module-level build file ▪ project/module/settings.gradle ▪ Only apply to this module ▪ Custom packaging options: Android options, module-level dependencies, product flavors (free / paid, …) Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 42
  • 43.
    ADDING INTERACTIVITY Hello World2.0 Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 43
  • 44.
    Adapt Size &Color ▪ Check Google Material Design guidelines ▪ https://material.io/guidelines/ ▪ Size ▪ View: use “dp” for device-independent pixels. Same physical view size no matter the pixel density of the screen. ▪ Text: use “sp” for scale-independent pixels. Also considers user’s settings. ▪ Color ▪ Use color tool: https://material.io/color/ Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 44
  • 45.
    Improving XML Definitions ▪Collect text in “res/values/strings.xml” ▪ Reference from TextView & Button ▪ Easier to localize and change ▪ Give useful IDs to elements ▪ Start with “@+id/” ▪ + indicates it’s a new resource ID ▪ Rename e.g., “@+id/textView” -> “@+id/tv_hello” Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 45 <TextView android:id="@+id/tv_hello"
  • 46.
    Interactivity with Kotlinfor Android ▪ MainActivity.kt > Change TextView text when Button is clicked ▪ Create member variables to access UI elements ▪ In onCreate(), find views: ▪ Set click listener and change TextView text Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 46 private lateinit var mChangeTextButton : Button private lateinit var mHelloTextView : TextView mHelloTextView = findViewById(R.id.tv_hello) mChangeTextButton = findViewById(R.id.bt_change) mChangeTextButton.setOnClickListener { mHelloTextView.text = "Welcome!" }
  • 47.
    Interactivity with Kotlinfor Android ▪ Define “Welcome!” text in strings.xml and load from Kotlin code: Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 47 mChangeTextButton.setOnClickListener { mHelloTextView.text = getText(R.string.welcome_text) }
  • 48.
    Kotlin Android Extensions ▪findViewById() – easy to make errors, lots of code to write ▪ Kotlin Android Extensions make accessing views easier ▪ build.gradle: ensure the plugin is loaded ▪ MainActivity.kt: Add import with name of xml file ▪ Directly access View elements: Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 48 apply plugin: 'kotlin-android-extensions' import kotlinx.android.synthetic.main.activity_main.* bt_change.setOnClickListener { tv_hello.text = getText(R.string.welcome_text) }
  • 49.
    Rotating the Screen? AndroidDevelopment with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 49 ? Text switches back to original
  • 50.
    ANATOMY OF ANDROIDAPPS Lifecycle Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 50
  • 51.
    Android Application Components 1.Activity ▪ “Single focused thing the user can do” ▪ Creates view (to draw, based on XML layout file) and receives events (touch) 2. Service 3. Content Provider 4. Broadcast Receiver Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 51
  • 52.
    Android Development withKotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 52 Source:https://developer.android.com/guide/components/activities/activity-lifecycle.html
  • 53.
    Task: Check Lifecycle ▪Override all lifecycle methods of the activity ▪ Log status message (Log.d) ▪ Create TAG to recognize your log messages ▪ Example ▪ Check output in logcat Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 53 private val TAG = MainActivity::class.java.simpleName override fun onStart() { super.onStart() Log.d(TAG, "onStart") }
  • 54.
    Task: Check Lifecycle ▪Rotate screen! Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 54 Rotation
  • 55.
    Saving the State ▪Bundle for storing small amount of data ▪ Only used when resuming apps, not for re-starts ▪ Built-in for activity: save key-value pairs ▪ Key definition ▪ Save state ▪ Restore in onCreate() + default if not set Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 55 private val KEY_TEXT = "uiText" override fun onSaveInstanceState(outState: Bundle?) { outState?.putString(KEY_TEXT, tv_hello.text.toString()) super.onSaveInstanceState(outState) } if (savedInstanceState != null) { tv_hello.text = savedInstanceState.getString(KEY_TEXT, getText(R.string.hello_text).toString()) }
  • 56.
    DEBUGGING Finding and FixingErrors Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 56
  • 57.
    Trigger Error ▪ Createunhandled exception in onCreate() ▪ App crashes on startup ▪ Check logcat (set log level to “Error”) Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 57 throw Exception("Error!")
  • 58.
    Debugging Android Apps ▪Set Breakpoints & use debugging tools ▪ Run app with “Debug” mode ▪ Break on any exception ▪ Run > View Breakpoints … > Activate “Any Exception” ▪ may include lots of others too Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 58
  • 59.
    Android Lint ▪ StaticCode Analysis: Analyze > Inspect Code… Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 59
  • 60.
    Issues with RClass / Unknown Error Source ▪ Recheck XML in your resource files (layouts, …) ▪ Android Studio might not highlight everything, e.g. some typos ▪ Clean project to rebuild from scratch ▪ Build > Clean Project ▪ Re-Sync project with Gradle ▪ Tools > Android > Sync Project with Gradle Files ▪ Run Android Lint Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 60
  • 61.
    Exercise: Guess-a-Number ▪ CreateUI with at least 3 views: ▪ EditText (“Plain Text” or “Number”), Button, TextView ▪ Put all user-visible text in strings.xml resource ▪ Phone thinks of random number [1..100] ▪ User enters number and taps button ▪ Phone tells if number was too low, too high or correct ▪ Bonus: also add number of tries to message ▪ Bonus: reset game and create new random number ▪ Bonus: handle screen rotation Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 61
  • 62.
    CODE STYLE Documentation &Naming Conventions Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 62
  • 63.
    Naming Conventions ▪ Androidnaming conventions & more: ▪ https://android.github.io/kotlin-guides/style.html ▪ Generic Kotlin ▪ https://kotlinlang.org/docs/reference/coding-conventions.html Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 63
  • 64.
    Naming Conventions ▪ Packagenames ▪ Always lowercase ▪ Classes / Objects ▪ Start with upper case letter, camel humps Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 64 package com.andreasjakl.helloworld class MainActivity : AppCompatActivity() {
  • 65.
    Naming Conventions ▪ Functions,properties, local variables ▪ Start with lower case letter, camel humps, no underscores ▪ Exception: constructors (-> same name as class, uppercase starting letter) ▪ Constants ▪ Uppercase, underscore-separated Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 65 var myCounter = 3 override fun onSaveInstanceState(outState: Bundle?) { private val KEY_TEXT = "uiText"
  • 66.
    Documenting Code ▪ Codecomments ▪ Important for classes, methods and properties (especially public) ▪ Java: JavaDoc ▪ Kotlin: KDoc – https://kotlinlang.org/docs/reference/kotlin-doc.html Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 66
  • 67.
    KDoc Syntax ▪ Addcomment directly above class / function ▪ Starts with /** , ends with */ ▪ Every documentation line has * at the beginning – not part of comment ▪ Block tags ▪ Parameters: @param <name> ▪ Returns: @return Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 67
  • 68.
    Generate Documentation: Dokka ▪Add dokka-android plugin to app build.gradle ▪ Add gradle task “dokka” to configure documentation ▪ See: https://github.com/Kotlin/dokka/blob/master/README.md Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 68 apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' apply plugin: 'org.jetbrains.dokka-android' dokka { outputFormat = 'html' outputDirectory = "$buildDir/javadoc" }
  • 69.
    Generate Documentation: Dokka ▪Configure docker version and dependency in module’s build.gradle ▪ Run gradle task “dokka” in terminal ▪ gradlew dokka Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 69 buildscript { ext.kotlin_version = '1.2.10' ext.dokka_version = '0.9.15' repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.0.1' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath "org.jetbrains.dokka:dokka-android-gradle-plugin:${dokka_version}" } }
  • 70.
    Generate Documentation: Dokka ▪Generated HTML documentation in app/build/javadoc directory: Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 70
  • 71.
    ACTIVITIES Adding multiple pagesto your app Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 71
  • 72.
    Our Task: PassingData Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 72
  • 73.
    Navigation Android Development withKotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 73 Activity Activity not called directly
  • 74.
    Indirect Triggering Android Developmentwith Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 74 Activity Activity Intents
  • 75.
    Flexibility: Launch VariousTasks Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 75 Activity Activity Start new Intents Take picture Open browser
  • 76.
    What is anIntent? Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 76 - Message object - Request action from other app component - Can include data (extras) Image source: Android Developer Guide https://developer.android.com/guide/components/intents-filters.html
  • 77.
    Exercise: Create MainActivity ▪ Name: GreetingApp ▪ UI ▪ TextView, EditText, Button ▪ Use helpful ids ▪ Externalize text to strings.xml ▪ Ensure proper dynamic layout ▪ Use setOnClickListener() on button ▪ Display entered text with a toast ▪ Search for documentation! Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 77
  • 78.
    Exercise: Create GreetingActivity Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 78
  • 79.
    Exercise: UI forGreeting Activity ▪ UI ▪ 2x TextView with helpful IDs ▪ Check AndroidManifest.xml ▪ Shows second activity ▪ It’s not configured for MAIN / LAUNCHER Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 79
  • 80.
    Context ▪ Global informationabout app environment ▪ Provided by Android system ▪ Access app-specific resources ▪ App-level operations (e.g., launching activities) Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 80
  • 81.
    Create & LaunchIntent Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 81 val welcomeIntent = Intent(this, GreetingActivity::class.java) startActivity(welcomeIntent) Context Activity to start Start!
  • 82.
    Passing Data ▪ Intentssupport extended data ▪ Key / Value-based ▪ Default Intent.EXTRA_TEXT for passing basic String data Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 82 welcomeIntent.putExtra(Intent.EXTRA_TEXT, et_name.text.toString()) Text from EditText
  • 83.
    Receiving Extra Data ▪Activity has intent property ▪ Provides access to details about Intent Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 83 // Check if the calling intent actually provided EXTRA_TEXT data if (intent.hasExtra(Intent.EXTRA_TEXT)) { // Retrieve String contents from EXTRA_TEXT data var userName = intent.getStringExtra(Intent.EXTRA_TEXT) // Apply the String to the UI tv_name.text = userName }
  • 84.
    Enable Back NavigationArrow ▪ Specify parent activity in manifest ▪ Add meta-data if targeting Android 4.0 ▪ For newer versions, the parentActivityName is enough Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 84 <activity android:name=".GreetingActivity" android:parentActivityName=".MainActivity"> <meta-data android:name="android.support.PARENT_ACTIVITY" android:value=".MainActivity" /> </activity>
  • 85.
    Implicit Intent ▪ Actionto be done + (optional) data ▪ Take picture ▪ Call contact ▪ Show web page ▪ … ▪ Multiple apps can handle intent? ▪ Android lets user choose Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 85 Activity Start new Take picture Open browser
  • 86.
    Open Web Site ▪Common Intents ▪ https://developer.android.com/guide/components/ intents-common.html ▪ -> Web Browser ▪ Extend UI ▪ Second button ▪ Click listener Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 86
  • 87.
    Resolving Intents Android Developmentwith Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 87 // Target address, converted from String to URI val webPage = Uri.parse("https://www.andreasjakl.com/") // Create an intent. ACTION_VIEW is generic to show data to the user // Apps can subscribe to handle specific URIs // See: https://developer.android.com/reference/android/content/Intent.html#ACTION_VIEW val webIntent = Intent(Intent.ACTION_VIEW, webPage) // Check if at least one app is installed to handle our intent if (webIntent.resolveActivity(packageManager) != null) { // If yes, start the activity! startActivity(webIntent) }
  • 88.
    URI? Android Development withKotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 88 scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment] https://www.andreasjakl.com/ mailto:andreas.jakl@fhstp.ac.at?subject=Android geo:48.214643,15.6224716 spotify:album:3hrSH1h42tH4W1ods3Cm7o
  • 89.
    Exercise ▪ Launch anothercommon intent ▪ https://developer.android.com/guide/components/intents-common.html ▪ Examples ▪ Map ▪ Share ▪ Email ▪ Camera ▪ Note: some activities need extra permissions in your manifest! Android Development with Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 89
  • 90.
    THANK YOU! Android Developmentwith Kotlin, Part 1 | 2018 | Andreas Jakl | FH St. Pölten 90