0% found this document useful (0 votes)
30 views24 pages

Android Development Basics: Module 1

Module 1 introduces foundational concepts in Android development, covering Android's architecture, setting up Android Studio, and basics of Kotlin programming. It includes practical experiments to create a new Android project and implement various programming concepts. Module 2 focuses on Android Activities, layouts, and UI components, emphasizing Material Design principles and user interaction handling.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views24 pages

Android Development Basics: Module 1

Module 1 introduces foundational concepts in Android development, covering Android's architecture, setting up Android Studio, and basics of Kotlin programming. It includes practical experiments to create a new Android project and implement various programming concepts. Module 2 focuses on Android Activities, layouts, and UI components, emphasizing Material Design principles and user interaction handling.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module 1: Introduction to Android Development (16 hours)

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.

Key Features of Android:

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.

The main components of the Android architecture are:

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.

Setting up Android Studio

Android Studio is the official Integrated Development Environment (IDE) for Android app development. It is based on JetBrains' IntelliJ IDEA software.

Steps to install Android Studio:

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:

Concise: Reduces the amount of boilerplate code you need to write.


Null Safety: The type system helps to eliminate the risk of null pointer exceptions.
Interoperable: You can use Kotlin and Java code in the same project.
Structured Concurrency: Simplifies the management of asynchronous operations.

Creating Your First Android Project

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.

Experiment 1.2: Write a Kotlin program to print "Hello, World!".

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

// Kotlin can often infer the data type


val pi = 3.14 // Inferred as Double
val isStudent = true // Inferred as Boolean

println("Name: $name")
println("Age: $age")
println("Value of pi: $pi")
println("Is a student: $isStudent")
}

Common Data Types:

Integers: Byte, Short, Int, Long


Floating-point numbers: Float, Double
Booleans: Boolean (true or false)
Characters: Char
Strings: String

Experiment 1.4: Implement basic arithmetic operations in Kotlin.

Kotlin supports standard arithmetic operators for mathematical calculations.

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
}

Experiment 1.5: Implement a conditional expressions & loop in Kotlin.

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")
}

// when expression (similar to a switch statement)


val day = 3
val dayOfWeek = when (day) {
1 -> "Sunday"
2 -> "Monday"
3 -> "Tuesday"
4 -> "Wednesday"
5 -> "Thursday"
6 -> "Friday"
7 -> "Saturday"
else -> "Invalid day"
}
println("Day of the week is $dayOfWeek")
}

Loops (for and while):

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()
}

Experiment 1.6: Implement function concept in Kotlin.

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
}

// Function with no return value (returns Unit implicitly)


fun greet(name: String) {
println("Hello, $name!")
}

fun main() {
val sum = add(5, 3)
println("The sum is: $sum") // Output: The sum is: 8

greet("Alice") // Output: Hello, Alice!


}

Experiment 1.7: Implement collection and arrays in Kotlin.

Collections are used to store groups of related objects.

Arrays: Have a fixed size.

fun main() {
// Creating an array of strings
val fruits = arrayOf("Apple", "Banana", "Cherry")

// Accessing an element
println(fruits[0]) // Output: Apple

// Iterating through an array


for (fruit in fruits) {
print("$fruit ")
}
println()
}

Lists: Can be mutable (changeable) or immutable (read-only).

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]
}```

**Maps:** Store key-value pairs.

```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) {

// Method (a function within a class)


fun getCarInfo() {
println("Brand: $brand, Model: $model, Year: $year")
}

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...
}

Key OOP Concepts in this example:

Class: A blueprint for creating objects (Car).


Object: An instance of a class (myCar).
Properties: Data associated with an object (brand, model, year).
Methods: Functions that define the behavior of an object (getCarInfo, start).
Encapsulation: Bundling of data (properties) and methods that operate on the data into a single unit (the Car class).

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.

Key Features of 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.

The main types based on launch modes include:

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

Layouts: Linear, Relative, Constraint, Frame, Table

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: TextView, EditText, Button, ImageView, RecyclerView

UI Components, or Views, are the basic building blocks you use to create the user interface.

TextView: Displays text to the user.

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.

ImageView: Displays image resources, such as bitmaps or drawables.

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 Principles

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.

Activity Life Cycle

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.

The primary lifecycle methods are:

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.

onStart(): Called when the activity becomes visible to the user.


onResume(): Called when the activity is in the foreground and the user can start interacting with it.

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).

onRestart(): Called when an activity is starting again after being stopped.

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:

[Link]: The Kotlin file for the single activity.

activity_main.xml: The XML layout file for the activity's UI.

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)

This experiment demonstrates creating a simple login form using LinearLayout.

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>

Experiment 2.3: Design a user interface using Constraint Layout

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]>

Experiment 2.4: Design a user interface using Relative Layout

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)

This involves creating a basic calculator UI and applying consistent styling.

1. Define Styles in res/values/[Link]:

A style is a collection of attributes that specify the look for a single View.
<resources>

<!-- Base application theme. -->


<style name="AppTheme" parent="[Link]">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>

