0% found this document useful (0 votes)
7 views

Android

The document provides an overview of Kotlin programming language and its features, including variable declaration, operators, control flow statements, and looping constructs. It explains the syntax and usage of functions, classes, and objects in Kotlin, as well as the Android architecture framework and app creation steps. Additionally, it covers the activity lifecycle and content providers in Android development.

Uploaded by

mishraayush1205
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Android

The document provides an overview of Kotlin programming language and its features, including variable declaration, operators, control flow statements, and looping constructs. It explains the syntax and usage of functions, classes, and objects in Kotlin, as well as the Android architecture framework and app creation steps. Additionally, it covers the activity lifecycle and content providers in Android development.

Uploaded by

mishraayush1205
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 40

Android

Unit-1
1) What is Kotlin ? explain kotlin variable with suitable
example
2) Write short note on Kotlin operators
3) What is control flow statement explain anyone in Kotlin
4) What is looping statement explain for loop with suitable
example
5) What is kotlin function how to pass the perimeter and
calling function with coding slipted
6) What is function ? explain type of arguments
7) Write short note on classes and object in Kotlin
8) Define lambla expression with code example in Kotlin
9) State and explain Android architecture framework with
suitable diagram
10) Explain the step of create Android app in Kotlin using
Android studio
11) Write a short note on activity life cycle
12) What is Indent ? explain type of indent class in kotlin
13) Write short note on contain provider and Android
notification
1)What is Kotlin ? explain kotlin variable with suitable example
What is Kotlin?
Kotlin is a modern programming language created by JetBrains,
in 2011 the same company behind the popular IntelliJ IDEA. It
runs on the Java Virtual Machine (JVM) and can also be
compiled to JavaScript or native code. Kotlin is an object-
oriented language, and a “better language” than Java, but still
be fully interoperable with Java code. Kotlin is sponsored by
Google, announced as one of the official languages for Android
Development in 2017.
Kotlin Variables
In Kotlin, every variable should be declared before it’s used.
Without declaring a variable, an attempt to use the variable
gives a syntax error. Declaration of the variable type also
decides the kind of data you are allowed to store in the memory
location. In case of local variables, the type of variable can be
inferred from the initialized value.
var rollno = 55
var name = "Praveen"
println(rollno)
println(name)
In Kotlin, variables are declared using two types –
1. Immutable using val keyword
2. Mutable using var keyword
Immutable Variables –
Immutable is also called read-only variables. Hence, we can
not change the value of the variable declared
using val keyword.
val myName = "Gaurav"
myName = "Praveen"
Mutable Variables –
In Mutable variable we can change the value of the variable.
var myAge = 25
myAge = 26
println("My new Age is ${myAge}")
Output:
My new Age is 26
2) Write short note on Kotlin operators
Operators are the special symbols that perform different
operation on operands. For example + and – are operators that
perform addition and subtraction respectively. Like Java, Kotlin
contains different kinds of operators.
 Arithmetic operator
 Relation operator
 Assignment operator
 Unary operator
 Logical operator
 Bitwise operator

Arithmetic Operators –

Operat Expressi Translate


ors Meaning on to

+ Addition a+b a.plus(b)

a.minus(b
– Subtraction a–b
)

Multiplicati
* a*b a.times(b)
on
Operat Expressi Translate
ors Meaning on to

/ Division a/b a.div(b)

% Modulus a%b a.rem(b)

 Kotlin

fun main(args: Array<String>)


{
var a = 20 var b = 4 println("a + b = " + (a + b))
println("a - b = " + (a - b))
println("a * b = " + (a.times(b)))
println("a / b = " + (a / b))
println("a % b = " + (a.rem(b)))
}

Output:
a + b = 24
a - b = 16
a * b = 80
a/b=5
a%b=0

Relational Operators –

Operat Expressi
ors Meaning on Translate to

> greater than a>b a.compareTo(b) > 0


Operat Expressi
ors Meaning on Translate to

< less than a<b a.compareTo(b) < 0

greater than or
>= a >= b a.compareTo(b) >= 0
equal to

