Goal
• Give you an idea of how to start developing mobile applications for Android
• Introduce the major concepts of Android applications, including:• UI & UX principles and techniques• Interacting with other applications and services, sensors• Testing
• Walk you through:• setting up the necessary development environment • creating several sample applications
• Homeworks
207/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu
References & Books
• Android developer portal• https://developer.android.com/guide
• Books• “Professional Android 4 Application Development”, By
Reto Meier. Wiley, 2010• (1 copy at J.Liivi library)
• “The Busy Coder’s Guide to Android Development”, By Mark L. Murphy• 2015 version is free (CC license)
https://commonsware.com/Android/4-2-free
• “Android in Action” by W. Frank Ableso, Robi Sen, Chris King, C. Enrique Ortiz. Manning, 2012
307/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu
Dealing with problems & Help
Practical Assistants:
• Jakob Mass ( [email protected] )
• Mohan Liyanage ( [email protected] )
Google Group
• https://groups.google.com/d/forum/mobile-app-development-2018
• Post any questions & technical issues
• Help out others!
407/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu
What is Android?
• An open-source mobile platform• Not just for phones
• TV, Watch, Smart Home Hub, Car Infotainment, Handheld GPS, …
• Google, Open Handset Alliance• 84 technology companies• Commitment to openness, shared vision and concrete plans
• A Linux-based, multiprocess, multithreaded OS• Each application is a different user• By default, every app runs in its own Linux process. • Each process has its own virtual machine, so an app's code
runs in isolation from other apps.
• Libraries & Support tools
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 5
Image: Wikimedia Commons user Wikideas1. The Android robot is reproduced or modified from work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License
Developing Applications
• You can write code for Android in Java, Kotlin or C/C++.• (Not taking into account 3rd party options)
• Today, Java is the most used language for Android
6
Java Kotlin
package com.example.firstapp;
import android.app.Activity;
…
public class MainActivity extends Activity {
String name = “John”;
@Override
protected void onCreate(Bundle savedState) {
super.onCreate(savedInstanceState);
…
}
}
package com.example.firstapp
import android.app.Activity
…
class MainActivity : Activity() {
var name = “John”
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedState)
…
}
}
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu
Software stack
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 7
Image: https://developer.android.com/guide/platform/
Android Software Stack
Linux Kernel• Foundation of the Android platform
• Provides key security features:• User-based permissions model• Process isolation• Application Sandbox
• E.g., file permission management:• one user cannot read/modify another user's files• Thus, one application cannot see the files created by
another application, except when explicitly shared by the developer
• Rooting• Only the kernel and a small subset of the core applications
run with root permissions• It’s possible to grant root access to applications, giving full
access to system files, applications and all application data
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 8
https://source.android.com/security/overview/kernel-security
Android Software Stack
Hardware Abstraction Layer (HAL)
• Provides interfaces for accessing device hardware capabilities from the higher-level Java API.
• HAL is divided into various modules/libraries: Camera, Bluetooth, etc., ..
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 9
https://source.android.com/devices/architecture/hal
Android Software Stack
Android Runtime
• Provides an environment to host applications
• Applications run using ART (Android Runtime)• Since Android v5.0 (API level 21)• Before, Dalvik was used
• Dalvik Executable (DEX) format• bytecode format designed specially for Android
• ART takes care of:• executing Dex bytecode specification
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 10
https://developer.android.com/guide/platform/#art
From source to execution
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 11
Check out “Comparative Analysis of Mobile App Reverse Engineering Methods on Dalvik and ART” by Na et al.
Android Java
Why Android/Dalvik Runtime?
• The runtime is optimized specifically for mobile applications
• Runs multiple VMs efficiently• Each application has its own VM instance
• Minimal memory footprint
• Relies on Linux kernel for threading and low-level memory management
1207/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu
Android Software Stack
• Native C/C++ Libraries
1307/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu
Java API & System Apps
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 14
https://developer.android.com/guide/platform
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 15
Supporting different versions..
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 16
https://developer.android.com/about/dashboards/ (August 2018)
Version Codename API %
2.3.3 -2.3.7
Gingerbread 10 0.3%
4.0.3 -4.0.4
Ice Cream Sandwich
15 0.3%
4.1.x
Jelly Bean
16 1.2%
4.2.x 17 1.8%
4.3 18 0.5%
4.4 KitKat 19 8.6%
5.0Lollipop
21 3.8%
5.1 22 15.4%
6.0 Marshmallow 23 22.7%
7.0Nougat
24 20.3%
7.1 25 10.5%
8.0Oreo
26 11.4%
8.1 27 3.2%
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 17
Development Environment & Tools• Android Studio, IntelliJ IDEA-based set of software tools
• Single, unified environment for developing Android• Download manager for SDK versions• Emulator• Performance profiling• Visual layout editing• Testing tools• …
(Formerly, Eclipse was used)
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 18
https://developer.android.com/studio/intro/
Getting Started
• I hope all of you have Android Studio installed
• If you haven’t, download the SDK tools and platforms for API 28
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 19
https://developer.android.com/training/basics/firstapp/creating-project
Exercise: Creating a New Project
1. Create a New Android Studio Project• minSDK 19
• Choose “Empty Activity” template
2. Let’s create an AVD (Android virtual device)
3. Run the application• You should see a view with “Hello, world!”
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 20
https://developer.android.com/studio/projects/create-project
Projects in Android Studio
• Applications are created as Gradle-based projects
• Gradle is a build automation-tool, it takes care of software development routines, such as• compiling the source code• executing tests• download and configuration of dependencies or other
libraries• packaging the application and additional files • Installing the application to a physical/virtual device and
running it there• ..
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 21
https://gradle.org/
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 22
https://developer.android.com/studio/projects/
Source code
Non-code resources
XML-based UI layout definitions
Images, icons
Constants
Build scripts of the project
Manifest file (Next slide)
Generally, we work with the build.gradle files only, especially the module-level build.gradle file!
A look at Gradle configuration
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 23
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "example.com.helloworld"
minSdkVersion 23
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-
rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
….
testImplementation 'junit:junit:4.12‘
…
}
Application Manifest
• Each project must declare an AndroidManifest.xmlfile
• Describes essential information about the app to the build tools, the Android OS, and Google Play
• It declares for instance:• The permissions that the app wishes to use• Capabilities such as supported device configurations• Metadata, such as the application package name• The components of the app (Activities, Services,
BroadcastReceivers, ..), and the corresponding Java (Kotlin) class names
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 24
https://developer.android.com/guide/topics/manifest/manifest-intro
2507/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu
Security in Android
• As mentioned earlier, follows standard Linux guidelines
• Each application runs in its own process
• Process permissions are enforced at user level and group IDs are assigned to processes
• Finer grained permissions are then granted (revoked) per operations
• Apps declare permissions in the manifest
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 26
https://developer.android.com/guide/topics/permissions/overview
Application Design Philosophy• Applications should be
• Lightweight• Resources are constrained: if your app consumes too much
RAM while in the background, it will get killed by the OS quickly!
• Responsive• The framework strongly discourages freeze-ups
• Secure, respectful of privacy• Declare and ask for only the permissions you need, when you
need them!
• Seamless• Usability is key, the framework gives you lots of tools to
support accessibility & localization options and storing, persisting data
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 27
Application priorities, process states• Applications have limited control over their own
lifecycles
• Recall that applications run in separate processes, each one in a separate instance of the ART virtual machine
• Memory and process management is handled by the runtime and kernel• Runtime may kill some services in the background
• Being aware of application states & priorities is critical
2807/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu
Process lifecycle, state hierarchy
1. Foreground process (active process)• Few simultaneously
2. Visible process• Activity that is visible to the user on-screen but not in
the foreground. E.g., if the foreground Activity is displayed as a dialog that allows the previous Activity to be seen behind it.
3. Service process• such as background network data upload or download
4. Cached process
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 29
https://developer.android.com/guide/components/activities/process-lifecycle
Android Activity lifecycle
Apps move through states during the lifecycle.Understanding the lifecycle is crucial, to prevent:
• Apps crashing if the user receives a call or switches to another app while using your app
• Using valuable resources when the user is not actively using your app
• Loss of user’s progress when they leave your app and return to it later
• Loss of progress or crashes when screen switches between landscape and portrait orientation
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 30
https://developer.android.com/guide/components/activities/activity-lifecycle
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 31
Let’s look at the default, empty activity
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
3207/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu
Logging in Android
• Traditional System.out.println is generally not used on Android (output may not be visible, depending on device)
• Instead, use the frameworks logging mechanisms:• android.util.Log class and its methods• For example, Log.v( String tag, String message)
• Tag: app name, view name, usually a constant per class• Message: the actual log message
• Log.v(..), Log.i( ..), Log.w( .. ), Log.e( ..)
• Log messages appear in the LogCat component of the Android Studio interface
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 33
https://developer.android.com/studio/debug/am-logcat
Exercise: Hello, LogCat!
• Write a message to the log output
• Put the statement in the onResume lifecycle method
• Verify that you can see the message in LogCat
3407/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu
Creating GUIs in Android
• Three approaches: • Declaring in XML
• Programmatically
• Visually• Android Studio Layout Editor
3507/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
36
Reference to XML-defined View
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu
Exercise 1: Programmatic UI
• Let’s create a vertical LinearLayout
• Add 2 buttons to it
3707/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu
XML-based approach
• Declarative approach
• Stored in /res/layout
• Straightforward XML vocabulary for view elements, such as widgets and layouts
• Declare the relationship and attributes of components
• During compiling, each XML layout is compiled into a View resource
• View resource is loaded via the setContentView() method
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 38
Exercise 2: XML-based UI
• Re-create the same LinearLayout activity using XML
• In res/layout, choose New-> Layout resource File
• Replace the default Root element with LinearLayout!
• We will look into the default option later
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 39
Troubleshooting
• If your XML is correct, but you’re not seeing anything in the “Design” view
• Quick workaround:• Change the Editor’s theme from AppTheme to something else (e.g.
Material Light)
There seems to be a bug in the latest versions of com.android.support:appcompat support library
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 40
Shouldn’t be seeing errors here!
String resources
• Notice the warnings the IDE shows you
• Android provides a system of managing resources like strings, numbers, colors, etc• Open app > res > values > strings.xml.
• Create a string value
• Use it for your button
4207/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu
Working with string resources
• strings.xml:
• Java:
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 43
https://developer.android.com/guide/topics/resources/string-resource
<string name="hello">Greetings!</string>
<string-array name="planets_array">
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
</string-array>
<string name="message">Hello, %1$s.</string>
// Single string
String string = getString(R.string.hello);
/// String array
Resources res = getResources();
String[] planets = res.getStringArray(R.array.planets_array);
// Formatted string
String text = getString(R.string.message, username);
Other resources
• Colour• accessed via the R.color class
• getResources().getColor(R.color.pink)
• Style, dimension resources• Accessed from the R.style, R.dimen classes
• Define various UI aspects such as margins, action bar configurations
44
<resources>
<color name="blue">#3F51B5</color>
<color name="pink">#FF4081</color>
</resources>
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu
Resource file benefits
• Separation of code & concerns• Easy to find, update – e.g no hardcoded strings, colours
in code
• Organizing, structuring resources• Localization
• Screen orientation
• Device type (tablet vs phone)
• Not just strings & layouts! • Color schemes
• Etc
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 45
https://developer.android.com/guide/topics/resources/available-resources
Supporting different screens
• Create additional res/layout directories for alternative layouts• Smallest width:
• Available width:
• Orientation:
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 46
https://developer.android.com/training/multiscreen/screensizes
Localizing applications
• Support different languages with • res/values-en
• res/values-fr
• res/values-est
• ISO 639 language codes
• Works for any resource – strings, mipmap images, ..
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 47
https://developer.android.com/training/basics/supporting-devices/languages
So far…
• Programmatic UI approach
• Declarative, XML-based UI approach
• Working with resources• Strings
• Colours
• Localization options
4807/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu
Coming back to screen sizes
• You should minimize hard-coding the position and size of your UI components or creating an alternative layout for every possible configuration
• Instead, build UI-s with flexible layouts, that stretch and adapt to the current size based on a set of rules (constraints)
• ConstraintLayout – easiest way to create a responsive layout
4907/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu
Visual approach: the Layout Editor
5007/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu
ConstraintLayout 101
• Every object must have:• At least 1 horizontal constraint
• At least 1 vertical constraint
• Centering objects:• Use 2 constraints on the same axis
• Next week we will have a more detailed look at ConstraintLayout
5107/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu
Exercise 3: Re-create the UI with ConstraintLayout
5207/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu
• Do NOT use the auto-converter tool!
Simple user interaction
• Let’s handle button clicks
• With the findViewById(..) method, you can get a handle for referencing XML-declared resources & view objects in code:
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 54
Button button = findViewById(R.id.buttonA);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//do something
}
});
Specifying click handler from XML
• Alternatively, in XML• Specify the click handler with the Button attribute android:onClick,setting its value to the method which will be called
• Create the corresponding method in the Activity
55
public void handleClick(View view) {
// Do something in response to button click
}
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu
Advantages of Declarative approach• Separation of appearance (presentation) from
state-changing code (business logic)
• Can change interface without having to completely recompile Java• View Resource is inflated at runtime
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 56
Exercise 4: Click counter
• Set up a click handler that updates the button to show the number of times it has been clicked
• Make the 2nd button restart the counter
• Try both the programmatic & declarative approach
5707/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu
Recap
• The Android Project
• Android Studio & Virtual Devices
• Application Lifecycle
• Working with resources
• Localization• Screens, Languages
• Basic UI creation & interaction• ConstraintLayout
• OnClick events
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 58
Homework. Task 1
• Implement a Celsius-Fahrenheit converter
• Should convert both ways
• Use EditText to get user input
• Use the setText, getText methods and click listeners
• Create separate portrait and landscape mode UI-s (using XML):• Portrait mode with LinearLayout• Landscape mode with
ConstraintLayout
07/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu 59
Homework. Task 2
• Observe the application lifecycle
• Override the onPause, onResume, onStop, onDestroy, onCreate lifecycle methods and with the help of logging answer these questions:
• Which of these methods are called & what order are they called in when:• Changing device orientation?• Hitting the ‘home’ button and returning to the application• Hitting the ‘back’ button and re-opening the application
• What happens to the EditText and TextView elements in each of these 3 cases (assuming the user has at least done 1 successful conversion)?
6007/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu
Homework 1 – additional info
• Deadline: before next lecture
• Submission: via the courses.cs.ut.ee page for this course
• You can also find a slightly more detailed explanation of the homework there
6107/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu
Next lecture
• Views & Layouts
• Fragments
• Events, Intents
• Application components
6207/09/2018 Mobile & Cloud Lab. Institute of Computer Science, University of Tartu