<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>

2. Design the Layout in activity_main.xml:

Use LinearLayout and apply the CalculatorButton style.

<!-- A simplified structure for one row of buttons -->


<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal">

<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 ... -->

3. Implement Logic in [Link]:

Set OnClickListener for each button to append numbers/operators to a display TextView and perform calculations when the equals button is pressed.

Experiment 2.6: Implement material design components in Android.

This involves adding the Material Components library and using its specific widgets.

1. Add Dependency: In your [Link] file, add the Material Components dependency.

implementation '[Link]:material:1.5.0' // Use the latest version

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]

Example with MaterialButton and FloatingActionButton:

<LinearLayout ... >


<[Link]
android:id="@+id/material_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
app:icon="@drawable/ic_baseline_send_24" />
</LinearLayout>

<[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"/>

Experiment 2.7: Implement an activity lifecycle in Android.

To observe the lifecycle, override the lifecycle methods in [Link] and add a log statement to each.

[Link]
import [Link]
import [Link]
import [Link]

class MainActivity : AppCompatActivity() {

private val TAG = "LifecycleDemo"

override fun onCreate(savedInstanceState: Bundle?) {


[Link](savedInstanceState)
setContentView([Link].activity_main)
Log.d(TAG, "onCreate called")
}

override fun onStart() {


[Link]()
Log.d(TAG, "onStart called")
}

override fun onResume() {


[Link]()
Log.d(TAG, "onResume called")
}

override fun onPause() {


[Link]()
Log.d(TAG, "onPause called")
}

override fun onStop() {


[Link]()
Log.d(TAG, "onStop called")
}

override fun onRestart() {


[Link]()
Log.d(TAG, "onRestart called")
}

override fun onDestroy() {


[Link]()
Log.d(TAG, "onDestroy called")
}
}

How to Observe:

1. Run the app on an emulator or a physical device.

2. Open the Logcat window in Android Studio (View > Tool Windows > Logcat).

3. Filter the logs by the tag "LifecycleDemo".

4. Perform actions and observe the log output:

Start the app: onCreate -> onStart -> onResume will be logged.

Press the Home button: onPause -> onStop 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.

**Module 3: Navigation & Data Passing **


Intents :

Android Intents serve as a fundamental component for communication between different parts of an Android application or between different Android applications.

You use intents to:

[Link] another activity (screen)

[Link] a service

[Link] a broadcast message

[Link] a web page, camera, email app, etc.

Types of Intents

There are two primary 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.

For example, opening another activity in the same app.

code

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
[Link](savedInstanceState)
setContentView([Link].activity_main)

val btnNext = findViewById<Button>([Link])

// Explicit Intent: Open SecondActivity


[Link] {
val intent = Intent(this, SecondActivity::[Link])
[Link]("username", "John Doe") // Send data
startActivity(intent) // Start the second activity
}
}
}

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.

For example, opening a web browser, camera, or dialer.

code
package [Link]

import [Link]
import [Link]
import [Link]
import [Link]
import [Link]

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
[Link](savedInstanceState)
setContentView([Link].activity_main)

val btnOpenWebsite = findViewById<Button>([Link])

// Implicit Intent: Open a web page


[Link] {
val intent = Intent(Intent.ACTION_VIEW)
[Link] = [Link]("[Link]
startActivity(intent)
}
}
}

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 and Stopping Services

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.

There are three main types of services:

1. Background Service

Description: Runs in the background without notification.

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.

Use Cases: Music player, file download.

Example: A music player app running in the background while the user is interacting with other apps.

Service lifecycle & important callbacks

onCreate() — called once when the service is created

onStartCommand(intent, flags, startId) — called when starting a service with startService()

onBind(intent) — called for bound services; returns an IBinder


onDestroy() — cleanup

onStartCommand return values:

START_NOT_STICKY — do not recreate the service if killed

START_STICKY — recreate the service and call onStartCommand with a null intent

START_REDELIVER_INTENT — recreate and redeliver last intent

Example

activity_main.xml (UI Layout)

<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" />

[Link] (Starting and Stopping the Service)

class MainActivity : AppCompatActivity() {


private lateinit var btStart: Button
private lateinit var btStop: Button

override fun onCreate(savedInstanceState: Bundle?) {


[Link](savedInstanceState)
setContentView([Link].activity_main)

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]))
}
}

[Link] (The Background Service)

import [Link] import [Link] import [Link] import [Link] import [Link]

class NewService : Service() {

private lateinit var player: MediaPlayer

override fun onBind(intent: Intent): IBinder? {


// [06:21] Returns null because this is an *unbound* service.
return null
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {


// Initialize and start the media player
player = [Link](this, [Link](this, RingtoneManager.TYPE_RINGTONE))
[Link] = true
[Link]()

// Return value ensures the service is restarted if killed by the system


return START_STICKY
}

override fun onDestroy() {


[Link]()
// Stop the media player when the service is destroyed
if ([Link]) {
[Link]()
}
[Link]()
}

<application
... >

<activity android:name=".MainActivity"
... >
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]" />
</intent-filter>
</activity>

<service android:name=".NewService" /> </application>

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”

“Airplane mode turned on”

“Wi-Fi connected or disconnected”

“SMS received

You can register a receiver in two ways:

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).