less than or
<= a <= b a.compareTo(b) <= 0
equal to

a?.equals(b) ?: (b
== is equal to a == b
=== null)

!(a?.equals(b) ?: (b
!= not equal to a != b
=== null)) > 0

 Kotlin

fun main(args: Array<String>)


{
var c = 30
var d = 40
println("c > d = "+(c>d))
println("c < d = "+(c.compareTo(d) < 0))
println("c >= d = "+(c>=d))
println("c <= d = "+(c.compareTo(d) <= 0))
println("c == d = "+(c==d))
println("c != d = "+(!(c?.equals(d) ?: (d === null))))
}

Output:
c > d = false
c < d = true
c >= d = false
c <= d = true
c == d = false
c != d = true
Assignment Operators –

Operat Expressi
ors on Translate to

a.plusAssign(b) >
+= a=a+b
0

a.minusAssign(b)
-= a=a–b
<0

a.timesAssign(b)
*= a=a*b
>= 0

a.divAssign(b)
/= a=a/b
<= 0

%= a=a%b a.remAssign(b)

 Kotlin
fun main(args : Array<String>){
var a = 10
var b = 5
a+=b
println(a)
a-=b
println(a)
a*=b
println(a)
a/=b
println(a)
a%=b
println(a)

Output:
15
10
50
10
0
Unary Operators –

Operat Expressi Translate


ors on to

++ ++a or a.inc()
Operat Expressi Translate
ors on to

a++

— –a or a– a.dec()

 Kotlin

fun main(args : Array<String>){


var e=10
var flag = true
println("First print then increment: "+ e++)
println("First increment then print: "+ ++e)
println("First print then decrement: "+ e--)
println("First decrement then print: "+ --e)
}

Output:
First print then increment: 10
First increment then print: 12
First print then decrement: 12
First decrement then print: 10
Logical Operators –

Operat Expressio
ors Meaning n

return true if all expressions (a>b) &&


&&
are true (a>c)
Operat Expressio
ors Meaning n

return true if any of expression (a>b) ||


||
is true (a>c)

return complement of the


! a.not()
expression

 Kotlin

fun main(args : Array<String>){


var x = 100
var y = 25
var z = 10
var result = false
if(x > y && x > z)
println(x)
if(x < y || x > z)
println(y)
if( result.not())
println("Logical operators")
}

Output:
100
25
Logical operators
Bitwise Operators –
Operat Expressi
ors Meaning on

Shl signed shift left a.shl(b)

signed shift
Shr a.shr(b)
right

unsigned shift
Ushr a.ushr()
right

And bitwise and a.and(b)

Or bitwise or a.or()

Xor bitwise xor a.xor()

Inv bitwise inverse a.inv()

 Kotlin

fun main(args: Array<String>)


{
println("5 signed shift left by 1 bit: " + 5.shl(1))
println("10 signed shift right by 2 bits: : " + 10.shr(2))
println("12 unsigned shift right by 2 bits: " + 12.ushr(2))
println("36 bitwise and 22: " + 36.and(22))
println("36 bitwise or 22: " + 36.or(22))
println("36 bitwise xor 22: " + 36.xor(22))
println("14 bitwise inverse is: " + 14.inv())
}

Output:
5 signed shift left by 1 bit: 10
10 signed shift right by 2 bits: : 2
12 unsigned shift right by 2 bits: 3
36 bitwise and 22: 4
36 bitwise or 22: 54
14itwise xor 22: 50
14itwise inverse is: -15
3) What is control flow statement explain anyone in Kotlin
Kotlin if-else expression
In programming too, a certain block of code needs to be
executed when some condition is fulfilled. A programming
language uses control statements to control the flow of
execution of a program based on certain conditions. If the
condition is true then it enters into the conditional block and
executes the instructions.
There are different types of if-else expressions in Kotlin:
 if expression
 if-else expression
 if-else-if ladder expression
 nested if expression
