0% found this document useful (0 votes)
5 views66 pages

Android Programming

The document provides a comprehensive guide on creating an Android application with various components such as buttons, broadcast receivers, and services. It includes XML layouts, Kotlin code for activities and services, and instructions for setting up resources like colors, dimensions, and themes. Additionally, it covers how to connect a phone to Android Studio for debugging and testing purposes.

Uploaded by

ashish16905
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)
5 views66 pages

Android Programming

The document provides a comprehensive guide on creating an Android application with various components such as buttons, broadcast receivers, and services. It includes XML layouts, Kotlin code for activities and services, and instructions for setting up resources like colors, dimensions, and themes. Additionally, it covers how to connect a phone to Android Studio for debugging and testing purposes.

Uploaded by

ashish16905
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

Adding button in android

Xml

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


<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />

</[Link]>
[Link]

package [Link]

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

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
[Link](savedInstanceState)
enableEdgeToEdge()

setContentView([Link].activity_main)

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


[Link] {
[Link](this, "button clicked", Toast.LENGTH_SHORT).show()
}

[Link](findViewById([Link])) { v, insets ->


val systemBars = [Link]([Link]())
[Link]([Link], [Link], [Link], [Link])
insets
}
}
}
0 a2 ) how to connect your phone using USB cable to android studio

Step 1: Enable Developer Options on Your Phone

Open Settings on your Android phone

Go to About phone

Find Build number

Tap Build number 7 times

Step 2: Enable USB Debugging

Go back to Settings

Open Developer options

Turn ON USB debugging

Tap OK when prompted

Step 3: Connect Phone to PC Using USB Cable

Connect your phone to your computer using a USB cable

On your phone, select:

File Transfer (MTP) or USB for file transfer

A popup will appear-> Allow USB debugging? ->Tap Allow

Step 4: Verify Device in Android Studio

Open Android Studio

Open your project

Click Device Manager (top-right)

Your phone should appear under Physical Devices

OR

Use terminal in Android Studio:

adb devices

You should see your device listed.


Practical 0 a 3

A BroadcastReceiver is an Android component that listens for system-wide or app-specific


broadcast events, such as:

 Battery low

 Airplane mode changed

 Network connectivity change

 SMS received

 Custom app events

First we’ve to create

[Link] file

package [Link] //broadcastreceiver is the name of my package it


would be different for you guys

import [Link] //import


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

class MainActivity : AppCompatActivity() {

//first line
private lateinit var airplaneModeReceiver: BroadcastReceiver

override fun onCreate(savedInstanceState: Bundle?) {


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

[Link](findViewById([Link])) { v, insets ->


val systemBars = [Link]([Link]())
[Link]([Link], [Link], [Link], [Link])
insets
}

// Broadcast Receiver second line


airplaneModeReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val isAirplaneModeOn =
intent?.getBooleanExtra("state", false) ?: false

if (isAirplaneModeOn) {
[Link](context, "Airplane Mode Enabled", Toast.LENGTH_SHORT).show()

} else {
[Link](context, "Airplane Mode Disabled", Toast.LENGTH_SHORT).show()
}
}
}

override fun onStart() {


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

override fun onStop() {


[Link]()
unregisterReceiver(airplaneModeReceiver)
}
}
Step 2 we’ve to create Class file with Kotlin extension

Click on package – app – src -main-java -your package name would be visible right click on that new
Kotlin class file name AirplaneModeReceiver

Now you’ll have a class called as [Link]

[Link]

package [Link]

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

class AirplaneModeReceiver : BroadcastReceiver() {

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


val isAirplaneModeOn =
intent?.getBooleanExtra("state", false) ?: false

if (isAirplaneModeOn) {
[Link](context, "Airplane Mode Enabled", Toast.LENGTH_SHORT).show()
} else {
[Link](context, "Airplane Mode Disabled", Toast.LENGTH_SHORT).show()
}
}
}
step 3 open the [Link]

Click on package – app – src -main below res you will see the [Link] file

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


