0% found this document useful (0 votes)
16 views67 pages

Untitled Document

The document provides step-by-step instructions for creating various Android applications using Kotlin, including a Hello World app, a simple calculator for adding two numbers, an app demonstrating the activity lifecycle, a Toast message app, and an app showcasing implicit and explicit intents. Each section includes project setup, XML layout design, and Kotlin code implementation. The guide is structured to be beginner-friendly, making it accessible for users with little to no programming experience.

Uploaded by

rwlrajat
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)
16 views67 pages

Untitled Document

The document provides step-by-step instructions for creating various Android applications using Kotlin, including a Hello World app, a simple calculator for adding two numbers, an app demonstrating the activity lifecycle, a Toast message app, and an app showcasing implicit and explicit intents. Each section includes project setup, XML layout design, and Kotlin code implementation. The guide is structured to be beginner-friendly, making it accessible for users with little to no programming experience.

Uploaded by

rwlrajat
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
You are on page 1/ 67

1 Create an Android app in Kotlin that displays Hello World on the

screen.

✅ Step 2: Create a New Project


When Android Studio opens:

1.​ Click "New Project".​

2.​ Select "Empty Activity" → Click Next.​

3.​ Set:​

○​ Name: HelloWorld​

○​ Language: Kotlin​

○​ Minimum SDK: API 21 (or keep default)​

4.​ Click Finish. 🎉​


Now Android Studio will create your app — this takes a minute ⏳.

✅ Step 3: Understand the Files (Don't worry, it's simple)


Android Studio gives you some important files:

📄 MainActivity.kt → This is like your app’s brain. It tells what to show.


📄 activity_main.xml → This is where we design the screen.

✅ Step 4: Edit the Design to Show "Hello World"


1.​ On the left, open: app > res > layout > activity_main.xml​

2.​ Change the code inside to this:​

<?xml version="1.0" encoding="utf-8"?>


<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/helloText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World"
android:textSize="30sp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

This makes a big "Hello World" text in the middle of the screen! 🎉

✅ Step 5: Run the App


You can run the app using:

1.​ An Android Phone (connect with USB + turn on Developer Mode)​

2.​ Or use the Emulator in Android Studio.​

Click the green play ▶️ button on top.


Wait a bit... and boom! 🎉 Your app will open and show:

====================================================================================
Create an Android app that takes two numbers as input
and displays their sum.

🚀 Step 2: Start a New Project


Open Android Studio:

1.​ Click New Project​

2.​ Choose Empty Activity​

3.​ Click Next​

Now fill:

●​ Name: AddNumbersApp​

●​ Language: Kotlin​

●​ Minimum SDK: Use the default (API 21 or above)​

Click Finish.​
Wait a bit while it sets everything up.

🧠 Step 3: Let's Design the Screen (XML)


Find the file called:

📁 app > res > layout > activity_main.xml


Click it, and remove everything inside. Now copy this code:

xml
CopyEdit
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<!-- First Number -->


<EditText
android:id="@+id/number1"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:hint="Enter first number"
android:inputType="number"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="80dp"/>

<!-- Second Number -->


<EditText
android:id="@+id/number2"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:hint="Enter second number"
android:inputType="number"
app:layout_constraintTop_toBottomOf="@id/number1"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="20dp"/>

<!-- Add Button -->


<Button
android:id="@+id/addButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
app:layout_constraintTop_toBottomOf="@id/number2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="20dp"/>

<!-- Answer Text -->


<TextView
android:id="@+id/resultText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result will be shown here"
android:textSize="20sp"
app:layout_constraintTop_toBottomOf="@id/addButton"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="30dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>

This creates:
●​ 2 input boxes 📦​
●​ 1 button ➕​
●​ 1 text for showing result 🧮​

👨‍💻 Step 4: Add Kotlin Code (The Brain)


Now open the file:

📁 app > java > your.package.name > MainActivity.kt


Change the code to this:

kotlin
CopyEdit
package com.example.addnumbersapp // Your package name might be different

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Get the views


val num1 = findViewById<EditText>(R.id.number1)
val num2 = findViewById<EditText>(R.id.number2)
val addBtn = findViewById<Button>(R.id.addButton)
val resultText = findViewById<TextView>(R.id.resultText)

// What happens when button is clicked


addBtn.setOnClickListener {
// Get the numbers as text
val n1 = num1.text.toString()
val n2 = num2.text.toString()

// Make sure both numbers are entered


if (n1.isNotEmpty() && n2.isNotEmpty()) {
val sum = n1.toInt() + n2.toInt()
resultText.text = "Sum = $sum"
} else {
resultText.text = "Please enter both numbers!"
}
}
}
}

What this code does:

●​ It waits for the button to be clicked​

●​ It takes the two numbers typed in​

●​ It adds them​

●​ It shows the sum on the screen​

▶️ Step 5: Run the App


Now click the green Play ▶️ button on top.
📱 If you have a phone, plug it in with a USB cable​
🖥 Or use the Android Emulator (like a pretend phone on your computer)
The app will open.

Try this:

●​ Type 5 and 3​

●​ Press "Add"​

🎉 You’ll see:
ini
CopyEdit
Sum = 8

====================================================================================
Create an android app to demonstrate Activity lifecycle.

✅ Step-by-step Guide
🛠 Step 1: Open Android Studio and Create New Project
1.​ Open Android Studio​

2.​ Click New Project​

3.​ Choose Empty Activity → Click Next​

4.​ Fill:​

○​ Name: LifecycleDemoApp​

○​ Language: Kotlin​

○​ Minimum SDK: Keep default​

5.​ Click Finish​

🎨 Step 2: Design is Not Important Here


We’ll keep it simple!

Open: 📁 app > res > layout > activity_main.xml


Change everything to this:

xml
CopyEdit
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<!-- Just a text label -->


<TextView
android:id="@+id/lifecycleText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity Lifecycle Demo"
android:textSize="24sp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

👨‍💻 Step 3: Write Kotlin Code to Show Lifecycle Messages


Open: 📁 app > java > your.package.name > MainActivity.kt
Replace everything with:

kotlin
CopyEdit
package com.example.lifecycledemoapp // Your package name

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
showToast("onCreate called")
}

override fun onStart() {


super.onStart()
showToast("onStart called")
}

override fun onResume() {


super.onResume()
showToast("onResume called")
}

override fun onPause() {


super.onPause()
showToast("onPause called")
}

override fun onStop() {


super.onStop()
showToast("onStop called")
}
override fun onDestroy() {
super.onDestroy()
showToast("onDestroy called")
}