if statement:
It is used to specify whether a block of statements will be
executed or not, i.e. if a condition is true, then only the
statement or block of statements will be executed otherwise it
fails to execute.
Syntax:
if(condition) {
// code to run if condition is true
}
Flowchart:

Example:
 Java

fun main(args: Array<String>) {


var a = 3
if(a > 0){
print("Yes,number is positive")
}
}

Output:
Yes, number is positive
if-else statement:
if-else statement contains two blocks of statements. ‘if’
statement is used to execute the block of code when the
condition becomes true and ‘else’ statement is used to execute
a block of code when the condition becomes false.
Syntax:
if(condition) {
// code to run if condition is true
}
else {
// code to run if condition is false
}
Flowchart:

Here is the Kotlin program to find the larger value of two


numbers.
Example:
 Java

fun main(args: Array<String>) {


var a = 5
var b = 10
if(a > b){
print("Number 5 is larger than 10")
}
else{
println("Number 10 is larger than 5")
}
}

Output:
Number 10 is larger than 5
4) What is looping statement explain for loop with suitable
example
Looping Statements in Kotlin
Looping statements in Kotlin allow you to repeatedly execute a
block of code as long as a certain condition is met or for a
predefined number of iterations. Loops help in automating
repetitive tasks, saving you from writing the same code
multiple times. Kotlin provides several types of looping
constructs:
1. for loop
2. while loop
3. do...while loop

1. for Loop
The for loop is the most commonly used loop in Kotlin,
especially when working with ranges, arrays, lists, or other
collections. It simplifies iteration by allowing you to directly
specify the range or collection to iterate over.
Syntax:
kotlin
Copy
for (item in collection) {
// Code block to execute for each item
}
 item: Represents each element or value in the collection
or range during each iteration.
 collection: The range, list, or other collection over which
you want to loop.
Example:
kotlin
Copy
fun main() {
for (i in 1..5) {
println(i)
}
}
Output:
Copy
1
2
3
4
5
2. while Loop
The while loop in Kotlin repeatedly executes a block of code
while a given condition is true. The condition is evaluated
before each iteration, so if the condition is false initially, the
loop won't execute at all.
Syntax:
kotlin
Copy
while (condition) {
// Code block to execute while the condition is true
}
 condition: The condition that is checked before each loop
iteration. If it's true, the loop will continue; if false, the
loop will stop.
Example:
kotlin
Copy
fun main() {
var i = 1
while (i <= 5) {
println(i)
i++ // Increment to avoid infinite loop
}
}
Output:
Copy
1
2
3
4
5
3. do...while Loop
The do...while loop is similar to the while loop, but the key
difference is that it checks the condition after executing the
block of code. This guarantees that the code will execute at
least once, regardless of whether the condition is initially true
or false.
Syntax:
kotlin
Copy
do {
// Code block to execute
} while (condition)
 The loop executes the block at least once, then checks the
condition to decide whether to continue looping.
Example:
kotlin
Copy
fun main() {
var i = 1
do {
println(i)
i++ // Increment
} while (i <= 5)
}
Output:
Copy
1
2
3
4
5
4) What is looping statement explain for loop with suitable
example
In Kotlin, a looping statement allows you to repeatedly execute
a block of code as long as a specified condition is true or for a
specific number of iterations. There are several types of looping
statements in Kotlin:
1. for loop: Used to iterate over a range, array, or collection.
It has a concise syntax.
o Syntax:
o for (item in collection) {
o // code to execute
o }
o Example:
o for (i in 1..5) {
o println(i)
o }
o // Output: 1, 2, 3, 4, 5
2. while loop: Repeats the code block as long as the
specified condition is true.
o Syntax:
o while (condition) {
o // code to execute
o }
o Example:
o var x = 0
o while (x < 5) {
o println(x)
o x++
o }
o // Output: 0, 1, 2, 3, 4
3. do-while loop: Similar to the while loop, but the condition
is checked after the code block is executed, ensuring the
block is executed at least once.
o Syntax:
o do {
o // code to execute
o } while (condition)
o Example:
o var y = 0
o do {
o println(y)
o y++
o } while (y < 5)
o // Output: 0, 1, 2, 3, 4
5) What is kotlin function how to pass the perimeter and
calling function with coding slipted

