Open menu with table of contents Android Introduction
Logo of Stuttgart Media University for light theme Logo of Stuttgart Media University for dark theme
Android Development

Android Introduction

Stuttgart Media University

Agenda

  • What is Android?
  • Android Architecture (Platform challenges, OS Layers, Dalvic / ART, Dex Files)
  • Developer Toolchain (Android Studio, ADB)
  • Android Development Basics

What is Android?

1 What is Android?

  • Operating System for
    • ...
    • ...
    • ...

center 80%

Source: Google Blog

2 What is Android?

  • Operating System for ...
    • Smartphones
    • Tablets
    • Smart Watches
    • Smart TVs
    • Infotainment Systems
    • Android Automotive
    • Or more general: Embedded Systems

3 Short Android History

  • July 2005: Google acquires Android Inc.
  • 5. November 2007: Open Handset Alliance established
  • 21. October 2008: Google publishes the Android source code (Apache 2.0 License)
  • 2. February 2009: T-Mobile G1 / HTC Dream is first available Android hardware in Germany
  • February 2011: Motorola Xoom: First Tablet with Android 3.0 (Honeycomb)
  • 19. October 2011: Release of Ice Cream Sandwich (ICS, 4.0) on Samsung Galaxy Nexus
  • 9. July 2012: Release of Jelly Bean (4.1 - 4.3.1) and Google Nexus 7 Tablet
  • 12. November 2014: Release of Lollipop (5.0 - 5.1.1) intrtoducing responsive design language material design
  • 5. October 2015: Release of Marshmallow (6.0 - 6.0.1), USB-C support, contextual search from keywords in apps, app permissions
  • 22. August 2016: Release of Nougat (7.0 - 7.1.2), support for file based encryption
  • 21. August 2017: Release of Oreo (8.0 - 8.1), project treble
  • 6. August 2018: Release of Pie (9.0)
  • 3. September 2019: Release of Android 10, dark mode
  • 8. September 2020: Release of Android 11, 5G support, advanced notifications
  • 4. October 2021: Release of Android 12, Easier Wi-Fi Sharing, Material You as an update of Material Design
  • 15. August 2022: Release of Android 13, Apps are now required to request permission from the user before they are able to send notifications., Support for Bluetooth LE Audio
  • 4. October 2023: Releaso of Android 14, Customizable lock screen, Restrict apps for access of distinct photos and videos

4 What comes with Android?

  • Basic system tools, e.g. dialer, address book...
  • Media support: H.265 HEVC MP4, MP3, WebM, PNG, JEPG...
  • Messaging: SMS, MMS
  • Connectivity: Wi-Fi, GSM/EDGE, UMTS, LTE, 5G, Bluetooth, NFC
  • 2D/3D graphics (OpenGL)
  • Multitasking
  • Additional Hardware: Camera, GPS, accelerometer, gyroscope, magnetometer...

center

Source: giphy.com

Android Architecture

1 Android Platform Challenges

  • Small / cheap devices with
    • Low processing power
    • Little memory
    • Battery driven
    • Slow or missing network connectivity
  • Various hardware (Smartphone, Tablet, Watch, Infotainment, TV, car, exotic devices, thousands of brands)
    • Requires platform abstraction

2 Android Platform Architecture

  • Based on Linux Kernel (v3.0 since Android 4.x)
  • Hardware Abstraction Layer providing standardized library modules for device's harware
  • Android Runtime (ART) since v5.0 before, Dalvik VM
  • Native Libraries written in C/C++
  • Java API Framework for normal Android Apps
  • System Apps use the Java APIs
  • See: Android Developers - Platform Architecture

60%

3 Dalvik VM / ART Optimizations