private fun showToast(message: String) {


Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
}

✅ Step 4: Run the App 🚀


1.​ Click the green play ▶️ button​
2.​ Use a phone or emulator​

3.​ Watch the screen carefully...​

👀 What You'll See


When the app runs:

●​ It will show small popups (Toasts) like:​

○​ onCreate called​

○​ onStart called​

○​ onResume called​

Now try these:

1.​ Minimize the app → You'll see onPause, onStop​

2.​ Come back to app → You'll see onStart, onResume​

3.​ Close the app completely → You'll see onDestroy​

====================================================================================
Create an android app to demonstrate on Toast

✅ Step-by-Step: Make a Toast App


🛠 Step 1: Open Android Studio and Create a New Project
1.​ Open Android Studio​

2.​ Click New Project​

3.​ Choose Empty Activity → Click Next​

4.​ Fill:​

○​ Name: ToastDemoApp​

○​ Language: Kotlin​

○​ Minimum SDK: Use default (API 21 or above)​

5.​ Click Finish​

Wait a little bit…⏳​


Android Studio will set things up for you!

🎨 Step 2: Design the Screen (Add a Button)


Open this file:

📁 app > res > layout > activity_main.xml


Remove everything inside, and paste this:

xml
CopyEdit
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<!-- Button to show the Toast -->


<Button
android:id="@+id/toastButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Toast"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

🧁
This adds a button in the center of the screen.​
When we press it — Toast time!

👨‍💻 Step 3: Write Code to Show the Toast


Open this file:

📁 app > java > your.package.name > MainActivity.kt


Now change the code to:

kotlin
CopyEdit
package com.example.toastdemoapp // Your package name might be different

import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Find the button on screen


val toastButton = findViewById<Button>(R.id.toastButton)

// When button is clicked


toastButton.setOnClickListener {
// Show the toast
Toast.makeText(this, "Hello! I’m a Toast 🍞", Toast.LENGTH_SHORT).show()
}
}
}
▶️ Step 4: Run Your App!
1.​ Click the green play button ▶️​
2.​ Pick your phone or emulator​

3.​ Wait for the app to open...​

Now Try It:

✅ Tap the button that says "Show Toast"​


🎉 A message will pop up that says:​
"Hello! I’m a Toast 🍞"

That’s your first TOAST message! 🎊

====================================================================================
Create Android app which demonstrate implicit and explicit intent.

🤖 Step-by-Step Guide (Easy for a 10-Year-Old!)


🛠 Step 1: Create a New Project in Android Studio
1.​ Open Android Studio​

2.​ Click New Project​

3.​ Select Empty Activity → Click Next​

4.​ Fill:​

○​ Name: IntentDemoApp​

○​ Language: Kotlin​

○​ Click Finish​

Wait for setup to finish ⏳

🧩 Step 2: Create Second Activity (Second Screen)


1.​ Right-click on java > your.package.name​

2.​ Click New > Activity > Empty Activity​

3.​ Name it: SecondActivity​

4.​ Click Finish​

Now you have two screens (MainActivity and SecondActivity)

🎨 Step 3: Design activity_main.xml


Open:

📁 res > layout > activity_main.xml


Paste this layout with two buttons:
xml
CopyEdit
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<Button
android:id="@+id/openSecondActivityButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to Second Screen"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="100dp"/>

<Button
android:id="@+id/openBrowserButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Open Browser"
app:layout_constraintTop_toBottomOf="@id/openSecondActivityButton"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="20dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>

✍️ Step 4: Add Code in MainActivity.kt


Open:

📁 java > your.package.name > MainActivity.kt


Replace everything with:

kotlin
CopyEdit
package com.example.intentdemoapp

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val openSecond = findViewById<Button>(R.id.openSecondActivityButton)


val openBrowser = findViewById<Button>(R.id.openBrowserButton)

// Explicit Intent - open SecondActivity


openSecond.setOnClickListener {
val intent = Intent(this, SecondActivity::class.java)
startActivity(intent)
}

// Implicit Intent - open a website in browser


openBrowser.setOnClickListener {
val url = "https://www.google.com"
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
startActivity(intent)
}
}
}

🧾 Step 5: Add Message to SecondActivity


Open:

📁 res > layout > activity_second.xml


Replace everything with:

xml
CopyEdit
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SecondActivity">

<TextView
android:id="@+id/secondScreenText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="You are on the second screen!"
android:textSize="24sp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

✅ Step 6: Run Your App!


1.​ Click the green ▶️ Run button​
2.​ Wait for your app to open​

3.​ Tap the buttons:​

🎉 What You’ll See:


●​ ✅ Tap Go to Second Screen​
➤ It opens your second screen using Explicit Intent​

●​ ✅ Tap Open Browser​


➤ It opens Google in your browser using Implicit Intent

====================================================================================
Create an Android application using Kotlin that
demonstrates the use of different layouts
(LinearLayout, RelativeLayout, and
ConstraintLayout) .

🤖 Let’s Build: Android App with 3 Layouts!


🛠 Step 1: Create a New Project
1.​ Open Android Studio​

2.​ Click New Project​

3.​ Choose Empty Activity → Click Next​

4.​ Fill:​

○​ Name: LayoutDemoApp​

○​ Language: Kotlin​

○​ Minimum SDK: Keep it default​

5.​ Click Finish​

✨ Step 2: Create 3 New Layout Files


We’ll make 3 screens:

Layout Type File Name

Linear Layout activity_linear.x


ml

Relative activity_relative
Layout .xml

Constraint activity_main.xml

Let’s make each one by one 👇


🟥 Step 3: Create activity_linear.xml
1.​ Go to: res > layout​

2.​ Right-click → New > Layout Resource File​

3.​ Name it: activity_linear​

4.​ Choose Root Element: LinearLayout​

Then paste this code:

xml
CopyEdit
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:text="This is LinearLayout"
android:textSize="22sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

<Button
android:text="Click Me"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>

🟩 Step 4: Create activity_relative.xml


Same as above, but choose root element as RelativeLayout and name the file activity_relative.

Paste this code:

xml
CopyEdit
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/titleText"
android:text="This is RelativeLayout"
android:textSize="22sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

<Button
android:text="Click Me"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/titleText"
android:layout_marginTop="20dp"/>
</RelativeLayout>

🟦 Step 5: Use ConstraintLayout in activity_main.xml


This file was already created. Replace its code with:

xml
CopyEdit
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:padding="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/constraintText"
android:text="This is ConstraintLayout"
android:textSize="22sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>