2. Add a Button to activity_main.xml:

<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" />

3. Implement the Intent in [Link]:


import [Link]
import [Link]
import [Link]
import [Link]

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
[Link](savedInstanceState)
setContentView([Link].activity_main)

val navigateButton: Button = findViewById([Link])

[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.

1. Modify activity_main.xml: Add an EditText.

<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" />

2. Modify [Link] to send data:

// ... inside the setOnClickListener


val dataToSend = findViewById<EditText>([Link]).[Link]()

val intent = Intent(this, SecondActivity::[Link])


// Put the data into the intent as an "extra"
[Link]("EXTRA_DATA", dataToSend)
startActivity(intent)

3. Modify activity_second.xml to display data: Add a TextView.

<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:

// ... inside onCreate


val receivedData = [Link]("EXTRA_DATA")
val textView: TextView = findViewById([Link])
[Link] = receivedData

Experiment 3.3: Create and use fragments in an Android app.

This demonstrates hosting a reusable Fragment inside an Activity.

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:

<FrameLayout ... >


<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="This is a Fragment"
android:textSize="20sp" />
</FrameLayout>

3. Add a container to activity_main.xml:

<[Link]
android:id="@+id/fragment_container_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />

4. Load the fragment in [Link]:

// ... in onCreate
if (savedInstanceState == null) {
[Link]()
.setReorderingAllowed(true)
.add([Link].fragment_container_view, MyFragment::[Link], null)
.commit()
}

Experiment 3.4: Implement a service to run in the background.

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]

class MyBackgroundService : Service() {


private val TAG = "MyBackgroundService"
private var isRunning = false

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {


Log.d(TAG, "Service Started")
if (!isRunning) {
isRunning = true
thread {
while (isRunning) {
Log.d(TAG, "Service is doing work in the background...")
[Link](5000)
}
}
}
return START_STICKY
}

override fun onDestroy() {


[Link]()
isRunning = false
Log.d(TAG, "Service Destroyed")
}

override fun onBind(intent: Intent): IBinder? {


return null
}
}

2. Declare the service in [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]))
}

Experiment 3.5: Use broadcast receivers to receive system events.


This shows how to listen for changes in airplane mode.

1. Create a BroadcastReceiver Class:

import [Link]
import [Link]
import [Link]
import [Link]

class AirplaneModeReceiver : BroadcastReceiver() {


override fun onReceive(context: Context?, intent: Intent?) {
if (intent?.action == Intent.ACTION_AIRPLANE_MODE_CHANGED) {
val isAirplaneModeOn = [Link]("state", false)
val message = if (isAirplaneModeOn) "Airplane Mode is ON" else "Airplane Mode is OFF"
[Link](context, message, Toast.LENGTH_SHORT).show()
}
}
}

2. Dynamically register the receiver in [Link]:

class MainActivity : AppCompatActivity() {

private lateinit var receiver: AirplaneModeReceiver

override fun onCreate(savedInstanceState: Bundle?) {


[Link](savedInstanceState)
setContentView([Link].activity_main)
receiver = AirplaneModeReceiver()
}

override fun onStart() {


[Link]()
val filter = IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED)
registerReceiver(receiver, filter)
}

override fun onStop() {


[Link]()
unregisterReceiver(receiver)
}
}

Experiment 3.6: Retrieve the device’s battery info. And show in a project.

This uses a broadcast receiver to monitor battery level.

1. Create the Receiver:


import [Link]
import [Link]
import [Link]
import [Link]
import [Link]

class BatteryReceiver(private val textView: TextView) : BroadcastReceiver() {


override fun onReceive(context: Context?, intent: Intent?) {
if (intent?.action == Intent.ACTION_BATTERY_CHANGED) {
val level = [Link](BatteryManager.EXTRA_LEVEL, -1)
val scale = [Link](BatteryManager.EXTRA_SCALE, -1)
val batteryPct = level * 100 / [Link]()
[Link] = "Battery Level: ${[Link]()}%"
}
}
}

2. Update activity_main.xml: Add a TextView to display the info.

<TextView
android:id="@+id/tvBatteryInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Battery Info:"
android:textSize="22sp"/>

3. Register and use the receiver in [Link]:

class MainActivity : AppCompatActivity() {

private lateinit var batteryReceiver: BatteryReceiver


private lateinit var tvBatteryInfo: TextView

override fun onCreate(savedInstanceState: Bundle?) {


[Link](savedInstanceState)
setContentView([Link].activity_main)
tvBatteryInfo = findViewById([Link])
batteryReceiver = BatteryReceiver(tvBatteryInfo)
}

override fun onStart() {


[Link]()
val filter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
registerReceiver(batteryReceiver, filter)
}

override fun onStop() {


[Link]()
unregisterReceiver(batteryReceiver)
}
}

You might also like