Android Development Basics: Module 1
Android Development Basics: Module 1
This module provides a foundational understanding of Android development, covering the essential theoretical concepts and practical skills needed to begin building
Android applications.
Theory
Overview of Android
Android is an open-source, Linux-based operating system designed primarily for touchscreen mobile devices such as smartphones and tablets. Developed by the
Open Handset Alliance, led by Google, it has become the most widely used mobile OS globally. Android's open nature allows manufacturers to customize the OS,
leading to a diverse ecosystem of devices.
Open Source: The Android Open Source Project (AOSP) allows developers to freely access and modify the source code.
Rich Application Framework: Provides a comprehensive set of APIs for developing sophisticated applications.
Customizable User Interface: Developers have extensive control over the look and feel of their applications.
Multiple Form Factors: Android is not limited to phones and tablets; it also powers TVs, wearables, and in-car entertainment systems.
Large User Base: Developing for Android provides access to a massive global audience.
Android Architecture
The Android operating system is structured as a software stack, composed of several layers, with each layer providing different services to the layer above it.
Applications: This is the top layer and includes the user-facing applications, both pre-installed (like the home screen, contacts, and camera) and third-party
apps downloaded from the Google Play Store.
Application Framework: This layer provides high-level services that applications can use directly. Key components of the Application Framework include:
Activity Manager: Manages the lifecycle of applications and provides a common navigation back stack.
Content Providers: Enables applications to share data with other applications.
Resource Manager: Provides access to non-code resources such as strings, graphics, and layout files.
Notifications Manager: Allows applications to display custom alerts in the status bar.
View System: A rich and extensible set of views used to build application user interfaces.
Android Runtime (ART): Starting from Android version 5.0 (Lollipop), ART is the runtime environment used by Android. It replaced the earlier Dalvik Virtual
Machine (DVM). ART is responsible for executing the application's code and managing memory. It compiles applications into a native machine code upon
installation, which improves performance and battery life.
Platform Libraries (Native C/C++ Libraries): This layer includes a set of C/C++ libraries used by various components of the Android system. These libraries
provide functionalities such as 2D and 3D graphics rendering (OpenGL ES), SQLite for database storage, and the WebKit for browser support.
Hardware Abstraction Layer (HAL): The HAL provides a standard interface that exposes device hardware capabilities to the higher-level Java API
framework. It allows Android to be agnostic about lower-level driver implementations.
Linux Kernel: At the bottom of the stack is the Linux kernel. Android relies on the Linux kernel for core system services such as security, memory
management, process management, network stack, and device drivers. The kernel acts as an abstraction layer between the device hardware and the rest of
the software stack.
Android Studio is the official Integrated Development Environment (IDE) for Android app development. It is based on JetBrains' IntelliJ IDEA software.
1. Download Android Studio: Visit the official Android Developer website to download the latest version of Android Studio.
2. Install Android Studio: Run the downloaded installer and follow the on-screen instructions. The setup wizard will guide you through the installation process.
3. Configure Android Studio: On the first launch, Android Studio will prompt you to configure your development environment. This includes downloading
necessary SDK components. It's recommended to go with the "Standard" setup for beginners.
4. SDK Manager: The SDK Manager helps you download and manage different Android SDK Platforms and tools. You can access it from the Android Studio
welcome screen or via "Tools" -> "SDK Manager".
Kotlin Basics
Kotlin is a modern, statically typed programming language that is the preferred language for Android development. It is fully interoperable with Java and offers a more
concise and expressive syntax.
Key features of Kotlin:
1. Start a New Project: Open Android Studio and click on "New Project" on the welcome screen or go to "File" > "New" > "New Project".
2. Choose a Project Template: Select a template for your app. For a simple first project, choose "Empty Activity".
3. Configure Your Project:
Name: Give your application a name.
Package name: This is a unique identifier for your app. By default, it's based on your company domain and application name.
Save location: Choose where to save your project files.
Language: Select "Kotlin".
Minimum SDK: Choose the minimum version of Android that your app will support.
4. Finish: Click "Finish" to create the project. Android Studio will then build the project and generate the necessary files.
Practice
Experiment 1.1: Set up Android Studio and create a new project.
This experiment involves following the steps outlined in the "Setting up Android Studio" and "Creating Your First Android Project" sections of the theory. The outcome
is a new, empty Android project ready for development.
In your new Android project, you can add a simple Kotlin file to run this program. However, a standalone Kotlin program is even simpler. The entry point for a Kotlin
application is the main function.
fun main() {
println("Hello, World!")
}
Explanation:
fun main(): This declares the main function, which is the starting point of the program.
println("Hello, World!"): This function prints the string "Hello, World!" to the standard output and adds a newline.
Experiment 1.3: Demonstrate the use of Kotlin data types and variables.
Kotlin has two keywords for declaring variables: val for immutable (read-only) variables and var for mutable variables.
fun main() {
// Immutable variable
val name: String = "John"
// name = "Jane" // This will cause a compilation error
// Mutable variable
var age: Int = 25
age = 26 // This is allowed
println("Name: $name")
println("Age: $age")
println("Value of pi: $pi")
println("Is a student: $isStudent")
}
fun main() {
val a = 15
val b = 5
// Addition
val sum = a + b
println("Sum: $sum") // Output: Sum: 20
// Subtraction
val difference = a - b
println("Difference: $difference") // Output: Difference: 10
// Multiplication
val product = a * b
println("Product: $product") // Output: Product: 75
// Division
val quotient = a / b
println("Quotient: $quotient") // Output: Quotient: 3
// Modulus (remainder)
val remainder = a % b
println("Remainder: $remainder") // Output: Remainder: 0
}
Conditional statements and loops are used to control the flow of execution in a program.
Conditional Expressions (if-else and when):
fun main() {
val number = 10
// if-else expression
if (number > 0) {
println("$number is positive")
} else if (number < 0) {
println("$number is negative")
} else {
println("$number is zero")
}
fun main() {
// for loop to iterate over a range
for (i in 1..5) {
print("$i ") // Output: 1 2 3 4 5
}
println()
// while loop
var i = 5
while (i > 0) {
print("$i ") // Output: 5 4 3 2 1
i--
}
println()
}
Functions are blocks of code that perform a specific task and can be reused.
// Function with parameters and a return value
fun add(a: Int, b: Int): Int {
return a + b
}
fun main() {
val sum = add(5, 3)
println("The sum is: $sum") // Output: The sum is: 8
fun main() {
// Creating an array of strings
val fruits = arrayOf("Apple", "Banana", "Cherry")
// Accessing an element
println(fruits[0]) // Output: Apple
fun main() {
// Immutable list
val numbers = listOf(1, 2, 3)
// Mutable list
val mutableNumbers = mutableListOf(4, 5, 6)
[Link](7) // Add an element
println(mutableNumbers) // Output: [4, 5, 6, 7]
}```
```kotlin
fun main() {
// Immutable map
val user = mapOf("name" to "John", "age" to 30)
println(user["name"]) // Output: John
}
Experiment 1.8: Implement object Oriented concept in Kotlin.
Object-Oriented Programming (OOP) is a paradigm based on the concept of "objects", which can contain data and code.
// Defining a class
class Car(val brand: String, val model: String, var year: Int) {
fun start() {
println("$brand $model is starting...")
}
}
fun main() {
// Creating an object (an instance of a class)
val myCar = Car("Toyota", "Camry", 2022)
// Accessing properties
println("My car's brand is ${[Link]}") // Output: My car's brand is Toyota
// Calling methods
[Link]() // Output: Brand: Toyota, Model: Camry, Year: 2022
[Link]() // Output: Toyota Camry is starting...
}
Module 2: Android Activities and Layouts (16 hours) Theory Activity & its type Layouts: Linear, Relative, Constraint, Frame,Table UI Components: TextView,
EditText, Button, ImageView, RecyclerView Material Design Principles, Activity Life Cycle Practice Experiment 2.1: Create a simple Android app with a single
activity Experiment 2.2: Design a user interface using Layout and user input controls (TextView, EditText, Button) Experiment 2.3: Design a user interface using
Constraint Layout Experiment 2.4: Design a user interface using Relative Layout . Experiment 2.5: Implement a simple calculator app in Android(Use themes &
Styles) Experiment 2.6: Implement material design components in Android. Experiment 2.7: Implement an activity lifecycle in Android
Theory
Activity & its type
An Activity is a fundamental building block of an Android app that represents a single, focused screen with which a user can interact and serves as the entry point
for a app's interaction with user. For example, an email app might have one activity that shows a list of new emails, another activity to compose an email, and another
for reading an email. Most apps are a collection of multiple activities.
UI Management: Activities manage the display of user interface elements like buttons, text views, images, and other widgets.
User Interaction Handling: They handle user interactions such as touches, clicks, and gestures.
Navigation: Activities facilitate navigation between different screens or parts of the application.
Standard: The default mode. A new instance of the activity is created every time it is started. Example: Clicking a button to open a new screen.
SingleTop: If an instance of this Activity already exists at the top of the stack, it won’t create a new one — it will reuse the existing one. Example:
Notifications opening a messaging app without creating multiple screens.
SingleTask: There will be only one instance of this Activity in the stack. Example: The home screen of an app — pressing back won’t create a new instance.
SingleInstance: Used for special cases where the Activity runs in its own task (independent of other activities). Example: A floating chat bubble like
Facebook Messenger
Android development, a layout is a way of organizing and arranging user interface elements within the user interface of an app. Layouts are defined using XML
(Extensible Markup Language) in Android, and they determine the structure and appearance of the app’s user interface.
LinearLayout: — Arranges its children elements in a single line either horizontally or vertically. — Useful for simple UIs with a linear arrangement of
components.
RelativeLayout: — Allows positioning of child elements relative to each other or the parent. — Supports more complex UI designs.
ConstraintLayout: -Similar to RelativeLayout but with a more flexible and powerful constraint-based system. — Supports building complex and responsive
UIs.
FrameLayout: —Places child elements on top of each other, relative to the top-left corner. — Useful for displaying a single item at a time, such as fragments
or overlapping views.
TableLayout: -Arranges views into rows and columns, similar to an HTML table. You use TableRow elements to define each row in the table.
UI Components, or Views, are the basic building blocks you use to create the user interface.
EditText: An extension of TextView that allows users to enter and edit text.
Button: A standard push-button that the user can press to trigger an action.
RecyclerView: A more advanced and flexible version of ListView. It is a container for displaying large data sets that can be scrolled through efficiently by
maintaining a limited number of views. It recycles views that scroll off-screen, which significantly improves performance.
Material Design is a comprehensive design system created by Google to help developers build high-quality, beautiful, and intuitive digital experiences. Its core
principles are:
Material is the Metaphor: The UI is treated as a series of layered surfaces that behave like physical materials, with realistic lighting, shadows, and depth.
This gives the design structure and predictability.
Bold, Graphic, Intentional: A focus on clear visual language using bold colors, strong typography, and meaningful white space to create hierarchy and guide
the user's attention.
Motion Provides Meaning: Animations and transitions are not just for decoration; they should be meaningful, guiding the user's focus and providing
feedback in a smooth and coherent way.
An activity has a lifecycle consisting of a series of callback methods that the Android system calls as the activity transitions between different states. Understanding
and implementing these callbacks is crucial for managing resources and creating a stable app.
onCreate(): This method is called when the activity is first created. It is responsible for initializing the activity’s UI, such as inflating the layout and finding
the views.
onPause(): Called when the activity is partially obscured (e.g., by a dialog) but still visible. You should stop any animations or other resource-intensive
operations here.
onStop(): Called when the activity is no longer visible to the user (e.g., another activity has covered it or the user pressed the Home button).
onDestroy(): The final call before the activity is destroyed. This happens either because the user is completely navigating away from it or because the
system needs to reclaim memory.
Practice
Experiment 2.1: Create a simple Android app with a single activity
This experiment involves creating a new project in Android Studio, selecting the "Empty Activity" template. Android Studio will automatically generate:
The default template provides a "Hello World!" TextView in the center of the screen, serving as a basic single-activity application.
Experiment 2.2: Design a user interface using Layout and user input controls (TextView, EditText, Button)
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email"
android:textSize="16sp"/>
<EditText
android:id="@+id/editTextEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:hint="Enter your email"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:layout_marginTop="16dp"
android:textSize="16sp"/>
<EditText
android:id="@+id/editTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="Enter your password"/>
<Button
android:id="@+id/buttonLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="32dp"
android:text="Login"/>
</LinearLayout>
Here is the same login form designed with ConstraintLayout for a more flexible and flat hierarchy.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<[Link] xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">
<TextView
android:id="@+id/textViewEmailLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email"
android:textSize="16sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/editTextEmail"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="Enter your email"
android:inputType="textEmailAddress"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/textViewEmailLabel" />
<TextView
android:id="@+id/textViewPasswordLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Password"
android:textSize="16sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/editTextEmail" />
<EditText
android:id="@+id/editTextPassword"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="Enter your password"
android:inputType="textPassword"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/textViewPasswordLabel" />
<Button
android:id="@+id/buttonLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="Login"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/editTextPassword" />
</[Link]>
This example shows how to arrange views relative to each other, like placing a description below a title.
activity_main.xml```xml
<TextView
android:id="@+id/titleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Article Title"
android:textSize="24sp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:id="@+id/authorTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="by John Doe"
android:layout_below="@id/titleTextView"
android:layout_alignEnd="@id/titleTextView" />
<ImageView
android:id="@+id/articleImage"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_below="@id/authorTextView"
android:layout_marginTop="16dp"
android:src="@android:drawable/ic_menu_gallery"
android:contentDescription="Article Image"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Read More"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"/>
```
Experiment 2.5: Implement a simple calculator app in Android (Use themes & Styles)
A style is a collection of attributes that specify the look for a single View.
<resources>
<style name="CalculatorButton">
<item name="android:layout_width">0dp</item>
<item name="android:layout_height">match_parent</item>
<item name="android:layout_weight">1</item>
<item name="android:textSize">24sp</item>
<item name="android:gravity">center</item>
</style>
</resources>
<Button
style="@style/CalculatorButton"
android:text="7" />
<Button
style="@style/CalculatorButton"
android:text="8" />
<Button
style="@style/CalculatorButton"
android:text="9" />
<Button
style="@style/CalculatorButton"
android:text="/" />
</LinearLayout>
<!-- ... add other rows ... -->
Set OnClickListener for each button to append numbers/operators to a display TextView and perform calculations when the equals button is pressed.
This involves adding the Material Components library and using its specific widgets.
1. Add Dependency: In your [Link] file, add the Material Components dependency.
2. Use a Material Theme: Ensure your app theme in [Link] or [Link] inherits from a [Link] theme.
<style name="AppTheme" parent="[Link]">
3. Use Material Components in Layout: Replace standard widgets with their Material counterparts.
Button -> [Link]
EditText -> [Link] with a
[Link] inside.
CardView -> [Link]
<[Link]
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
android:src="@drawable/ic_baseline_add_24"
android:contentDescription="Add Item"/>
To observe the lifecycle, override the lifecycle methods in [Link] and add a log statement to each.
[Link]
import [Link]
import [Link]
import [Link]
How to Observe:
2. Open the Logcat window in Android Studio (View > Tool Windows > Logcat).
Start the app: onCreate -> onStart -> onResume will be logged.
Return to the app: onRestart -> onStart -> onResume will be logged.
Rotate the screen: The activity is typically destroyed and recreated. You will see onPause -> onStop -> onDestroy -> onCreate -> onStart ->
onResume.
Press the Back button: onPause -> onStop -> onDestroy will be logged, and the activity finishes.
Android Intents serve as a fundamental component for communication between different parts of an Android application or between different Android applications.
[Link] a service
Types of Intents
1. Explicit Intents: These intents explicitly define the target component by specifying its class name. They are typically used to launch components within the
same application.
code
2. Implicit Intents: Implicit intents do not name a specific component. Instead, they declare a general action to perform, which allows a component from
another app to handle it.
code
package [Link]
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
Services :
A Service is an android component that can perform long-running operations in the background and does not provide a user interface. Another application
component can start a service, and it will continue to run in the background even if the user switches to another application.
Starting a Service: Use startService(Intent intent). The service will run indefinitely until stopSelf() or stopService(Intent intent) is called.
Stopping a Service: Use stopSelf() to stop the service from within itself, or stopService(Intent intent) to stop it from an external component.
1. Background Service
2. Bound Service:
Description: These services provide a client-server interface that allows components to interact with the service, send requests, receive responses, and even perform
IPC (Inter-Process Communication).An activity (or other component) binds to the service with bindService().
Use Cases: Interaction between different components of the same application or different applications.
3. Foreground Service:
Description: These services perform tasks that are noticeable to the user. They must display a notification in the status [Link] startForeground() inside the service.
Example: A music player app running in the background while the user is interacting with other apps.
START_STICKY — recreate the service and call onStartCommand with a null intent
Example
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Services Example"
android:textAlignment="center"
android:textSize="24sp"
android:textStyle="bold"
android:textColor="@color/black" />
<Button
android:id="@+id/bt_start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start Service"
android:padding="10dp"
android:textSize="30sp"
android:layout_margin="20dp" />
<Button
android:id="@+id/bt_stop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Stop Service"
android:padding="10dp"
android:textSize="30sp"
android:layout_margin="20dp"
android:layout_marginBottom="50dp" />
btStart = findViewById([Link].bt_start)
btStop = findViewById([Link].bt_stop)
[Link] {
// Start the service
startService(Intent(this, NewService::[Link]))
}
[Link] {
// Stop the service
stopService(Intent(this, NewService::[Link]))
}
}
import [Link] import [Link] import [Link] import [Link] import [Link]
<application
... >
<activity android:name=".MainActivity"
... >
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]" />
</intent-filter>
</activity>
Broadcast Receivers
Broadcast Receiver is one of the component in Android that enable apps to listen for and respond to broadcast messages from other apps or the system itself. Think
of it as a listener waiting for important announcements — like:
“Battery is low”
“SMS received
1. **Static Registration (Manifest-declared):**Declared in [Link]. The system can start your app automatically when the broadcast is
received. Works even if the app is not running.
2. Dynamic Registration (Context-registered): Registered in code using registerReceiver(). Only works while your app is running
Practice
Experiment 3.1: Use intents to navigate between activities.
This experiment shows how to use an explicit intent to navigate from MainActivity to SecondActivity.
1. Create Two Activities: Create a new project with an Empty Activity named MainActivity. Then, add another Empty Activity named
SecondActivity (File > New > Activity > Empty Activity).
<Button
android:id="@+id/btnNavigate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to Second Activity"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
[Link] {
// Create an explicit intent to start SecondActivity
val intent = Intent(this, SecondActivity::[Link])
startActivity(intent)
}
}
}
Experiment 3.2: Receive data from the user by Edit Text and pass the data to another activity using intent.
This builds on the previous experiment by sending data with the intent.
<EditText
android:id="@+id/editTextData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Enter some data"
app:layout_constraintBottom_toTopOf="@+id/btnNavigate"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="@+id/textViewReceivedData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
tools:text="Received Data"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
4. Modify [Link] to receive data:
1. Create a Fragment: (File > New > Fragment > Fragment (Blank)). Name it MyFragment. This will create [Link] and fragment_my.xml.
2. Design fragment_my.xml:
<[Link]
android:id="@+id/fragment_container_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
// ... in onCreate
if (savedInstanceState == null) {
[Link]()
.setReorderingAllowed(true)
.add([Link].fragment_container_view, MyFragment::[Link], null)
.commit()
}
This creates a simple service that logs a message every few seconds.
1. Create a Service Class: (File > New > Service > Service). Name it MyBackgroundService.
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
<application ...>
...
<service android:name=".MyBackgroundService" />
</application>
3. Start/Stop the service from [Link]: Add buttons to your layout to start and stop the service and implement their click listeners.
// In MainActivity
val startButton: Button = findViewById([Link])
val stopButton: Button = findViewById([Link])
[Link] {
startService(Intent(this, MyBackgroundService::[Link]))
}
[Link] {
stopService(Intent(this, MyBackgroundService::[Link]))
}
import [Link]
import [Link]
import [Link]
import [Link]
Experiment 3.6: Retrieve the device’s battery info. And show in a project.
<TextView
android:id="@+id/tvBatteryInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Battery Info:"
android:textSize="22sp"/>