Optimization Effect
Combination of multiple Class files in one DEX file Smaller memory footprint, faster load of the application
Sharing of DEX files between processes (read-only mapping) Smaller memory footprint, faster load of the application
Byte ordering and word alignment according to local machine (install time) Faster load of the application DEX file itself still platform independent
Bytecode pre-verification (as much as possible, install time) Faster load and execution
Install-time optimization of bytecode Faster execution, still platform independence
Register instead of stack based virtual machine Faster execution (~30%)

See: http://sites.google.com/site/io/dalvik-vm-internals

4 Dex File Format

80%

Android Developer Toolchain

1 Android Studio Contains

  • Android SDK
    • Android APIs
    • AVD Manager & Emulator
    • Android Development Tools
      • adb (Android Debug Bridge)
      • dx (.class -> .dex)
      • aapt (Android Asset Packaging Tool)
  • Android NDK
  • Download here

2 Android Debug Bridge (adb)

  • Terminal tool to connect to a device
    • Find it at (on macOS): /Users/\<user>/Library/Android/sdk/platform-tools
  • open shell on emulator
adb -e shell 
  • copy file/dir to device
adb push \<local> \<remote>
  • copy file/dir from device
adb pull \<remote> \[\<local>]
  • Install package
adb install \<file>

Android Development Basics

  • The Manifest
  • Jetpack Compose
  • Resources (Strings, Images, etc.)
  • Support Libraries
  • Android Build Process

1 Android Manifest

  • It names the Java package for the application (unique identifier for the app)
  • It describes the components of the application (e.g. activities, services, etc.) and names the classes that implement them
  • Defines the Intent messages that they can handle
  • Declares the permissions
  • It declares the minimum level of the Android API that the application requires.
  • It lists the libraries that the application must be linked against.
  • ...

1.1 Android Manifest Structure

<?xml version="1.0" encoding="utf-8"?>
<manifest>
    <uses-permission/>
    <application>
        <activity>
            <intent-filter>
                <action/>
                <category/>
                <data/>
            </intent-filter>
            <meta-data/>
        </activity>
        <service>
            <intent-filter>...</intent-filter>
            <meta-data/>
        </service>
    </application>
</manifest>

1.2 Android Manifest Example

center 80%

2 Jetpack Compose

  • It's the state of the art way to build modern native UI in Android
  • It makes UI development faster by writing less code. Jetpack Compose is a declarative programming paradigm
  • The UI is completely written in code and also compatible with the old way of writing layouts in xml

3 Comparison Layout XML and Jetpack Compose

3.1 The old Layout XML way

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:id="@+id/main"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical"
              tools:context=".MainActivity">

    <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!"/>

    <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button"/>

</LinearLayout>

3.2 The new Jetpack Compose way

@Composable
fun component() {
    Column(modifier = Modifier.fillMaxSize()) {
        Text(text = "Hello World!")
        Button(onClick = { /*TODO*/ }) {
            Text(text = "Button")
        }
    }
}

3.3 Basics of Composable Functions

A composable function always has the annotation @Composable. Within the function the basic building block is declared and describes the UI. It might contain several UI elements.

@Composable
fun MovieItem(movie: Movie, onMovieClick: (Movie) -> Unit) {
    AsyncImage(model = movie.poster, contentDescription = "poster")
    Text(text = movie.title)
    Text(text = movie.year)
}

center

In most of the cases you can just use the standard layout elements like Box, Row or Column to place the items on the screen.

@Composable
fun MovieItem(movie: Movie, onMovieClick: (Movie) -> Unit) {
    Row() {
        AsyncImage(model = movie.poster, contentDescription = "poster",)
        Text(text = movie.title)
        Text(text = movie.year)
    }
}

center

There are also properties to align the elements accordingly:

@Composable
fun MovieItem(movie: Movie, onMovieClick: (Movie) -> Unit) {
    Row(verticalAlignment = Alignment.CenterVertically) {
        AsyncImage(model = movie.poster, contentDescription = "poster",)
        Text(text = movie.title)
        Text(text = movie.year)
    }
}

center

You can also nest elements like you need them:

@Composable
fun MovieItem(movie: Movie, onMovieClick: (Movie) -> Unit) {
    Row(verticalAlignment = Alignment.CenterVertically) {
        AsyncImage(model = movie.poster, contentDescription = "poster",)
        Column {
            Text(text = movie.title)
            Text(text = movie.year)
        }
    }
}

center

A special property is the Modifier. This can be used to change the size, layout, behaviour of the element. You can also add information like accessibility labels or test tags. You can also make elements clickable. Please keep in mind that the order of the modifiers functions is significant because this can affect the final result.

@Composable
fun MovieItem(movie: Movie, onMovieClick: (Movie) -> Unit) {
    Row(verticalAlignment = Alignment.CenterVertically) {
        AsyncImage(modifier = Modifier.width(80.dp).padding(8.dp), model = movie.poster, contentDescription = "poster",)
        Column {
            Text(text = movie.title, fontSize = 20.sp)
            Text(text = movie.year)
        }
    }
}

center

4 Android Layouts

  • Each app uses UI components. Pretty popular ones are the Material components on Android
  • Here you can find an overview of the Material components
  • The most popular ones are:
    • Scaffold which provides a structure of your screen
    • TopAppBar to display a title and provide navigation
    • Text as a label to display text
    • Button to make clickable elements
    • TextField for text inputs

5 Android Layouts

The MainActivity class is the entry UI component. The onCreate() function belongs to the Activity Lifecycle and is automatically called by the system. In there you need to call the first composable in the setContent() function:

class MainActivity : ComponentActivity() {

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    enableEdgeToEdge()

    setContent {
      MovieTrackerTheme {
        MovieTracker()
      }
    }
  }
}

6 Android Layouts

To keep in mind that there are still old apps around you need to now the most common types of layouts:

6.1 Constraint Layout

A ConstraintLayout is a android.view.ViewGroup which allows you to position and size widgets in a flexible way.

6.2 Linear Layout

A layout that organizes its children into a single horizontal or vertical row. It creates a scrollbar if the length of the window exceeds the length of the screen.

6.3 Relative Layout

source: android

Enables you to specify the location of child objects relative to each other (child A to the left of child B) or to the parent (aligned to the top of the parent).

7 Managing State

  • All Android apps display state to the user, eg a list with movie entries fetched from a server
  • Composable can use the remember API to store objects in memory. There are 3 different ways to do so:
    • val mutableState = remember { mutableStateOf(default) }
    • var value by remember { mutableStateOf(default) }
    • val (value, setValue) = remember { mutableStateOf(default) }

Here is an example:

@Composable
fun helloContent() {
  Column(modifier = Modifier.padding(16.dp)) {
    var name by remember { mutableStateOf("") }
    if (name.isNotEmpty()) {
      Text(
        text = "Hello, $name!",
        modifier = Modifier.padding(bottom = 8.dp),
        style = MaterialTheme.typography.bodyMedium
      )
    }
    OutlinedTextField(
      value = name,
      onValueChange = { name = it },
      label = { Text("Name") }
    )
  }
}

8 Resource Types and Directories

  • Resources can be strings, images, styles, colors, layouts, other data ...
  • Each project contains resources in the /res folder where they are grouped by types
    • strings are in /res/values/strings.xml
    • icons are in /res/drawable
    • images in /res/mipmap
    • layouts are in /res/layout (not needed with Jetpack Compose)
  • Attributes can be used to reference other resources such as strings (@string) and images (@drawable):
AsyncImage(model = R.drawable.ic_launcher_background, contentDescription = "poster",)
Text(text = stringResource(id = R.string.app_name))

9 Resource Qualifiers

  • Problem: Many different Android devices with different screen sizes and resolutions exist
  • Thus, there must be a possibility to define different resources depending on the screen size and resolution of a device
  • Resource qualifiers allow us to define which resource should be used for which device type and Android will automatically use the right one