<Button
android:text="Click Me"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@id/constraintText"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="20dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>

📲 Step 6: Add Activities for Each Layout


You already have MainActivity. Let’s add two more activities.

🧩 Add LinearActivity:
1.​ Right-click java > your.package.name​

2.​ New → Kotlin Class → Name it: LinearActivity​

kotlin
CopyEdit
package com.example.layoutdemoapp

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity

class LinearActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_linear)
}
}

🧩 Add RelativeActivity:
Same way, create RelativeActivity.kt and paste:

kotlin
CopyEdit
package com.example.layoutdemoapp

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity

class RelativeActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_relative)
}
}

📒 Step 7: Add Buttons in activity_main.xml to Open Other Layouts


We’ll now make the ConstraintLayout screen open other layout screens.

Replace your ConstraintLayout layout with this:

xml
CopyEdit
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:padding="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
android:id="@+id/btnLinear"
android:text="Show LinearLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>

<Button
android:id="@+id/btnRelative"
android:text="Show RelativeLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@id/btnLinear"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="20dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>

Then update MainActivity.kt to:

kotlin
CopyEdit
package com.example.layoutdemoapp

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val btnLinear = findViewById<Button>(R.id.btnLinear)
val btnRelative = findViewById<Button>(R.id.btnRelative)

btnLinear.setOnClickListener {
startActivity(Intent(this, LinearActivity::class.java))
}

btnRelative.setOnClickListener {
startActivity(Intent(this, RelativeActivity::class.java))
}
}
}

🧠 Step 8: Register All Activities in AndroidManifest.xml


Open AndroidManifest.xml and add:

xml
CopyEdit
<activity android:name=".LinearActivity" />
<activity android:name=".RelativeActivity" />

So it looks like:

xml
CopyEdit
<application
...
<activity android:name=".RelativeActivity" />
<activity android:name=".LinearActivity" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

▶️ Step 9: Run and Test!


1.​ Click Run ▶️​
2.​ Tap buttons:​

○​ "Show LinearLayout" → 📏 opens Linear layout​


○​ "Show RelativeLayout" → 🔀 opens Relative layout

====================================================================================
Create an Android application in Kotlin that uses a
button .

🛠 Step-by-Step 🧒
🟢 Step 1: Open Android Studio
1.​ Open Android Studio​

2.​ Click New Project​

3.​ Select Empty Activity → Click Next​

4.​ Fill like this:​

○​ Name: ButtonApp​

○​ Language: Kotlin​

○​ Leave everything else as it is​

5.​ Click Finish​

🟡 Step 2: Add a Button in activity_main.xml


This file controls how your screen looks.

Go to this file:

nginx
CopyEdit
app > res > layout > activity_main.xml

Replace everything with this:

xml
CopyEdit
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="20dp">
<Button
android:id="@+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me!" />
</LinearLayout>

🔵 Step 3: Add Button Code in MainActivity.kt


This file controls what happens when you click something.

Go to:

nginx
CopyEdit
app > java > your_package_name > MainActivity.kt

Replace everything with this:

kotlin
CopyEdit
package com.example.buttonapp // your app package

import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Find the button using its ID


val myButton = findViewById<Button>(R.id.myButton)

// Set what happens when button is clicked


myButton.setOnClickListener {
// Show a message
Toast.makeText(this, "You clicked the button!",
Toast.LENGTH_SHORT).show()
}
}
}
▶️ Step 4: Run the App
1.​ Click the green play button ▶️ at the top​
2.​ Select an emulator or connect your phone with USB​

3.​ Wait for app to launch...​

👉 Tap the button — you’ll see a message:​


“You clicked the button!”

====================================================================================
Create a android &quot;Hello World&quot; app using Jetpack
Compose in Android Studio:

🟢 Step 1: Open Android Studio


1.​ Open Android Studio​

2.​ Click on "New Project"​

3.​ Select Empty Compose Activity (not normal Empty Activity)​

4.​ Click Next​

Then fill in these details:

●​ Name: HelloWorldCompose​

●​ Language: Kotlin​

●​ Minimum SDK: API 21 or higher​

●​ Click Finish​

Now wait a little bit. It will create your app with some code already.

🟡 Step 2: Understand the Files


Go to the file:

nginx
CopyEdit
app > java > com.example.helloworldcompose > MainActivity.kt

Android Studio already adds some code to show “Android”. Let’s change that to “Hello World”

🔵 Step 3: Change the Text


In MainActivity.kt, find this part:

kotlin
CopyEdit
Greeting("Android")

Change "Android" to "Hello World" so it looks like:

kotlin
CopyEdit
Greeting("Hello World")

Also, if you want, you can customize the Greeting function like this:

kotlin
CopyEdit
@Composable
fun Greeting(name: String) {
Text(text = name)
}

So the whole code will now look like:

kotlin
CopyEdit
package com.example.helloworldcompose

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
import com.example.helloworldcompose.ui.theme.HelloWorldComposeTheme

class MainActivity : ComponentActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HelloWorldComposeTheme {
Surface {
Greeting("Hello World")
}
}
}
}
}

@Composable
fun Greeting(name: String) {
Text(text = name)
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
HelloWorldComposeTheme {
Greeting("Hello World")
}
}

▶️ Step 4: Run the App


1.​ Click the Green Play Button ▶️ at the top​
2.​ Select a phone emulator or connect your phone​

3.​ Wait for it to run​

You’ll see this on your screen:

nginx
CopyEdit
Hello World

🎉 YAY! You did it!

====================================================================================
Create a android app to create basic notification.

🟢 Step 1: Open Android Studio


1.​ Open Android Studio​

2.​ Click New Project​

3.​ Choose Empty Activity​

4.​ Click Next​

Now fill this:

●​ Name: NotificationApp​

●​ Language: Kotlin​

●​ Minimum SDK: 21 or higher​

●​ Click Finish​

🟡 Step 2: Add a Button to Trigger Notification


Open this file:

nginx
CopyEdit
app > res > layout > activity_main.xml

Replace with:

xml
CopyEdit
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">

<Button
android:id="@+id/notifyButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Notification" />
</LinearLayout>

🔵 Step 3: Add Notification Code in MainActivity.kt


Now go to:

nginx
CopyEdit
app > java > com.example.notificationapp > MainActivity.kt

Replace the code with:

kotlin
CopyEdit
package com.example.notificationapp

import android.app.NotificationChannel
import android.app.NotificationManager
import android.os.Build
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat

class MainActivity : AppCompatActivity() {

private val CHANNEL_ID = "channel_id_example_01"


private val NOTIFICATION_ID = 101

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

createNotificationChannel()

val notifyButton = findViewById<Button>(R.id.notifyButton)


notifyButton.setOnClickListener {
showNotification()
}
}

private fun createNotificationChannel() {


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "Example Channel"
val descriptionText = "This is a demo notification channel"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
description = descriptionText
}
val notificationManager: NotificationManager =
getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}

private fun showNotification() {


val builder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setContentTitle("Hello Rajat!")
.setContentText("This is your first notification 🎉")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)

with(NotificationManagerCompat.from(this)) {
notify(NOTIFICATION_ID, builder.build())
}
}
}

🧠 What Does This Do?


●​ 📦 createNotificationChannel() → Makes a space for notifications (Android 8+ needs this)​
●​ 🛎 showNotification() → Sends a notification when you click the button​

✅ Step 4: Give Permission (Android 13+ only)


If you’re using Android 13 or above, you need to ask for notification permission.

Add this to AndroidManifest.xml:

xml
CopyEdit
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>

And inside onCreate() (above showNotification()):

kotlin
CopyEdit
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
requestPermissions(arrayOf(android.Manifest.permission.POST_NOTIFICATIONS), 101)
}

▶️ Step 5: Run the App!


1.​ Click the green play button ▶️​
2.​ Tap the “Show Notification” button​

🛎 BOOM! You’ll see:​


🎉”
3.​
“Hello Rajat! This is your first notification

====================================================================================
Create an Android application that demonstrates
the use of a ListView to display a list of items.

🟢 Step 1: Open Android Studio


1.​ Open Android Studio​

2.​ Click on New Project​

3.​ Select Empty Activity​

4.​ Click Next​

Now fill this:

●​ Name: ListViewApp​

●​ Language: Kotlin​

●​ Minimum SDK: API 21 or higher​

●​ Click Finish​

🟡 Step 2: Add a ListView in activity_main.xml


This file controls how your screen will look.

Open this file:

nginx
CopyEdit
app > res > layout > activity_main.xml

Replace the code inside with this:

xml
CopyEdit
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<!-- ListView to show the list of items -->
<ListView
android:id="@+id/myListView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>

🔵 Step 3: Prepare Data for the List


Now, let’s put the data we want to show in the ListView.

Open this file:

nginx
CopyEdit
app > java > com.example.listviewapp > MainActivity.kt

Replace the code with:

kotlin
CopyEdit
package com.example.listviewapp

import android.os.Bundle
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Data to show in ListView


val items = listOf("Apple", "Banana", "Cherry", "Date", "Elderberry", "Fig",
"Grapes")

// Find the ListView


val listView = findViewById<ListView>(R.id.myListView)

// Create an ArrayAdapter to bind data to ListView


val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, items)

// Set the adapter to the ListView


listView.adapter = adapter
// Add a click listener to ListView items
listView.setOnItemClickListener { parent, view, position, id ->
val selectedItem = parent.getItemAtPosition(position).toString()
Toast.makeText(this, "You clicked: $selectedItem",
Toast.LENGTH_SHORT).show()
}
}
}

🧠 What’s Happening Here?


●​ items: We created a list of fruits.​

●​ ArrayAdapter: This is used to connect the list of items to the ListView.​

●​ setOnItemClickListener: This makes the items clickable. When you tap an item, it will show a
Toast message.​

✅ Step 4: Run the App


1.​ Click the green play button ▶️​
2.​ Select an emulator or connect your phone​

3.​ Wait for the app to launch​

You’ll see a list of fruit names: Apple, Banana, Cherry...

Now, when you tap any item in the list, a Toast will show saying, “You clicked: [Fruit Name]”.

====================================================================================
Create an Android application that demonstrates the use of a
ListView to display a list of item and icon.

🟢 Step 1: Create a New Project


1.​ Open Android Studio​

2.​ Click New Project​

3.​ Select Empty Activity​

4.​ Click Next​

Now fill in these details:

●​ Name: ListViewWithIcons​

●​ Language: Kotlin​

●​ Minimum SDK: API 21 or higher​

●​ Click Finish​

🟡 Step 2: Add Icons to the Project


Before we work on the code, let’s add some icons.

1.​ Download some icons: You can search for free icons on sites like Flaticon. Let’s say we want to use
fruit icons.​

2.​ Add the icons to your project:​

○​ Open the folder res > drawable​

○​ Right-click on drawable and click New > Image Asset​

○​ Select Icon Type as Image and choose the fruit images you downloaded.​

3.​ Name each image something meaningful like apple_icon.png, banana_icon.png, etc.​

🔵 Step 3: Add ListView to activity_main.xml


Now, let’s make the layout where the ListView will show up.

Go to res > layout > activity_main.xml and replace the code with this:

xml
CopyEdit
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<!-- ListView to display text and icons -->


<ListView
android:id="@+id/myListView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>

🟠 Step 4: Create a Custom Adapter


A Custom Adapter allows us to show both text and icons in each list item.

Open MainActivity.kt and add this code:

kotlin
CopyEdit
package com.example.listviewwithicons

import android.os.Bundle
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.ListView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Create data with item names and icon ids


val items = listOf(
Item("Apple", R.drawable.apple_icon),
Item("Banana", R.drawable.banana_icon),
Item("Cherry", R.drawable.cherry_icon),
Item("Date", R.drawable.date_icon),
Item("Elderberry", R.drawable.elderberry_icon)
)

// Find the ListView


val listView = findViewById<ListView>(R.id.myListView)

// Create an ArrayAdapter to manage the data


val adapter = CustomAdapter(this, items)

// Set the adapter to the ListView


listView.adapter = adapter

// Add a click listener to ListView items


listView.setOnItemClickListener { parent, view, position, id ->
val selectedItem = parent.getItemAtPosition(position) as Item
Toast.makeText(this, "You clicked: ${selectedItem.name}",
Toast.LENGTH_SHORT).show()
}
}
}

// Create a data class for the item (name and icon)


data class Item(val name: String, val iconResId: Int)

// Custom Adapter for the ListView


class CustomAdapter(private val context: MainActivity, private val items: List<Item>)
: ArrayAdapter<Item>(context, 0, items) {

override fun getView(position: Int, convertView: android.view.View?, parent:


android.view.ViewGroup): android.view.View {
val view = convertView ?:
android.view.LayoutInflater.from(context).inflate(android.R.layout.simple_list_item_2
, parent, false)

// Get the current item


val currentItem = getItem(position)

// Set the text and icon


val textView: TextView = view.findViewById(android.R.id.text1)
val imageView: ImageView = view.findViewById(android.R.id.icon)

textView.text = currentItem?.name
imageView.setImageResource(currentItem?.iconResId ?: 0)

return view
}
}

