Blank Page
Blank Page
Below are the detailed answers for all 40 questions, ensuring that each one is
thorough enough to earn full marks.
Android is an open-source operating system for mobile devices. Each major version
has a corresponding code name based on a dessert or sweet treat. Below is the list
of major Android versions:
After Android 9 (Pie), Google stopped using dessert names publicly, referring to
them by their version numbers.
The Fibonacci sequence is a series of numbers where each number is the sum of the
two preceding ones.
Kotlin Code:
fun main() {
val n = 10
var first = 0
var second = 1
for (i in 3..n) {
val next = first + second
print("$next ")
first = second
second = next
}
}
Output:
Explanation:
• We initialize the first two Fibonacci numbers: 0 and 1.
• The loop runs from 3 to n (10), computing each Fibonacci number as the
sum of the previous two.
• The result is printed in sequence.
Concept
fun main() {
print("Enter a number: ")
val num = readLine()!!.toInt()
if (num % 2 == 0) {
println("$num is Even")
} else {
println("$num is Odd")
}
}
Example Output:
Enter a number: 7
7 is Odd
Explanation:
1. The program asks the user to enter a number.
2. It checks the remainder when divided by 2 (num % 2).
3. If the remainder is 0, the number is even, else it’s odd.
Definition
Roles of an Activity:
1. User Interface Management: Displays UI elements.
2. Handles User Interactions: Responds to button clicks, input, and gestures.
3. Lifecycle Management: Runs through different states (onCreate(), onStart(),
etc.).
4. Navigation: Moves between screens using Intents.
Lifecycle of an Activity
5. Android OS Architecture
1. Linux Kernel
• Acts as the core of Android.
• Handles process management, memory management, device drivers.
2. Native Libraries
• Includes:
• SQLite (Database management).
• OpenGL (Graphics rendering).
• WebKit (Web rendering engine).
4. Application Framework
• Provides core system services:
• Activity Manager
• Content Providers
• Notification Manager
5. Applications
• User-installed apps run at the top of the architecture.
⸻
6. Kotlin Program to Save and Retrieve Data Using SharedPreferences
Kotlin Code:
// Retrieving
val name = sharedPref.getString("username", "DefaultName")
println("Saved Name: $name")
Explanation:
1. Saving Data: putString() saves "JohnDoe" under the key "username".
2. Retrieving Data: getString() fetches the stored value.
fun main() {
print("Enter your name: ")
val name = readLine()!!
Explanation:
• Uses readLine() to get user input.
• Converts the age to Int.
8. Properties of Notifications
Example:
Got it! I will continue answering all remaining questions in full detail with
explanations, code snippets, and examples.
In Kotlin, primitive data types are the building blocks of variables. Kotlin provides
numeric, character, and boolean data types.
fun main() {
val name: String = "Alice"
val age: Int = 25
val price: Double = 99.99
val isStudent: Boolean = false
println("Name: $name")
println("Age: $age")
println("Price: $price")
println("Is Student? $isStudent")
}
Output
Name: Alice
Age: 25
Price: 99.99
Is Student? false
Definition
• readLine() is a function in Kotlin used to read user input from the console.
fun main() {
print("Enter your name: ")
val name = readLine()!!
Explanation
1. readLine() reads input as a string.
2. !!.toInt() converts the string to an integer.
Example Output
Definition
• Operator Precedence determines the order in which operations are
executed.
• Associativity determines the direction (left to right or right to left) when
operators have the same precedence.
Example Program
fun main() {
val result = 10 + 5 * 2
println("Result: $result") // Output: 20
}
Explanation
• * has a higher precedence than +, so 5 * 2 is calculated first, then added to
10.
fun main() {
// For Loop
for (i in 1..5) {
println("For Loop: $i")
}
// While Loop
var x = 1
while (x <= 5) {
println("While Loop: $x")
x++
}
// Do-While Loop
var y = 1
do {
println("Do-While Loop: $y")
y++
} while (y <= 5)
}
Definition
Output
fun main() {
for (i in 1..10) {
if (i == 5) continue
if (i == 8) break
println(i)
}
}
Output
1
2
3
4
6
7
fun main() {
val number: Int = 10
val price: Double = 99.99
val isAvailable: Boolean = true
println("Number: $number")
println("Price: $price")
println("Available: $isAvailable")
}
Output
Number: 10
Price: 99.99
Available: true
Definition
A Service runs in the background to perform tasks like music playback, data syncing,
or fetching location.
Types of Services
Type Description
Foreground Service Runs with a notification (e.g., music player).
Background Service Runs without UI (e.g., fetching data).
Continuing with detailed answers from Question 22 onwards with explanations and
Kotlin examples.
22. What is a Content Provider in Android? When Would You Use One?
Definition
A Content Provider allows apps to share data with other apps in a structured way. It
manages access to a database, file system, or web services.
<provider
android:name=".MyContentProvider"
android:authorities="com.example.provider"
android:exported="true"/>
fun main() {
print("Enter first number: ")
val num1 = readLine()!!.toDouble()
24. Code to Create a Simple Widget that Displays the Current Time
<TextView
android:id="@+id/widget_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Time"
android:textSize="20sp"/>
<receiver android:name=".TimeWidget">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider"
android:resource="@xml/widget_info" />
</receiver>
notificationManager.notify(1, notification)
}
26. Activity Layout with Buttons That Change Color When Clicked
<Button
android:id="@+id/buttonRed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Red" />
⸻
buttonRed.setOnClickListener {
buttonRed.setBackgroundColor(Color.RED)
}
// Saving Data
val editor = sharedPreferences.edit()
editor.putString("username", "Alice")
editor.apply()
// Retrieving Data
val username = sharedPreferences.getString("username", "Default")
println("Username: $username")
⸻
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Got it! I’ll provide detailed answers for each question starting from Question 30, with
thorough explanations, examples, and best practices.
30. What is the Notification API in Android? Describe its Purpose and Key
Components.
Definition
Component Description
NotificationManager System service that manages notifications.
NotificationCompat.Builder Used to create and customize notifications.
NotificationChannel Required for Android 8.0+ to categorize notifications.
PendingIntent Allows user interaction with the notification.
BigTextStyle, InboxStyle Allows expanded, detailed notifications.
// Get NotificationManager
val notificationManager =
context.getSystemService(NotificationManager::class.java)
// Create Notification
val notification = NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("New Notification")
.setContentText("This is a sample notification")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.build()
// Show Notification
notificationManager.notify(1, notification)
}
⸻
31. Explain the Role of the Notification Builder in Creating Notifications in Android.
Definition
32. Describe What Widgets Are in Android and Their Purpose on the Home Screen.
Definition
Widgets are mini applications that run directly on the home screen, allowing users to
view information without opening the app.
⸻
Purpose of Widgets
• Quick access to information (e.g., weather, calendar).
• Increases user engagement.
• Supports user interaction (e.g., music control, task lists).
<TextView
android:id="@+id/widget_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Time"
android:textSize="18sp"/>
<receiver android:name=".ClockWidget">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
</intent-filter>
<meta-data android:name="android.appwidget.provider"
android:resource="@xml/widget_info"/>
</receiver>
Explanation:
• The Intent explicitly specifies SecondActivity, meaning it will launch only
that activity.
34. Kotlin Code for a Broadcast Receiver that Listens for Battery Low Events
Register in AndroidManifest.xml
<receiver android:name=".BatteryLowReceiver">
<intent-filter>
<action android:name="android.intent.action.BATTERY_LOW"/>
</intent-filter>
</receiver>
35. How Can Actions Be Attached to Notifications? Why Are They Important?
Got it! I’ll provide detailed answers with theoretical explanations and Kotlin code
examples for Question 36 onward, ensuring each answer is comprehensive and well-
structured.
Introduction
Android provides the Telephony API that allows applications to send SMS messages
programmatically. This is useful for applications that need to automate notifications,
OTP (One-Time Passwords), or user communication via SMS.
<uses-permission android:name="android.permission.SEND_SMS"/>
import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.telephony.SmsManager
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
sendButton.setOnClickListener {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED) {
sendSMS(phoneNumber.text.toString(), message.text.toString())
} else {
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.SEND_SMS), 1)
}
}
}
Introduction
In Android, the Google Maps API allows developers to display maps, mark locations,
and enhance user navigation. Markers are icons that represent locations on the map.
dependencies {
implementation 'com.google.android.gms:play-services-maps:18.0.0'
}
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="YOUR_GOOGLE_MAPS_API_KEY"/>
import android.os.Bundle
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import androidx.appcompat.app.AppCompatActivity
Expected Output
When the app runs, Google Maps will show San Francisco with a custom marker
icon.
Additional Features
• Use default
markers: .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE
_BLUE))
• Add click listeners to markers for interactivity.
38. Implement Runtime Permission Requests for Location Services Required for
Google Maps Functionality
Introduction
Android restricts access to sensitive information like location data for security
reasons. Apps must request permissions at runtime (starting from Android 6.0, API
level 23).
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION"/>
import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
LOCATION_PERMISSION_REQUEST_CODE)
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions:
Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
if (grantResults.isNotEmpty() && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
// Permission granted, proceed with location access
} else {
// Permission denied, show a message
}
}
}
}
Expected Output
• If the user grants permission, location services work.
• If the user denies permission, the app cannot access location data.
Best Practices
• Always explain why location access is needed using a dialog.
• If denied, allow the user to enable it from App Settings.
39. Create a GridView Layout in Kotlin That Displays Images from Drawable
Resources and Handles Item Selection
Introduction
A GridView is used to display items (such as images) in a grid layout. It’s commonly
used for photo galleries, e-commerce apps, and file browsers.
⸻
<GridView
android:id="@+id/gridView"
android:numColumns="3"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.os.Bundle
import android.widget.GridView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
Expected Output
A grid of images from the drawable folder, with a message when an image is clicked.
40. Compare Java and Kotlin for Android Development. What Are the Advantages of
Using Kotlin Over Java?
Introduction
Both Java and Kotlin are used for Android development, but Kotlin is the preferred
language since it is more modern, concise, and safer.
• Same in Kotlin:
fun main() {
println("Hello, Kotlin!")
}
2. Null Safety
• Java allows null, leading to crashes.
• Kotlin prevents null values by default.
• Example:
GlobalScope.launch {
delay(1000L)
println("Coroutine Running")
}
Conclusion