10 Resource Qualifiers

  • Resources can be device specific by using resource qualifiers
  • To specify configuration-specific alternatives for a set of resources:
  1. Create a new directory in res/ named in the form <resources_name>-<config_qualifier>

    • <resources_name> is the directory name of the corresponding default resources
    • <qualifier> is a name that specifies an individual configuration for which these resources are to be used
    • More than one qualifier can be appended, but the order must be correct
  2. Save the respective alternative resources in this new directory. The resource files must be named exactly the same as the default resource files

11 Resource Qualifiers

  • Example for default and alternative resources:
res/
    drawable/   
        icon.png
        background.png    
    drawable-hdpi/  
        icon.png
        background.png 
  • The hdpi qualifier indicates that the resources in that directory are for devices with a high-density screen.
    • The screen sizes and densities can be used as configuration qualifiers to provide different layouts and bitmap resources
  • A list of valid configuration qualifier names can be found here

12 Density Independent Design

center

13 Density Independent Design

  • Sizes of view components should be defined in Density Independent Pixels (dp) in order to always get the best results.

    More information here.

center

14 Density Independent Design

  • A density independent pixel (dp) describes the size of a UI element in a density independent manner
  • At 160ppi, one dp corresponds to one physical pixel (px)
  • For devices with densities other than 160ppi, the dp values are converted with the help of the densityFactor
  • The densityFactor describes the device's physical density in relation to the default density of 160ppi
  • To guarantee optimal UI quality, bitmap drawables for different physical densities have to be supplied
  • Obtaining the densityFactor at runtime:
val densityFactor = LocalDensity.current.density

15 The R Class

  • Mapping between resources in files and Java code is realized by using the R.java file
    • It is generated by Android with each build
    • It contains references to resources in the different XML files
public final class R {

    // ...

    public static final class layout {
        public static final int activity_main = 0x7f030000;
    }

    public static final class mipmap {
        public static final int ic_launcher = 0x7f020000;
        public static final int ic_launcher_round = 0x7f020001;
    }

    public static final class string {
        public static final int ButtonText = 0x7f050000;
        public static final int app_name = 0x7f050001;
    }
}

16 AndroidX and Support Libraries

  • Problem: Still many older Android versions are in use, so how can we develop apps using the latest features and providing those to older Android versions at the same time?
  • Solution: Use Jetpack's AndroidX libraries
    • Provides backward compatible versions of Android framework APIs
    • comprises the Android Jetpack libraries

Note: AndroidX is the successor of the deprecated Android Support Libraries. The usage of the old Android Support Libraries is not recommended anymore for most of the projects.

17 AndroidX and Support Libraries

  • The usage of the AndroidX library is unavoidable if one wants to support older Android versions and increase the amount of supported devices. Therefore, the usage of AndroidX is considered as best practice and thus Android Studio templates usually include them in the project templates
    • E.g. the AppCompatActivity class is the default class used for Activities that want to make use of the new Material Design features (introduced with API level 21)

18 Android Build Process

  • Compilers convert source code into DEX files and resources into binary resources
  • DEX files and resources are combined in a APK
  • APK is signed using the debug or release keystore
  • APK is zip-aligned to use less memory when running on a device by APK Packager
  • APK can be installed on device

60%

19 Android Build Process

20 Summary

  • Android is an open-source OS based on an embedded Linux kernel
  • It runs on numerous types of devices and is not only designed for Smartphones
  • Android Apps are written in Kotlin / Java but are optimized during build and installation time to run in an ARM optimized VM called Dalvik VM / ART (since 5.0)
  • Modern Android apps use Jetpack Compose to define the UI, XML files to define resources and a separation of UI design and program logic
  • In order to access resources from your code the R.java file is generated on each build

21 Recap Questions

  • What are the key procedures that are used in the Android Runtime to optimize the execution of code in a Virtual Machine?
  • What is the role of R-class on Android? By whom and when is the class created?
  • What are resource qualifiers used for?

Questions?