🧠 What’s Happening Here?


●​ Item Data Class: This stores the name and icon resource ID for each item.​

●​ CustomAdapter: This is a custom adapter that binds the name and icon to each item in the list.​

●​ setOnItemClickListener: When you tap an item, it will show a Toast with the item's name.​

✅ Step 5: Run the App


1.​ Click the green play button ▶️ at the top​
2.​ Choose an emulator or connect your phone​

3.​ Wait for the app to launch​

Now you’ll see a list of items with icons next to them. When you tap any item, you’ll get a Toast saying "You
clicked: [Item Name]."

====================================================================================
Create an android app to create basic notification with reply.

🟢 Step 1: Create a New Project


1.​ Open Android Studio​

2.​ Click New Project​

3.​ Select Empty Activity​

4.​ Click Next​

Now fill in these details:

●​ Name: NotificationWithReply​

●​ Language: Kotlin​

●​ Minimum SDK: API 21 or higher​

●​ Click Finish​

🟡 Step 2: Modify AndroidManifest.xml


Before we start coding, we need to add a permission for notification access. Open the
AndroidManifest.xml file and add the following permission inside the <manifest> tag:

xml
CopyEdit
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>

This permission is required to post notifications starting from Android 13 (API level 33).

🔵 Step 3: Set Up the Layout


Now, let’s create a button in the main activity to trigger the notification. Open activity_main.xml and add
this code:

xml
CopyEdit
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<!-- Button to trigger notification -->


<Button
android:id="@+id/showNotificationButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Notification"
android:layout_centerInParent="true"/>
</RelativeLayout>

🟠 Step 4: Write the Code for Notification


Now we will write the Kotlin code to create the notification with a reply option.

Open MainActivity.kt and replace the code with this:

kotlin
CopyEdit
package com.example.notificationwithreply

import android.app.*
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.widget.Button
import android.widget.RemoteInput
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat

class MainActivity : AppCompatActivity() {


private val CHANNEL_ID = "my_channel_01"
private val NOTIFICATION_ID = 1

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Create the Notification Channel for devices running Android 8.0 and above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "Notification Channel"
val descriptionText = "Channel for Reply Notification"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
description = descriptionText
}
// Register the channel with the system
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}

// Button to show notification


val showNotificationButton: Button =
findViewById(R.id.showNotificationButton)
showNotificationButton.setOnClickListener {
showNotificationWithReply()
}
}

private fun showNotificationWithReply() {


// Create the reply action
val remoteInput = RemoteInput.Builder(KEY_REPLY)
.setLabel("Reply...") // Text shown in the reply box
.build()

val replyIntent = Intent(this, ReplyReceiver::class.java)


val replyPendingIntent = PendingIntent.getBroadcast(this, 0, replyIntent,
PendingIntent.FLAG_UPDATE_CURRENT)

val replyAction = NotificationCompat.Action.Builder(


R.drawable.ic_reply, // You can add your own icon here
"Reply", replyPendingIntent
).addRemoteInput(remoteInput) // Add the remote input (reply box)
.build()

// Build the notification


val notification = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification) // Add your icon here
.setContentTitle("Message Received")
.setContentText("You have a new message. Tap to reply.")
.addAction(replyAction) // Add the reply action
.setAutoCancel(true)
.build()

// Show the notification


val notificationManager = NotificationManagerCompat.from(this)
notificationManager.notify(NOTIFICATION_ID, notification)
}

companion object {
const val KEY_REPLY = "key_reply"
}
}

🔴 Step 5: Create the BroadcastReceiver for Reply


When the user replies to the notification, we need to catch that reply. To do that, we need to create a
BroadcastReceiver that will handle the reply.

1.​ Create a new Kotlin class called ReplyReceiver.kt:​

○​ Right-click on your java > com.example.notificationwithreply folder.​

○​ Select New > Kotlin Class and name it ReplyReceiver.​

Add this code to the ReplyReceiver.kt:

kotlin
CopyEdit
package com.example.notificationwithreply

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.widget.Toast
import androidx.core.app.RemoteInput

class ReplyReceiver : BroadcastReceiver() {

override fun onReceive(context: Context, intent: Intent) {


val replyText = getMessageText(intent)
// Show a toast with the reply message
Toast.makeText(context, "Reply: $replyText", Toast.LENGTH_SHORT).show()
}
private fun getMessageText(intent: Intent): CharSequence? {
val remoteInput = RemoteInput.getResultsFromIntent(intent)
return remoteInput?.getCharSequence(MainActivity.KEY_REPLY)
}
}

This class will handle the reply and display a Toast message showing what the user typed.

🟣 Step 6: Register the Receiver in AndroidManifest.xml


We need to tell the app about the BroadcastReceiver. Open AndroidManifest.xml and add this inside the
<application> tag:

xml
CopyEdit
<receiver android:name=".ReplyReceiver" android:exported="false" />

🧠 What’s Happening Here?


1.​ Notification with Reply: When the user taps the notification, they can type a reply in the notification
itself.​

2.​ BroadcastReceiver: The ReplyReceiver handles the user's reply when they submit it. It shows a
Toast with the reply message.​

3.​ RemoteInput: This is used to collect the user's reply.​

✅ Step 7: Run the App


1.​ Click the green play button ▶️​
2.​ Choose an emulator or connect your phone​

3.​ Wait for the app to launch​

When you press the "Show Notification" button, a notification will appear. You can reply directly from the
notification, and your reply will show in a Toast.
Create an Android application that demonstrates
the use of a Service to perform a
1) background task
2) forground task.

🟢 Step 1: Create a New Project


1.​ Open Android Studio.​

2.​ Click New Project.​

3.​ Select Empty Activity.​

4.​ Click Next.​

Fill in these details:

●​ Name: ServiceExample​

●​ Language: Kotlin​

●​ Minimum SDK: API 21 or higher.​

●​ Click Finish.​

🟡 Step 2: Add Permissions to AndroidManifest.xml


For both background and foreground services, we need to add permissions to the AndroidManifest.xml.

1.​ Open the AndroidManifest.xml file.​

2.​ Add these lines inside the <application> tag:​

xml
CopyEdit
<service android:name=".BackgroundService" android:enabled="true"
android:exported="false" />
<service android:name=".ForegroundService" android:enabled="true"
android:exported="false" />