What is Functions?
A function is a unit of code that performs a special task. In
programming, the function is used to break the code into smaller
modules which makes the program more manageable.
We can call sum(x, y) at any number of times and it will return
the sum of two numbers. So, the function avoids the repetition of
code and makes the code more reusable.
Note: There is a space between closing bracket ‘)’ and
opening ‘{‘ .

Example of a Function
For example: If we have to compute the sum of two numbers
then define a fun sum().
fun sum(a: Int, b: Int): Int {
Int c = a + b
return c
}
Steps for Passing Parameters and Calling Functions in
Kotlin:
1. Define the Function: Create a function that accepts
parameters.
2. Call the Function: When calling the function, pass the
values (arguments) for those parameters.
3. Use Parameters: Inside the function, you can access and
use the parameters as needed.
Example: Passing Parameters and Calling Functions in
Kotlin
1. Create a Function with Parameters
Let's say you want to create a function that calculates the area
of a rectangle. The function will take the length and width as
parameters.
fun calculateArea(length: Double, width: Double): Double {
return length * width
}
Here:
 length and width are parameters of the calculateArea
function.
 The function returns the area of the rectangle, which is
calculated by multiplying length and width.
2. Calling the Function
Now, you can create another function (for example, a main
function) where you will call calculateArea and pass the
required values.
fun main() {
val length = 5.0
val width = 3.0

// Call the calculateArea function and pass length and width


val area = calculateArea(length, width)

// Output the result


println("The area of the rectangle is: $area")
}
Here:
 The main function initializes length and width values.
 It calls calculateArea(length, width) and stores the result in
the area variable.
 The println function prints the calculated area to the
console.
3. Complete Example
// Function to calculate the area of a rectangle
fun calculateArea(length: Double, width: Double): Double {
return length * width
}
// Main function to call calculateArea and display the result
fun main() {
val length = 5.0
val width = 3.0
// Call the function and pass the parameters
val area = calculateArea(length, width)
// Print the result
println("The area of the rectangle is: $area")
}
Output: The area of the rectangle is: 15.0

6) What is function ? explain type of arguments

What is Functions?
A function is a unit of code that performs a special task. In
programming, the function is used to break the code into smaller
modules which makes the program more manageable.We can
call sum(x, y) at any number of times and it will return the sum
of two numbers. So, the function avoids the repetition of code
and makes the code more reusable.

Note: There is a space between closing bracket ‘)’ and


opening ‘{‘ .
Example of a Function
For example: If we have to compute the sum of two numbers
then define a fun sum().
fun sum(a: Int, b: Int): Int {
Int c = a + b
return c
}
Kotlin Default Argument
In Kotlin, you can provide default values to parameters in
function definition.
If the function is called with arguments passed, those
arguments are used as parameters. However, if the function is
called without passing argument(s), default arguments are
used.
Case I: All arguments passed

The function foo() takes two arguments. The arguments are


provided with default values. However, foo() is called by
passing both arguments in the above program. Hence, the
default arguments are not used.
The value of letter and number will be 'x' and 2 respectively
inside the foo() function.
Case II: All arguments are not passed
Here, only one (first) argument is passed to the foo() function.
Hence, the first argument uses the value passed to the
function. However, second argument number will take the
default value since the second argument is not passed during
function call.
The value of letter and number will be 'y' and 15 respectively
inside the foo() function.
Case III: No argument is passed

Here, the foo() function is called without passing any argument.


Hence, both arguments uses its default values.
The value of letter and number will be 'a' and 15 respectively
inside the foo() function.
7) Write short note on classes and object in Kotlin
Class
Like Java, class is a blueprint for objects having similar
properties. We need to define a class before creating an object
and the class keyword is used to define a class. The class
declaration consists of the class name, class header, and class
body enclosed with curly braces.
Syntax of the class declaration:
class className { // class header
// property
// member function
}
 Class name: every class has a specific name
 Class header: header consists of parameters and