<manifest xmlns:android="[Link]
xmlns:tools="[Link]

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/[Link]">

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

<receiver
android:name=".AirplaneModeReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="[Link].AIRPLANE_MODE_CHANGED" />
</intent-filter>
</receiver>

</application>

</manifest>
Output
Practical 0 a 4

Use of services in android

A Service in Android is a component that runs in the background, without a user interface.

 Unlike an Activity, the user doesn’t see it on the screen.

 It’s useful for tasks that need to keep running even if the app is minimized, like:

Playing music, Downloading files, Syncing data

Step 1

Download an music.mp3 file

And add it in the below location

App – src – main – res – now right click on res – new – android resource directory - in resource type
choose raw – click on ok

No you’ll see the raw folder added in res


Now copy the music.mp3 and paste in the raw

Step 2 Create [Link] file

Here ive aman.mp3 which is my music file

App – src – main – java – you’ll see your package name, right click on the package – new Kotlin class
and name it [Link]

[Link]

package [Link]

import [Link].*
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]

class MusicService : Service() {

private var mediaPlayer: MediaPlayer? = null


private val CHANNEL_ID = "MusicChannel"

override fun onCreate() {


[Link]()
createNotificationChannel()
mediaPlayer = [Link](this, [Link])
}

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


val notification = [Link](this, CHANNEL_ID)
.setContentTitle("Music Player")
.setContentText("Music is playing")
.setSmallIcon([Link].ic_media_play)
.build()

startForeground(1, notification)
mediaPlayer?.start()

return START_STICKY
}

override fun onDestroy() {


mediaPlayer?.stop()
mediaPlayer?.release()
mediaPlayer = null
[Link]()
}

override fun onBind(intent: Intent?): IBinder? = null

private fun createNotificationChannel() {


if ([Link].SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
CHANNEL_ID,
"Music Channel",
NotificationManager.IMPORTANCE_LOW
)
val manager = getSystemService(NotificationManager::[Link])
[Link](channel)
}
}
}

step 3 [Link] adding two buttons

<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">

<Button
android:id="@+id/btnPlay"
android:text="Play Music"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/btnStop"
android:text="Stop Music"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>

Step 4 [Link]

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


<manifest xmlns:android="[Link]
xmlns:tools="[Link]

<!-- REQUIRED FOR MUSIC FOREGROUND SERVICE -->


<uses-permission android:name="[Link].FOREGROUND_SERVICE" />
<uses-permission android:name="[Link].FOREGROUND_SERVICE_MEDIA_PLAYBACK"
/>

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/[Link]">

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

<service
android:name=".MusicService"
android:exported="false"
android:foregroundServiceType="mediaPlayback"
tools:targetApi="29" />

</application>
</manifest>

Step 5 [Link]

package [Link]

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

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


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

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


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

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

if ([Link].SDK_INT >= Build.VERSION_CODES.O) {


startForegroundService(intent)
} else {
startService(intent)
}
}

[Link] {
stopService(Intent(this, MusicService::[Link]))
}
}
}
As you run the song by playing PLAY MUSIC make sure the Emulator Volume is full
Practical 1

Write a code to explain drawable resources in android studio,

add color, dimension, Strings, themes, images

Step 1

myapplication – app – src- main – res – values

Right click on values – new – value/resource file

[Link]

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


<resources>
<color name="primaryColor">#6200EE</color>
<color name="secondaryColor">#03DAC5</color>
<color name="whiteColor">#FFFFFF</color>
<color name="red">#393D6E</color>
</resources>

[Link]

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


<resources>
<dimen name="text_size_large">24sp</dimen>
<dimen name="text_size_medium">18sp</dimen>
<dimen name="padding_small">8dp</dimen>
</resources>
[Link]

<resources>
<string name="app_name">ResourceDemo</string>
<string name="welcome_message">Welcome to Android Resources Demo!</string>
<string name="button_text">Click Me</string>
</resources>

[Link]