🔵 Step 3: Create the Background Service


Now, let’s create the background service that will run a task without showing any UI to the user.
1.​ Create a new Kotlin class called BackgroundService.kt:​

Right-click on java > your.package.name and choose New > Kotlin Class. Name it BackgroundService.

Add this code to the BackgroundService.kt:

kotlin
CopyEdit
package com.example.serviceexample

import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.util.Log
import android.widget.Toast
import androidx.core.app.NotificationCompat

class BackgroundService : Service() {

private val TAG = "BackgroundService"

override fun onCreate() {


super.onCreate()
Log.d(TAG, "Background Service Created")
}

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


// Perform a background task
Thread {
try {
for (i in 1..10) {
Thread.sleep(1000)
Log.d(TAG, "Task in background: $i")
}
stopSelf() // Stop the service once the task is done
} catch (e: InterruptedException) {
e.printStackTrace()
}
}.start()

return START_STICKY
}

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


// Not used in this example
return null
}

override fun onDestroy() {


super.onDestroy()
Log.d(TAG, "Background Service Destroyed")
}
}

🧠 What’s Happening Here?


●​ The BackgroundService performs a background task using a separate thread.​

●​ It runs for 10 seconds, and each second, it logs a message to show that the task is happening in the
background.​

●​ The service stops itself when the task is done (stopSelf()).​

🟠 Step 4: Create the Foreground Service


Now, let’s create the foreground service that will run a task while showing a notification.

1.​ Create a new Kotlin class called ForegroundService.kt:​

Right-click on java > your.package.name and choose New > Kotlin Class. Name it ForegroundService.

Add this code to the ForegroundService.kt:

kotlin
CopyEdit
package com.example.serviceexample

import android.app.*
import android.content.Intent
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat

class ForegroundService : Service() {

private val CHANNEL_ID = "foreground_service_channel"


private val TAG = "ForegroundService"

override fun onCreate() {


super.onCreate()
Log.d(TAG, "Foreground Service Created")

// Create a notification channel (required for Android 8.0 and above)


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(CHANNEL_ID, "Foreground Service",
NotificationManager.IMPORTANCE_DEFAULT)
val manager = getSystemService(NotificationManager::class.java)
manager.createNotificationChannel(channel)
}

// Create a notification to show while the service is running in the


foreground
val notification = NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentText("Running in the foreground")
.setSmallIcon(R.drawable.ic_launcher_foreground) // You can set your own
icon
.build()

// Start the service in the foreground with the notification


startForeground(1, notification)
}

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


// Perform the foreground task
Thread {
try {
for (i in 1..10) {
Thread.sleep(1000)
Log.d(TAG, "Foreground Task: $i")
}
stopSelf() // Stop the service once the task is done
} catch (e: InterruptedException) {
e.printStackTrace()
}
}.start()

return START_STICKY
}

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


// Not used in this example
return null
}

override fun onDestroy() {


super.onDestroy()
Log.d(TAG, "Foreground Service Destroyed")
}
}

🧠 What’s Happening Here?


●​ ForegroundService shows a notification while it runs the task in the foreground.​

●​ We create a notification channel for Android versions 8.0 (Oreo) and above.​

●​ startForeground() is used to run the service in the foreground and show a notification.​

🔴 Step 5: Modify MainActivity.kt to Start the Services


Now, let’s add buttons in MainActivity to start both the background and foreground services.

1.​ Open activity_main.xml and modify it to add two buttons:​

xml
CopyEdit
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<!-- Button to start the background service -->


<Button
android:id="@+id/startBackgroundServiceButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Background Service"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"/>

<!-- Button to start the foreground service -->


<Button
android:id="@+id/startForegroundServiceButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Foreground Service"
android:layout_centerHorizontal="true"
android:layout_below="@id/startBackgroundServiceButton"
android:layout_marginTop="20dp"/>
</RelativeLayout>

2.​ Open MainActivity.kt and modify it to start the services when the buttons are clicked:​

kotlin
CopyEdit
package com.example.serviceexample

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val startBackgroundServiceButton: Button =


findViewById(R.id.startBackgroundServiceButton)
val startForegroundServiceButton: Button =
findViewById(R.id.startForegroundServiceButton)

// Start background service


startBackgroundServiceButton.setOnClickListener {
val backgroundServiceIntent = Intent(this, BackgroundService::class.java)
startService(backgroundServiceIntent)
}

// Start foreground service


startForegroundServiceButton.setOnClickListener {
val foregroundServiceIntent = Intent(this, ForegroundService::class.java)
startService(foregroundServiceIntent)
}
}
}

🧠 What’s Happening Here?


●​ When you click the "Start Background Service" button, the BackgroundService starts in the
background.​

●​ When you click the "Start Foreground Service" button, the ForegroundService starts in the
foreground with a notification.​

✅ Step 6: Run the App


1.​ Click the green play button ▶️ at the top.​
2.​ Choose an emulator or connect your phone.​

3.​ Wait for the app to launch.

====================================================================================
Create an Android application that demonstrates
the use of a Broadcast Receiver to listen for a wifi
status on or off and respond to it.

🛠️ Step-by-Step Guide
🟢 Step 1: Create a New Project
1.​ Open Android Studio.​

2.​ Click New Project.​

3.​ Select Empty Activity.​

4.​ Click Next.​

Fill in these details:

●​ Name: WifiBroadcastReceiverExample​

●​ Language: Kotlin​

●​ Minimum SDK: API 21 or higher.​

●​ Click Finish.​

🟡 Step 2: Add Permissions to AndroidManifest.xml


In order to listen for Wi-Fi status changes, you need to request permissions to access Wi-Fi state.

1.​ Open AndroidManifest.xml.​

2.​ Add the following permissions inside the <manifest> tag:​

xml
CopyEdit
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

These permissions are required to monitor Wi-Fi state changes and manage the Wi-Fi state.
🔵 Step 3: Create the Broadcast Receiver
Now, let’s create the Broadcast Receiver to listen for Wi-Fi status changes.

1.​ Create a new Kotlin class called WifiReceiver.kt:​

○​ Right-click on java > your.package.name and choose New > Kotlin Class. Name it
WifiReceiver.​

Add this code to the WifiReceiver.kt:

kotlin
CopyEdit
package com.example.wifibroadcastreceiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import android.widget.Toast