constructors of a class
 Class body: surrounded by curly braces, contains
member functions and other property
Both the header and the class body are optional; if there is
nothing in between curly braces then the class body can be
omitted.
class emptyClass
If we want to provide a constructor, we need to write a
keyword constructor just after the class name.
Creating constructor:
class className constructor(parameters) {
// property
// member function }
Object
It is a basic unit of Object-Oriented Programming and
represents the real-life entities, which have states and
behavior. Objects are used to access the properties and
member functions of a class. In Kotlin, we can create multiple
objects of a class. An object consists of:
 State: It is represented by the attributes of an object. It
also reflects the properties of an object.
 Behavior: It is represented by the methods of an object. It
also reflects the response of an object to other objects.
 Identity: It gives a unique name to an object and enables
one object to interact with other objects.
Create an object
We can create an object using the reference of the class.
var obj = className()
Accessing the property of the class:
We can access the properties of a class using an object. First,
create an object using the class reference and then access the
property.
obj.nameOfProperty
Accessing the member function of the class:
We can access the member function of the class using the
object. obj.funtionName(parameters)
8) Define lambla expression with code example in Kotlin
Lambdas Expressions
Lambdas expression and Anonymous function both are function
literals means these functions are not declared but passed
immediately as an expression.
Lambda Expression –
As we know, the syntax of Kotlin lambdas is similar to Java
Lambdas. A function without a name is called an anonymous
function. For lambda expression, we can say that it is an
anonymous function.
Example:
fun main(args: Array<String>) {
val company = { println("GeeksforGeeks")}

// invoking function method1


company()

// invoking function method2


company.invoke()
}
Output:
GeeksforGeeks
GeeksforGeeks

Syntax of Lambda expression –


val lambda_name : Data_type = { argument_List ->
code_body }

A lambda expression is always surrounded by curly braces,


argument declarations go inside curly braces and have optional
type annotations, the code_body goes after an arrow -> sign. If
the inferred return type of the lambda is not Unit, then the last
expression inside the lambda body is treated as return value.
Example:
val sum = {a: Int , b: Int -> a + b}

In Kotlin, the lambda expression contains optional part except


code_body. Below is the lambda expression after eliminating
the optional part.
val sum:(Int,Int) -> Int = { a, b -> a + b}
Kotlin program of using lambda expression-
// with type annotation in lambda expression
val sum1 = { a: Int, b: Int -> a + b }

// without type annotation in lambda expression


val sum2:(Int,Int)-> Int = { a , b -> a + b}

fun main(args: Array<String>) {


val result1 = sum1(2,3)
val result2 = sum2(3,4)
println("The sum of two numbers is: $result1")
println("The sum of two numbers is: $result2")

// directly print the return value of lambda


// without storing in a variable.
println(sum1(5,7))
}
Output:
The sum of two numbers is: 5
The sum of two numbers is: 7
12

9)State and explain Android architecture framework with


suitable diagram
Android Architecture
Android architecture contains a different number of
components to support any Android device’s needs. Android
software contains an open-source Linux Kernel having a
collection of a number of C/C++ libraries which are exposed
through application framework services.
Components of Android Architecture
The main components of Android architecture are the
following:-
 Applications
 Application Framework
 Android Runtime
 Platform Libraries
 Linux Kernel
1. Applications
Applications is the top layer of android architecture. The pre-
installed applications like home, contacts, camera, gallery etc
and third party applications downloaded from the play store like
chat applications, games etc. will be installed on this layer only.
It runs within the Android run time with the help of the classes
and services provided by the application framework.

2. Application framework
Application Framework provides several important classes
which are used to create an Android application. It provides a
generic abstraction for hardware access and also helps in
managing the user interface with application resources It
includes different types of services activity manager,
notification manager, view system, package manager etc.
3. Application runtime
Android Runtime environment is one of the most important part
of Android. It contains components like core libraries and the
Dalvik virtual machine(DVM). Mainly, it provides the base for
the application framework and powers our application with the
help of the core libraries. It depends on the layer Linux kernel
for threading and low-level memory management.