<resources xmlns:tools="[Link]
<style name="[Link]" parent="[Link]">

<item name="colorPrimary">@color/primaryColor</item>
<item name="colorSecondary">@color/secondaryColor</item>
<item name="android:textColor">@color/whiteColor</item>

</style>
</resources>

Step 2

Change then shape of the button

myapplication – app – src- main – res- drawable – right click on drawable – new drawable resource
file

This popup will appear

File name = as per your choice (I have taken rounded_button.xml)

Root element = shape


rounded_button.xml

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


<shape xmlns:android="[Link]
android:shape="rectangle">

<solid android:color="@color/primaryColor"/>
<corners android:radius="16dp"/>
<padding
android:left="12dp"
android:top="8dp"
android:right="12dp"
android:bottom="8dp"/>
</shape>

Step 3

How to add a image in the activity

Download any jpg image and past it in the drawable

Here it is [Link]

Step 4

[Link]

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


<manifest xmlns:android="[Link]
xmlns:tools="[Link]

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/[Link]">

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

</application>

</manifest>

Step 5

Activity_main.xml

<LinearLayout xmlns:android="[Link]
android:orientation="vertical"
android:padding="@dimen/padding_small"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/tvWelcome"
android:text="@string/welcome_message"
android:textColor="@color/primaryColor"
android:textSize="@dimen/text_size_large"
android:layout_marginBottom="16dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

<Button
android:id="@+id/btnClick"
android:text="@string/button_text"
android:background="@drawable/rounded_button"
android:textColor="@color/whiteColor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

<ImageView
android:id="@+id/imgDemo"
android:src="@drawable/aman"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginTop="16dp"/>
</LinearLayout>

Step 6

[Link]

package [Link]

import [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 tvWelcome = findViewById<TextView>([Link])


val secondaryColor = [Link](this, [Link])
[Link](secondaryColor)

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


[Link] {
[Link] = getString([Link].button_text)
}

val imgDemo = findViewById<ImageView>([Link])


[Link]([Link])

val padding = [Link]([Link].padding_small).toInt()


[Link](padding, padding, padding, padding)
}
}
Practical 2: Activity Life cycle

Step 1

Open [Link]

package [Link]

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

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


[Link](savedInstanceState)
setContentView([Link].activity_main)
Log.d("Lifecycle", "onCreate")
}
override fun onStart() {
[Link]()
Log.d("Lifecycle", "onStart")
}
override fun onResume() {
[Link]()
Log.d("Lifecycle", "onResume")
}
override fun onPause() {
[Link]()
Log.d("Lifecycle", "onPause")
}
override fun onStop() {
[Link]()
Log.d("Lifecycle", "onStop")
}
override fun onRestart() {
[Link]()
Log.d("Lifecycle", "onRestart")
}
override fun onDestroy() {
[Link]()
Log.d("Lifecycle", "onDestroy")
}
}
Step 2

now to check the output you’ve to click on logcat which is available at the bottom left of the screen

See here it is written

Step 3

Now where package:mine is written there you’ve to write tag:Lifecycle

Step 4 now you’ve to run the app


When you Close the app you’ll see the below logs
Practical 3 Explain the Types of layout

Step 1 how to create a layout

Myapplication- src- main – res – layout – right click – new – layout resource file – name of the layout
– ok

A layout will be created, now depending upon the topic you’ve to create the layout, here I’ve
created a demo layout, which is [Link]

1)constraintlayout

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


<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/tvHello"
android:text="Hello Android"
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:id="@+id/btnClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="196dp"
android:text="Click Me"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/tvHello" />
</[Link]>
2) FrameLayout

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


<FrameLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
android:src="@android:color/darker_gray"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

<TextView
android:text="Splash Screen"
android:textSize="24sp"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</FrameLayout>

3) GridLayout

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


<GridLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:columnCount="2"
android:padding="16dp">

<Button android:text="One"/>
<Button android:text="Two"/>
<Button android:text="Three"/>
<Button android:text="Four"/>
</GridLayout>