class WifiReceiver : BroadcastReceiver() {

override fun onReceive(context: Context, intent: Intent) {


// Get the Wi-Fi status from the intent
val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as
WifiManager
val wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
WifiManager.WIFI_STATE_UNKNOWN)

// Check the Wi-Fi status and show a Toast


if (wifiState == WifiManager.WIFI_STATE_ENABLED) {
Toast.makeText(context, "Wi-Fi is ON", Toast.LENGTH_SHORT).show()
} else if (wifiState == WifiManager.WIFI_STATE_DISABLED) {
Toast.makeText(context, "Wi-Fi is OFF", Toast.LENGTH_SHORT).show()
}
}
}

🧠 What’s Happening Here?


●​ The WifiReceiver extends BroadcastReceiver and overrides the onReceive method.​

●​ It listens for Wi-Fi status changes (ON or OFF).​

●​ When the Wi-Fi state changes, it displays a Toast message to show the status ("Wi-Fi is ON" or "Wi-Fi
is OFF").​
🟠 Step 4: Register the Receiver in AndroidManifest.xml
Now, we need to register the Broadcast Receiver in the AndroidManifest.xml so that the app can listen
for Wi-Fi state changes.

1.​ Open AndroidManifest.xml.​

2.​ Add the following <receiver> tag inside the <application> tag:​

xml
CopyEdit
<receiver android:name=".WifiReceiver" android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>

🧠 What’s Happening Here?


●​ The <intent-filter> tells the system to listen for the WIFI_STATE_CHANGED action, which is
broadcast when the Wi-Fi state changes (ON or OFF).​

●​ When this event is triggered, the system calls the onReceive() method of the WifiReceiver class.​

🔴 Step 5: Create the UI in activity_main.xml


We can create a simple UI that will show when Wi-Fi status changes. In this case, we'll show a message
through the Toast, but you can also display this in the app UI if needed.

1.​ Open activity_main.xml.​

2.​ Modify it as follows to add a simple TextView (though it's not strictly necessary for the task, but for
clarity, we will show it):​

xml
CopyEdit
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/statusTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Wi-Fi Status: Unknown"
android:textSize="18sp"
android:layout_centerInParent="true"/>

</RelativeLayout>

We’ll use this TextView to show the Wi-Fi status, but for now, the Toast message is the main output.

🟢 Step 6: Update MainActivity.kt to Respond to Wi-Fi State


While the BroadcastReceiver listens for Wi-Fi state changes, let’s update the UI to display the current Wi-Fi
status.

1.​ Open MainActivity.kt.​

2.​ Modify the code to display a message in the TextView when the Wi-Fi status changes:​

kotlin
CopyEdit
package com.example.wifibroadcastreceiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.wifi.WifiManager
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

private lateinit var statusTextView: TextView


private lateinit var wifiReceiver: WifiReceiver

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Initialize the UI components


statusTextView = findViewById(R.id.statusTextView)

// Initialize the WifiReceiver


wifiReceiver = WifiReceiver()

// Register the receiver to listen for Wi-Fi state changes


val wifiStateChangedFilter = IntentFilter(WifiManager.WIFI_STATE_CHANGED)
registerReceiver(wifiReceiver, wifiStateChangedFilter)
}

override fun onDestroy() {


super.onDestroy()
// Unregister the receiver to avoid memory leaks
unregisterReceiver(wifiReceiver)
}

// This method will be called by the BroadcastReceiver to update the UI


fun updateWifiStatus(status: String) {
statusTextView.text = "Wi-Fi Status: $status"
}
}

🧠 What’s Happening Here?


●​ We initialize a TextView in the MainActivity to show the Wi-Fi status.​

●​ We register the WifiReceiver to listen for Wi-Fi state changes.​

●​ When the Wi-Fi state changes, we call updateWifiStatus to update the UI with the new status.​

🧠 Step 7: Final Adjustments


●​ The WifiReceiver sends a Toast message and updates the TextView in MainActivity with the
current Wi-Fi state.​

●​ The BroadcastReceiver will respond to changes in Wi-Fi status, i.e., whether Wi-Fi is turned ON or
OFF.​

✅ Step 8: Run the App


1.​ Click the green play button ▶️ at the top.​
2.​ Choose an emulator or connect your phone.​

3.​ Wait for the app to launch.


Create an Android application that demonstrates

the use of a RecyclerView to display a


1)list of items
2) text and image

🛠️ Step-by-Step Guide
🟢 Step 1: Create a New Project
1.​ Open Android Studio.​

2.​ Click New Project.​

3.​ Choose Empty Activity.​

4.​ Set the following:​

○​ Name: RecyclerViewDemo​

○​ Language: Kotlin​

○​ Minimum SDK: API 21 or higher.​

5.​ Click Finish.​

🟡 Step 2: Add RecyclerView to Dependencies


In order to use RecyclerView, you need to add the required dependencies to the build.gradle file.

1.​ Open build.gradle (Module: app).​

2.​ Inside the dependencies block, add the following line:​

gradle
CopyEdit
implementation 'androidx.recyclerview:recyclerview:1.2.1'

3.​ Sync the project by clicking Sync Now when prompted.​

🔵 Step 3: Create a Data Model for the List


You need to create a data model to represent each item in the list. For this example, we'll have a title (text)
and image (URL of the image).

1.​ Create a new Kotlin class called Item.kt in your project:​

○​ Right-click on java > your.package.name and choose New > Kotlin Class. Name it Item.​

kotlin
CopyEdit
data class Item(
val title: String,
val imageUrl: String
)

🧠 What’s Happening Here?


●​ The Item class has two properties: title (a String for the text) and imageUrl (a String for the image
URL).​

🟠 Step 4: Create the Layout for Each Item in the List


Now, create the layout for each individual item in the RecyclerView.

1.​ In the res > layout folder, create a new layout file called item_layout.xml.​

2.​ Add the following XML code:​

xml
CopyEdit
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="16dp">

<ImageView
android:id="@+id/itemImage"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_marginEnd="16dp"
android:scaleType="centerCrop" />

<TextView
android:id="@+id/itemTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:gravity="center_vertical" />
</LinearLayout>

🧠 What’s Happening Here?


●​ The layout has a horizontal LinearLayout, where the ImageView (for the image) and the TextView
(for the title) are arranged next to each other.​

●​ We’ll use this layout for each item in the RecyclerView.​

🟢 Step 5: Create the Adapter for RecyclerView


1.​ In your java > your.package.name folder, create a new Kotlin class called ItemAdapter.kt.​

2.​ This adapter will be used to bind data (text and images) to each item in the RecyclerView.​

kotlin
CopyEdit
package com.example.recyclerViewdemo

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide

class ItemAdapter(private val itemList: List<Item>) :