4. Platform libraries
 Media library provides support to play and record an
audio and video formats.
 Surface manager responsible for managing access to
the display subsystem.
 SGL and OpenGL both cross-language, cross-platform
application program interface (API) are used for 2D and 3D
computer graphics.
5. Linux Kernel
Linux Kernel is heart of the android architecture. It manages all
the available drivers such as display drivers, camera drivers,
Bluetooth drivers, audio drivers, memory drivers, etc. which are
required during the runtime. It is responsible for management
of memory, power, devices etc. The features of Linux kernel
are:
 Security: The Linux kernel handles the security between
the application and the system.
 Memory Management: It efficiently handles the memory
management thereby providing the freedom to develop
our apps.

10) Explain the step of create Android app in Kotlin using


Android studio
Android Application in Kotlin
We can build an Android application using Kotlin and Java. In
the Android Studio Kotlin Tutorial, we are using Kotlin language
to build the application. we learned how to create a project for
Kotlin language but here, we will learn how to run an
application using the AVD (Android Virtual Device).
Creating a Project in Android Studio
Using Step-by-Step Implementation for Creating Projects in
Android Studio with Kotlin:
Step 1: Select the Layout for your Kotlin Application:

Step 2: Here we write name of our application and select the


language Kotlin for the project. Then, click on
the Finish button to launch the project.
Step 3: Check on the Created Project.
We obtained two files when we launched the project, which
are:
 MainActivity.kt – This is a Kotlin file and is used to code
in Kotlin language.
 activity_main.xml – This is an xml file and is used for the