4) LinearLayout

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


<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<TextView
android:text="Login"
android:textSize="24sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

<EditText
android:hint="Username"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

<EditText
android:hint="Password"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

<Button
android:text="Submit"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>

5) RelativeLayout

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


<RelativeLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/tvTitle"
android:text="Welcome"
android:textSize="22sp"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

<Button
android:text="Continue"
android:layout_below="@id/tvTitle"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
6) ScrollView

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


<ScrollView xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 1" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 2" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 3" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 4" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 5" />
</LinearLayout>

</ScrollView>

7) TableLayout

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


<TableLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp">
<TableRow>
<TextView android:text="Name"/>

<EditText
android:layout_width="163dp"
android:hint="Enter name" />
</TableRow>

<TableRow>
<TextView android:text="Age"/>
<EditText android:hint="Enter age"/>
</TableRow>
</TableLayout>

Step 2

package [Link]

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

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
[Link](savedInstanceState)
enableEdgeToEdge()
setContentView([Link]) //here you've to write the namme of the layout you're
using syntax:[Link]

}
}
Output Constraint layout

Output Framelayout
Output : GridLayout

Output : Linearlayout
Output : relativelayout

Output : Scrollview
Output : Tablelayout
Practical 4

Explain all the UI components in Android

Step 1

Activity_main.xml

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


<ScrollView xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">

<TextView
android:id="@+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="User Registration"
android:textSize="22sp"
android:textStyle="bold"
android:layout_marginBottom="12dp" />

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

<EditText
android:id="@+id/etEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Email"
android:inputType="textEmailAddress" />

<RadioGroup
android:id="@+id/rgGender"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/rbMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male" />

<RadioButton
android:id="@+id/rbFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female" />
</RadioGroup>

<CheckBox
android:id="@+id/cbJava"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Java" />

<CheckBox
android:id="@+id/cbKotlin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Kotlin" />

<Spinner
android:id="@+id/spCity"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<Switch
android:id="@+id/swNotify"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enable Notifications" />

<SeekBar
android:id="@+id/sbAge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100" />

<RatingBar
android:id="@+id/rbRating"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numStars="5"
android:stepSize="1.0" />

<Button
android:id="@+id/btnSubmit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Submit" />

</LinearLayout>
</ScrollView>

Step 2

Main [Link]

package [Link]

import [Link]
import [Link].*

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

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


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

// Link XML components


val etName = findViewById<EditText>([Link])
val etEmail = findViewById<EditText>([Link])
val rgGender = findViewById<RadioGroup>([Link])
val cbJava = findViewById<CheckBox>([Link])
val cbKotlin = findViewById<CheckBox>([Link])
val spinner = findViewById<Spinner>([Link])
val swNotify = findViewById<Switch>([Link])
val sbAge = findViewById<SeekBar>([Link])
val rbRating = findViewById<RatingBar>([Link])
val btnSubmit = findViewById<Button>([Link])

val cities = arrayOf("Mumbai", "Pune", "Delhi", "Bangalore")


val adapter = ArrayAdapter(this,[Link].simple_spinner_dropdown_item, cities)
[Link] = adapter

[Link] {

val name = [Link]()


val email = [Link]()

val genderId = [Link]


val gender = if (genderId != -1) {
findViewById<RadioButton>(genderId).[Link]()
} else {
"Not Selected"
}

val skills = mutableListOf<String>()


if ([Link]) [Link]("Java")
if ([Link]) [Link]("Kotlin")

val city = [Link]()


val notification =
if ([Link]) "Enabled" else "Disabled"
val age = [Link]
val rating = [Link]

[Link](
this,
"Name: $name\nEmail: $email\nGender: $gender\nSkills: $skills\nCity: $city\nAge:
$age\nRating: $rating\nNotifications: $notification",
Toast.LENGTH_LONG
).show()
}
}
}
Output
Practical 5

App bar and Dialog box

Step 1

Go to res – right click – new android resource directoy –

This pop up will open make sure to type menu in both of the pop up