RecyclerView.Adapter<ItemAdapter.ItemViewHolder>() {

// ViewHolder to hold references to the views


inner class ItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val title: TextView = itemView.findViewById(R.id.itemTitle)
val image: ImageView = itemView.findViewById(R.id.itemImage)
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder


{
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_layout,
parent, false)
return ItemViewHolder(view)
}

override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {


val item = itemList[position]
holder.title.text = item.title

// Load image using Glide (you need to add Glide dependency)


Glide.with(holder.image.context)
.load(item.imageUrl)
.into(holder.image)
}

override fun getItemCount(): Int = itemList.size


}

🧠 What’s Happening Here?


●​ ItemAdapter extends RecyclerView.Adapter.​

●​ The ItemViewHolder class holds references to the TextView and ImageView for each item.​

●​ In onBindViewHolder(), the title and image are set for each item using Glide to load images from
URLs.​

🔴 Step 6: Add Glide Dependency for Image Loading


Since we are using Glide to load images, you need to add the Glide dependency.

1.​ Open build.gradle (Module: app).​

2.​ Add the following inside the dependencies block:​

gradle
CopyEdit
implementation 'com.github.bumptech.glide:glide:4.12.0'
kapt 'com.github.bumptech.glide:compiler:4.12.0'

3.​ Click Sync Now to sync the project.​

🟡 Step 7: Update activity_main.xml Layout to Include RecyclerView


Open activity_main.xml and replace its content with the following code to include the RecyclerView:

xml
CopyEdit
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>

🧠 What’s Happening Here?


●​ A RecyclerView is added to display the list of items.​

🔵 Step 8: Set up RecyclerView in MainActivity.kt


1.​ Open MainActivity.kt.​

2.​ Initialize the RecyclerView and set up the ItemAdapter to bind the data.​

kotlin
CopyEdit
package com.example.recyclerViewdemo

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

class MainActivity : AppCompatActivity() {

private lateinit var recyclerView: RecyclerView


private lateinit var itemList: List<Item>

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

recyclerView = findViewById(R.id.recyclerView)

// Initialize the data (a list of items with text and image)


itemList = listOf(
Item("Item 1", "https://example.com/image1.jpg"),
Item("Item 2", "https://example.com/image2.jpg"),
Item("Item 3", "https://example.com/image3.jpg")
)
// Set the layout manager and adapter
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = ItemAdapter(itemList)
}
}

🧠 What’s Happening Here?


●​ A list of Item objects is created.​

●​ The RecyclerView is set with a LinearLayoutManager (to display items in a vertical list).​

●​ The ItemAdapter is used to bind the data to the RecyclerView.​

🟢 Step 9: Run the App


1.​ Click the green play button ▶️ at the top.​
2.​ Choose an emulator or connect your phone.​

3.​ Wait for the app to launch.​

====================================================================================
====================================================================================

Create an Android app development focusing on


the use of a ContentProvider.

🔨 Step-by-Step Guide to Create the App


✅ Step 1: Create New Android Project
1.​ Open Android Studio​

2.​ Click New Project > Empty Activity​

3.​ Name it: ContentProviderDemo​

4.​ Language: Kotlin​

5.​ Click Finish​


✅ Step 2: Create the Layout
In res/layout/activity_main.xml, replace everything with:

xml
CopyEdit
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="24dp">

<EditText
android:id="@+id/nameInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter name" />

<Button
android:id="@+id/insertButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Insert Name" />

<Button
android:id="@+id/readButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Read Names" />

<TextView
android:id="@+id/displayText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Saved names will appear here"
android:paddingTop="16dp" />
</LinearLayout>

✅ Step 3: Create the ContentProvider


Create a new Kotlin file: MyContentProvider.kt

kotlin
CopyEdit
package com.example.contentproviderdemo

import android.content.ContentProvider
import android.content.ContentValues
import android.database.Cursor
import android.net.Uri
import android.util.Log

class MyContentProvider : ContentProvider() {

private val names = mutableListOf<String>()

companion object {
const val AUTHORITY = "com.example.contentproviderdemo.provider"
val CONTENT_URI: Uri = Uri.parse("content://$AUTHORITY/names")
}

override fun insert(uri: Uri, values: ContentValues?): Uri? {


val name = values?.getAsString("name")
if (name != null) {
names.add(name)
Log.d("ContentProvider", "Inserted: $name")
}
return uri
}

override fun query(


uri: Uri,
projection: Array<String>?,
selection: String?,
selectionArgs: Array<String>?,
sortOrder: String?
): Cursor? {
val matrixCursor = android.database.MatrixCursor(arrayOf("name"))
for (name in names) {
matrixCursor.addRow(arrayOf(name))
}
return matrixCursor
}

override fun onCreate(): Boolean = true


override fun getType(uri: Uri): String? = null
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?):
Int = 0
override fun update(uri: Uri, values: ContentValues?, selection: String?,
selectionArgs: Array<String>?): Int = 0
}

✅ Step 4: Add ContentProvider in AndroidManifest.xml


Add this inside the <application> tag:
xml
CopyEdit
<provider
android:name=".MyContentProvider"
android:authorities="com.example.contentproviderdemo.provider"
android:exported="true" />

✅ Step 5: Add Logic in MainActivity.kt


Now open MainActivity.kt and write this code:

kotlin
CopyEdit
package com.example.contentproviderdemo

import android.content.ContentValues
import android.net.Uri
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

private lateinit var nameInput: EditText


private lateinit var insertButton: Button
private lateinit var readButton: Button
private lateinit var displayText: TextView

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

nameInput = findViewById(R.id.nameInput)
insertButton = findViewById(R.id.insertButton)
readButton = findViewById(R.id.readButton)
displayText = findViewById(R.id.displayText)

val uri =
Uri.parse("content://com.example.contentproviderdemo.provider/names")

insertButton.setOnClickListener {
val name = nameInput.text.toString()
val values = ContentValues().apply {
put("name", name)
}
contentResolver.insert(uri, values)
nameInput.setText("")
}

readButton.setOnClickListener {
val cursor = contentResolver.query(uri, null, null, null, null)
val builder = StringBuilder()

cursor?.let {
while (it.moveToNext()) {
val name = it.getString(it.getColumnIndexOrThrow("name"))
builder.append(name).append("\n")
}
it.close()
}

displayText.text = builder.toString()
}
}
}

✅ Step 6: Run the App


1.​ Click ▶️ Run.​
2.​ Enter names and press "Insert".​

3.​ Press "Read" to show names using the ContentProvider.

You might also like