layout of our main activity.
MainActivity.kt File
There are an enormous number of activities in the Android
application. For each activity, we require a separate Kotlin file
to write the code. All the functionalities are added
like onclick, onCreate, etc.
11) Write a short note on activity life cycle
Activity Lifecycle in Kotlin (Android)
In Android, an Activity represents a single screen with a user
interface. It is a crucial component of an Android app.
Understanding the Activity Lifecycle is essential for managing
the activity's behavior during different stages of its existence,
such as when it is created, started, paused, resumed, or
destroyed.
The Activity Lifecycle consists of several states, and Android
provides lifecycle methods that correspond to these states.
These methods allow you to perform tasks such as initializing
resources, saving data, releasing resources, or handling the
user interface.
Activity Lifecycle Stages and Methods
1. onCreate()
o Called when the activity is first created.
o This is where you perform one-time initialization
tasks like setting up the user interface
(setContentView()), initializing variables, and binding
data.
Example:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Initialization code here
}
2. onStart()
o Called when the activity becomes visible to the
user.
o This is called after onCreate() or when the activity is
restarted after being paused or stopped.
o At this point, the activity is about to start interacting
with the user.
Example:
override fun onStart() {
super.onStart()
// Called when the activity becomes visible
}
3. onResume()
o Called when the activity starts interacting with
the user.
o This is the last method called before the activity
gains focus and starts accepting input.
o You can resume animations or refresh UI elements
here.
Example:
override fun onResume() {
super.onResume()
// Resume any paused actions (animations, sensors, etc.)
}
4. onPause()
o Called when the activity is no longer in the
foreground but is still visible.
o This is the method where you should release
resources like sensors, save data, or stop animations.
The activity is still visible but not interacting with the
user.
Example:
override fun onPause() {
super.onPause()
// Pause or release resources (e.g., sensors, audio, etc.)
}
5. onStop()
o Called when the activity is no longer visible.
o If the activity is not going to be needed for a while,
you should release resources or save data that needs
to persist. For example, stop background threads or
save user progress.
Example:
override fun onStop() {
super.onStop()
// Release resources that are no longer needed
}
6. onRestart()
o Called after the activity has been stopped and
is about to start again.
o This is called when the activity is brought back to the
foreground after being stopped.
Example:
override fun onRestart() {
super.onRestart()
// Reinitialize things that were released in onStop
}
7. onDestroy()
o Called before the activity is destroyed.
o This is where you clean up resources like closing files,
releasing memory, or canceling ongoing operations
that could continue running if the activity is
destroyed.
Example:
override fun onDestroy() {
super.onDestroy()
// Clean up resources, close connections, etc.
}
12) What is Indent ? explain type of indent class in kotlin
In Kotlin, Indent generally refers to the concept of indenting or
formatting the code to make it more readable. Indentation is
the practice of adding spaces or tabs before the lines of code to
visually represent the structure of the program, such as blocks
of code within functions, classes, loops, or conditionals.
However, if you're specifically referring to an Indent class, you
may be asking about a class related to code formatting or a
utility for handling indentation in Kotlin
What is Indentation in Kotlin?
Indentation refers to the practice of adding spaces (or tabs)
before the actual code to define code structure, particularly for
nested blocks or scopes. Proper indentation is essential for the
clarity and readability of code, even though Kotlin itself does
not require specific indentation for the code to compile and run
(unlike Python, which uses indentation to define scope).
Indentation Types (Based on IDE Tools or Libraries)
In some cases, tools for Kotlin code formatting may have
specific classes or objects to help with indenting, such as:
1. Spaces or Tabs: You can use spaces or tabs to indent
your code. By default, Kotlin (and many IDEs) uses 4
spaces for each indentation level.
2. Indent Class for Code Formatting:
o While Kotlin itself doesn't have a Indent class in the
standard library, some code formatting libraries
or Kotlin compiler tools (like ktlint or Detekt) might
implement or interact with the indentation in a way
that it could be useful in writing custom formatting
solutions.
Example of Indentation in Code:
fun main() {
val outerVariable = 10
// First level of indentation
if (outerVariable > 5) {
val innerVariable = 5

// Second level of indentation


if (innerVariable > 2) {
println("This is deeply nested.")
}
}
}
13) Write short note on contain provider and Android
notification
Content Provider and Android Notifications
In Android, Content Providers and Notifications are two
important components, each serving distinct purposes in an
app, but they can interact in various ways to enhance user
experience. Let’s break down each concept individually, then
explain how they might work together.
1. Content Provider in Android
A Content Provider is an application component that
manages access to a structured set of data. It serves as an
interface between the data and other applications. The data
can come from various sources such as databases, files, or
other applications. Content Providers help to share data
securely across different apps.
CRUD Operations: They support Create, Read, Update, and
Delete operations on the data, typically via the ContentResolver
class.
URI-based Access: Data is accessed through a uniform
resource identifier (URI), which acts as a path for accessing
content.
Example of a Content Provider:
For example, Android’s Contacts Content Provider allows
apps to access contacts stored in the device’s contacts
database:
val cursor =
contentResolver.query(ContactsContract.Contacts.CONTENT_UR
I, null, null, null, null)
This query retrieves contacts stored on the device, making it
accessible to apps with the appropriate permissions.

2. Android Notifications
Notifications in Android are messages or alerts that pop up
outside of an app's normal UI to inform the user of important
events, updates, or actions they need to take. Notifications are
displayed in the status bar and can include different types of
information, such as text, images, or actions.
 User Alerts: Notifications are used to alert users about
new events, messages, or updates in an app.
 Customizable: You can customize notifications with
different styles (e.g., big text, images, buttons).
Example of Creating a Simple Notification:
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as
NotificationManager
val notification = NotificationCompat.Builder(this, "channelId")
.setContentTitle("New Message")
.setContentText("You have received a new message!")
.setSmallIcon(R.drawable.ic_message)
.build()

notificationManager.notify(1, notification)
This creates a basic notification to alert the user of a new
message.
3. Content Provider and Notifications Interaction
Content Providers and Notifications can work together in
scenarios where an app needs to notify the user about some
updates related to the content managed by the Content
Provider. Here’s how they might interact:
Example Scenario: New Message Notification
 Content Provider: Your app could have a content
provider to manage a database of messages, e.g.,
MessagesProvider.
 Notification: When a new message is inserted into the
MessagesProvider (via the ContentProvider), your app can
send a notification to the user indicating that there is a
new message.

You might also like