Click okay your menu directory will be created

Step 2

Now fight click on menu – new resource file – type – [Link]

Step 3

[Link]

<menu xmlns:android="[Link]
<item
android:id="@+id/menu_delete"
android:title="Delete"/>

<item
android:id="@+id/menu_about"
android:title="About"/>
</menu>
Step 4

Activity_main.xml

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


<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<[Link]
android:id="@+id/toolbar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:title="Menu Example"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />

</[Link]>

Step 5 Main [Link]

package [Link]

import [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)
setSupportActionBar(findViewById([Link]))
}

override fun onCreateOptionsMenu(menu: Menu?): Boolean {


[Link]([Link], menu)
return true
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {


when ([Link]) {

[Link].menu_delete -> {
showDeleteDialog()
}

[Link].menu_about -> {
[Link](this, "Menu & Dialog Example", Toast.LENGTH_SHORT).show()
}
}
return true
}

private fun showDeleteDialog() {


[Link](this)
.setTitle("Delete")
.setMessage("Are you sure you want to delete?")
.setPositiveButton("Yes") { _, _ ->
[Link](this, "Deleted", Toast.LENGTH_SHORT).show()
}
.setNegativeButton("No", null)
.show()
}
}
Output
Practical 6 Intent, Event and event Listener

Step 1

App – src -main -[Link] – right click – new – activity- empty-view activity

Main [Link]

package [Link]

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

import [Link]

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


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

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


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

Activity_main.xml

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


<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="22sp"
android:text="First Activity1" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next" />

</LinearLayout>

[Link]

package [Link]

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

class SecondActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


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

val button = findViewById<Button>([Link].button2)

[Link] {
//finish()
val intent = Intent(this, MainActivity::[Link])
startActivity(intent)

}
}
}

Activity_second.xml

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


<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Second Activity"
android:textSize="22sp" />

<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Previous Activity" />

</LinearLayout>
Practical 0 a 3

A BroadcastReceiver is an Android component that listens for system-wide or app-specific


broadcast events, such as:

 Battery low

 Airplane mode changed

 Network connectivity change

 SMS received

 Custom app events

First we’ve to create

[Link] file

package [Link] //broadcastreceiver is the name of my package it


would be different for you guys

import [Link] //import


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

class MainActivity : AppCompatActivity() {

//first line
private lateinit var airplaneModeReceiver: BroadcastReceiver

override fun onCreate(savedInstanceState: Bundle?) {


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

[Link](findViewById([Link])) { v, insets ->


val systemBars = [Link]([Link]())
[Link]([Link], [Link], [Link], [Link])
insets
}

// Broadcast Receiver second line


airplaneModeReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val isAirplaneModeOn =
intent?.getBooleanExtra("state", false) ?: false

if (isAirplaneModeOn) {
[Link](context, "Airplane Mode Enabled", Toast.LENGTH_SHORT).show()

} else {
[Link](context, "Airplane Mode Disabled", Toast.LENGTH_SHORT).show()
}
}
}

override fun onStart() {


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

override fun onStop() {


[Link]()
unregisterReceiver(airplaneModeReceiver)
}
}
Step 2 we’ve to create Class file with Kotlin extension

Click on package – app – src -main-java -your package name would be visible right click on that new
Kotlin class file name AirplaneModeReceiver

Now you’ll have a class called as [Link]

[Link]

package [Link]

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

class AirplaneModeReceiver : BroadcastReceiver() {

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


val isAirplaneModeOn =
intent?.getBooleanExtra("state", false) ?: false

if (isAirplaneModeOn) {
[Link](context, "Airplane Mode Enabled", Toast.LENGTH_SHORT).show()
} else {
[Link](context, "Airplane Mode Disabled", Toast.LENGTH_SHORT).show()
}
}
}
step 3 open the [Link]

Click on package – app – src -main below res you will see the [Link] file

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


<manifest xmlns:android="[Link]
xmlns:tools="[Link]

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/[Link]">

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

<receiver
android:name=".AirplaneModeReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="[Link].AIRPLANE_MODE_CHANGED" />
</intent-filter>
</receiver>

</application>

</manifest>
Output
Practical 0 a 4

Use of services in android

A Service in Android is a component that runs in the background, without a user interface.

 Unlike an Activity, the user doesn’t see it on the screen.

 It’s useful for tasks that need to keep running even if the app is minimized, like:

Playing music, Downloading files, Syncing data

Step 1

Download an music.mp3 file

And add it in the below location

App – src – main – res – now right click on res – new – android resource directory - in resource type
choose raw – click on ok

No you’ll see the raw folder added in res


Now copy the music.mp3 and paste in the raw

Step 2 Create [Link] file

Here ive aman.mp3 which is my music file

App – src – main – java – you’ll see your package name, right click on the package – new Kotlin class
and name it [Link]

[Link]

package [Link]

import [Link].*
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]

class MusicService : Service() {

private var mediaPlayer: MediaPlayer? = null


private val CHANNEL_ID = "MusicChannel"

override fun onCreate() {


[Link]()
createNotificationChannel()
mediaPlayer = [Link](this, [Link])
}

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


val notification = [Link](this, CHANNEL_ID)
.setContentTitle("Music Player")
.setContentText("Music is playing")
.setSmallIcon([Link].ic_media_play)
.build()

startForeground(1, notification)
mediaPlayer?.start()

return START_STICKY
}

override fun onDestroy() {


mediaPlayer?.stop()
mediaPlayer?.release()
mediaPlayer = null
[Link]()
}

override fun onBind(intent: Intent?): IBinder? = null

private fun createNotificationChannel() {


if ([Link].SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
CHANNEL_ID,
"Music Channel",
NotificationManager.IMPORTANCE_LOW
)
val manager = getSystemService(NotificationManager::[Link])
[Link](channel)
}
}
}

step 3 [Link] adding two buttons

<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">

<Button
android:id="@+id/btnPlay"
android:text="Play Music"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/btnStop"
android:text="Stop Music"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>

Step 4 [Link]

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


<manifest xmlns:android="[Link]
xmlns:tools="[Link]

<!-- REQUIRED FOR MUSIC FOREGROUND SERVICE -->


<uses-permission android:name="[Link].FOREGROUND_SERVICE" />
<uses-permission android:name="[Link].FOREGROUND_SERVICE_MEDIA_PLAYBACK"
/>

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/[Link]">

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

<service
android:name=".MusicService"
android:exported="false"
android:foregroundServiceType="mediaPlayback"
tools:targetApi="29" />

</application>
</manifest>

Step 5 [Link]

package [Link]

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

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


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

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


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

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

if ([Link].SDK_INT >= Build.VERSION_CODES.O) {


startForegroundService(intent)
} else {
startService(intent)
}
}

[Link] {
stopService(Intent(this, MusicService::[Link]))
}
}
}
As you run the song by playing PLAY MUSIC make sure the Emulator Volume is full
Practical 8: Database Programing with Sqlite using Kotlin

[Link]

package [Link]

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

class DatabaseHelper(context: Context) :


SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {

companion object {
private const val DATABASE_NAME = "StudentDB"
private const val DATABASE_VERSION = 1
private const val TABLE_NAME = "Student"
private const val COL_ID = "id"
private const val COL_NAME = "name"
private const val COL_MARKS = "marks"
}

override fun onCreate(db: SQLiteDatabase?) {


val createTable = ("CREATE TABLE $TABLE_NAME (" +
"$COL_ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"$COL_NAME TEXT, " +
"$COL_MARKS INTEGER)")
db?.execSQL(createTable)
}

override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {


db?.execSQL("DROP TABLE IF EXISTS $TABLE_NAME")
onCreate(db)
}

fun insertData(name: String, marks: Int): Boolean {


val db = [Link]
val contentValues = ContentValues()
[Link](COL_NAME, name)
[Link](COL_MARKS, marks)

val result = [Link](TABLE_NAME, null, contentValues)


return result != -1L
}
fun getAllData() = [Link]("SELECT * FROM $TABLE_NAME", null)
}

activity_main.xml

<LinearLayout
xmlns:android="[Link]
android:orientation="vertical"
android:padding="16dp"
android:layout_width="match_parent"
android:layout_height="match_parent">

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

<EditText
android:id="@+id/etMarks"
android:hint="Enter Marks"
android:inputType="number"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

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

<Button
android:id="@+id/btnView"
android:text="View Data"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

</LinearLayout>
[Link]

package [Link]

import [Link]
import [Link].*
import [Link]

class MainActivity : AppCompatActivity() {

lateinit var db: DatabaseHelper


lateinit var etName: EditText
lateinit var etMarks: EditText
lateinit var btnInsert: Button
lateinit var btnView: Button

override fun onCreate(savedInstanceState: Bundle?) {


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

db = DatabaseHelper(this)

etName = findViewById([Link])
etMarks = findViewById([Link])
btnInsert = findViewById([Link])
btnView = findViewById([Link])

[Link] {
val name = [Link]()
val marks = [Link]().toIntOrNull()

if ([Link]() && marks != null) {


val isInserted = [Link](name, marks)
if (isInserted)
[Link](this, "Data Inserted", Toast.LENGTH_SHORT).show()
else
[Link](this, "Error", Toast.LENGTH_SHORT).show()
} else {
[Link](this, "Enter valid data", Toast.LENGTH_SHORT).show()
}
}

[Link] {
val cursor = [Link]()

if ([Link] == 0) {
[Link](this, "No Data Found", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}

val buffer = StringBuilder()


while ([Link]()) {
[Link]("ID: ${[Link](0)}\n")
[Link]("Name: ${[Link](1)}\n")
[Link]("Marks: ${[Link](2)}\n\n")
}

val builder = [Link](this)


[Link]("Student Data")
[Link]([Link]())
[Link]("OK", null)
[Link]()
}
}
}
Practical 9 Thread

activity_main.xml

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


<LinearLayout
xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Press Start"
android:textSize="22sp"
android:padding="20dp"/>

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

[Link]

package [Link]

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

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


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

val t = findViewById<TextView>([Link])
val b = findViewById<Button>([Link])

[Link] {
val thread = Thread {
for (i in 1..5) {
[Link](1000)
runOnUiThread {
[Link] = "Count: $i"
}
}
}
[Link]()
}
}
}
Practical 10

Wap in android to demonstrate the use of telephone api

[Link]

<manifest xmlns:android="[Link]

xmlns:tools="[Link]

<uses-permission android:name="[Link].CALL_PHONE"/>

<uses-feature android:name="[Link]" android:required="false"/>

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:supportsRtl="true"

android:theme="@style/[Link]">

<activity

android:name=".MainActivity"

android:exported="true">

<intent-filter>

<action android:name="[Link]"/>

<category android:name="[Link]"/>

</intent-filter>

</activity>

</application>

</manifest>
Activity_main.xml

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

<LinearLayout

xmlns:android="[Link]

android:layout_width="match_parent"

android:layout_height="match_parent"

android:gravity="center"

android:orientation="vertical">

<Button

android:id="@+id/callButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Direct Call"/>

</LinearLayout>

[Link]

package [Link]

import [Link]

import [Link]

import [Link]

import [Link]

import [Link]

import [Link]

import [Link]

class MainActivity : AppCompatActivity() {

private val requestPermissionLauncher =

registerForActivityResult([Link]()) { isGranted ->


if (isGranted) {

callNumber()

override fun onCreate(savedInstanceState: Bundle?) {

[Link](savedInstanceState)

setContentView([Link].activity_main)

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

[Link] {

[Link]([Link].CALL_PHONE)

private fun callNumber() {

val intent = Intent(Intent.ACTION_CALL)

[Link] = [Link]("[Link]

startActivity(intent)

You might also like