Mobile Application Development
Mobile Application Development
Notification
combined Page 1
Notification
val notification = NotificationCompat.Builder(this, "channel_id")
.setContentTitle("Title")
.setContentText("Message")
.setSmallIcon(R.drawable.ic_notification)
.build()
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.notify(1, notification)
Progress Bar
progressBar.visibility = View.VISIBLE // Show
progressBar.visibility = View.GONE // Hide
combined Page 2
}
}
n roi anifest.xml ( the secon ac vity)
xml
CopyEdit
<activity android:name=".SecondActivity" />
ac vity main.xml
xml
CopyEdit
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to Next Screen"/>
ac vity secon .xml
xml
CopyEdit
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to Second Screen"/>
combined Page 3
Trick: Use onCreateOptionsMenu (to show menu) and onOptionsItemSelected (to handle click).
ain c vity. t
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.option1 -> Toast.makeText(this, "Option 1 clicked", Toast.LENGTH_SHORT).show()
}
return super.onOptionsItemSelected(item)
}
men main.xml (Insi e res men fol er)
<menu xmlns:android="<http://schemas.android.com/apk/res/android>">
<item android:id="@+id/option1"
android:title="Option 1"/>
</menu>
combined Page 5
Syntax Breakdown:
kotlin
CopyEdit
val button = findViewById<Button>(R.id.button) // Find Button
button.setOnClickListener { // Set Click
val intent = Intent(this, SecondActivity::class.java) // Create Intent
startActivity(intent) // Start Activity
}
✅ Memory Trick → "Find → Click → Intent → Start (FCIS)"
combined Page 6
}
✅ Memory Trick → "Create → Load → Show" (C-L-S)
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 100)
return
}
combined Page 8
ces MODE_PRIVATE)
Geolocation getSystemService(Context.LOCATION_SE System Service → Get Last Location
RVICE)
combined Page 9
26 February 2025 21:23
Android Notifications
Introduction
A notification is a message that can be displayed to the user of our application. Notifications help users stay informed about updates, alerts, or
events happening in the background of an application.
Types of Notifications
1. Toast Notification
2. Status Notification
3. Dialog Notification
1. Toast Notification
A Toast notification is a message that appears on the screen and fades away after a few seconds. It does not require user interaction and is best
suited for displaying short messages.
Context
Context is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources, classes,
and application-level operations such as launching activities, broadcasting intents, etc.
getApplicationContext()
This method returns the context for the entire application (the process in which all activities are running).
Creating a Toast Notification
val toast = Toast.makeText(context, "Hello, World!", Toast.LENGTH_SHORT)
toast.setGravity(Gravity.CENTER, 0, 0) // Optional: Positioning the toast
toast.show()
2. Dialog Notifications
Dialogs are small windows that prompt the user to make a decision or enter additional information. They do not fill the entire screen and are
used for important user interactions.
Types of Dialogs
1. AlertDialog
2. ProgressDialog
3. DatePickerDialog / TimePickerDialog
AlertDialog
An AlertDialog is a pop-up window that displays a message and buttons for user interaction.
Creating an AlertDialog
val builder = AlertDialog.Builder(this)
val positiveButtonClick = { dialog: DialogInterface, which: Int ->
Toast.makeText(applicationContext, "Yes", Toast.LENGTH_SHORT).show()
}
val negativeButtonClick = { dialog: DialogInterface, which: Int ->
Toast.makeText(applicationContext, "No", Toast.LENGTH_SHORT).show()
}
builder.setTitle("Confirmation")
.setMessage("Are you sure?")
.setPositiveButton("Yes", positiveButtonClick)
.setNegativeButton("No", negativeButtonClick)
.setCancelable(true)
.show()
ProgressDialog
A progress bar is used to indicate the progress of a background task, such as downloading or uploading.
Creating a Progress Bar
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:progress="0"
android:max="100"
style="@android:style/Widget.DeviceDefault.Light.ProgressBar.Horizontal" />
lateinit var progressBar: ProgressBar
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
progressBar = findViewById(R.id.progressBar)
incrementProgress()
}
theory Page 10
}
private fun incrementProgress() {
Thread {
for (i in 1..100) {
Thread.sleep(50) // Simulate work
runOnUiThread {
progressBar.progress = i
}
}
}.start()
}
DatePickerDialog & TimePickerDialog
These dialogs allow users to select a date or time.
Creating a DatePickerDialog
val calendar = Calendar.getInstance()
val year = calendar.get(Calendar.YEAR)
val month = calendar.get(Calendar.MONTH)
val day = calendar.get(Calendar.DAY_OF_MONTH)
val datePickerDialog = DatePickerDialog(this, { _, selectedYear, selectedMonth, selectedDay ->
val formattedDate = "$selectedDay/${selectedMonth + 1}/$selectedYear"
selectedDateTextView.text = formattedDate
}, year, month, day)
datePickerDialog.show()
Creating a TimePickerDialog
val calendar = Calendar.getInstance()
val hour = calendar.get(Calendar.HOUR_OF_DAY)
val minute = calendar.get(Calendar.MINUTE)
val timePickerDialog = TimePickerDialog(this, { _, selectedHour, selectedMinute ->
val formattedTime = String.format("%02d:%02d", selectedHour, selectedMinute)
selectedTimeTextView.text = formattedTime
}, hour, minute, true)
timePickerDialog.show()
3. Status Notification
A status notification displays rich information from a background service and appears in the status bar.
Adding Permission
Add the following permission in AndroidManifest.xml:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
Creating a Notification Channel
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "Example Channel"
val descriptionText = "This is a sample notification channel"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel("example_channel_id", name, importance).apply {
description = descriptionText
}
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}
Sending a Notification
private fun sendNotification() {
val intent = Intent(this, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
val builder = NotificationCompat.Builder(this, "example_channel_id")
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("Hello, User!")
.setContentText("This is a sample notification.")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
with(NotificationManagerCompat.from(this)) {
if (ActivityCompat.checkSelfPermission(
applicationContext,
Manifest.permission.POST_NOTIFICATIONS
) != PackageManager.PERMISSION_GRANTED) {
return
theory Page 11
return
}
notify(1, builder.build())
}
}
Android Menus
Menus are a common user interface component in many types of applications. They provide options for a list of actions that a user can take.
Types of Menus in Android
1. Options Menu
2. Context Menu
3. Popup Menu
Option Menu
The options menu is the primary collection of menu items for an activity. It is where actions such as "Search," "Settings," and "Logout" are
typically placed.
Steps to Create an Options Menu
1. Create a Menu Resource Directory
○ Navigate to res → e → And oid Reso ce Di ecto y → elect men as t e eso ce type.
2. Create a Menu XML File
○ Right-click on res/menu → e → Men Reso ce File → ame it men .xml.
3. Add Items in the XML File
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/action_share"
android:title="@string/action_share"
app:showAsAction="never" />
</menu>
Handling Menu Actions in Kotlin (MainActivity.kt)
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_share -> {
Toast.makeText(this, "Share Selected", Toast.LENGTH_SHORT).show()
}
R.id.action_settings -> {
Toast.makeText(this, "Settings Selected", Toast.LENGTH_SHORT).show()
}
}
return super.onOptionsItemSelected(item)
}
Popup Menu
A Popup Menu appears below the anchor text if space is available; otherwise, it appears above the anchor text. It disappears if you click outside
the menu.
Steps to Create a Popup Menu
1. Create a Menu Resource File (popup_menu.xml)
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/java" android:title="Java" />
<item android:id="@+id/kotlin" android:title="Kotlin" />
<item android:id="@+id/android" android:title="Android" />
</menu>
1. Create a Button in activity_main.xml
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Popup Menu" />
1. Implement the Popup Menu in MainActivity.kt
val button = findViewById<Button>(R.id.button)
button.setOnClickListener {
val popupMenu = PopupMenu(this, button)
popupMenu.menuInflater.inflate(R.menu.popup_menu, popupMenu.menu)
popupMenu.setOnMenuItemClickListener { item ->
when (item.itemId) {
R.id.java -> Toast.makeText(this, "Java Selected", Toast.LENGTH_SHORT).show()
R.id.kotlin -> Toast.makeText(this, "Kotlin Selected", Toast.LENGTH_SHORT).show()
}
true
}
theory Page 12
}
popupMenu.show()
}
Context Menu
A Context Menu is a floating list of menu items that appears when a user long-presses a view. It provides contextual actions related to the
selected item.
Steps to Create a Context Menu
1. Register the View for Context Menu
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
registerForContextMenu(findViewById(R.id.textView))
}
1. Define the Context Menu in onCreateContextMenu
override fun onCreateContextMenu(menu: ContextMenu, v: View, menuInfo: ContextMenu.ContextMenuInfo?) {
super.onCreateContextMenu(menu, v, menuInfo)
menu.setHeaderTitle("Choose an Option")
menu.add(0, v.id, 0, "Copy")
menu.add(0, v.id, 0, "Delete")
}
1. Handle Context Menu Selection
override fun onContextItemSelected(item: MenuItem): Boolean {
return when (item.title) {
"Copy" -> {
Toast.makeText(this, "Copied", Toast.LENGTH_SHORT).show()
true
}
"Delete" -> {
Toast.makeText(this, "Deleted", Toast.LENGTH_SHORT).show()
true
}
else -> super.onContextItemSelected(item)
}
}
Summary of Menus in Android
Menu Type Description
Options Menu Global menu for the activity, placed in the app bar.
Popup Menu Temporary menu appearing next to an anchor view.
Context Menu Menu that appears on long-press for contextual actions.
This document provides a detailed explanation of Android menus, their types, and how to implement them. Let me know if you need any
modifications or additional explanations!
From <https://chatgpt.com/c/67bef026-5964-800a-99d5-9be4cef8b588>
1. Android Layouts
Android layouts define how UI components (views and widgets) are arranged in an activity or fragment.
1.1 LinearLayout
• Arranges children vertically (default) or horizontally.
• Uses android:orientation="vertical" or "horizontal".
Example
xml
CopyEdit
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me" />
</LinearLayout>
theory Page 13
1.2 RelativeLayout
• Positions children relative to each other or the parent.
• Uses attributes like layout_above, layout_below, layout_alignParentTop, etc.
Example
xml
CopyEdit
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 2"
android:layout_below="@id/btn1" />
</RelativeLayout>
1.4 FrameLayout
• Used for stacking views on top of each other.
• Commonly used for fragments.
Example
xml
CopyEdit
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/sample_image"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Overlay Text"
android:layout_gravity="center"/>
</FrameLayout>
theory Page 14
Views are UI components like TextView, Button, EditText, etc.
2.1 TextView
• Displays text.
Example
xml
CopyEdit
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, Android!"
android:textSize="20sp"
android:textColor="#FF0000"/>
2.2 EditText
• Allows users to input text.
Example
xml
CopyEdit
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your name"/>
2.3 Button
• Triggers actions when clicked.
Example
xml
CopyEdit
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:onClick="buttonClicked"/>
In Activity (Kotlin)
kotlin
CopyEdit
fun buttonClicked(view: View) {
Toast.makeText(this, "Button Clicked!", Toast.LENGTH_SHORT).show()
}
2.4 ImageView
• Displays images.
Example
xml
CopyEdit
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/sample_image"/>
2.5 CheckBox
• Allows multiple selections.
Example
xml
CopyEdit
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Accept Terms & Conditions"/>
theory Page 15
2.6 RadioButton
• Used in RadioGroup for single selection.
Example
xml
CopyEdit
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 1"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 2"/>
</RadioGroup>
2.7 Switch
• Used for on/off toggling.
Example
xml
CopyEdit
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enable Notifications"/>
2.8 ProgressBar
• Displays a loading animation.
Example
xml
CopyEdit
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
2.9 SeekBar
• Allows users to adjust values (e.g., volume control).
Example
xml
CopyEdit
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
gradle
CopyEdit
dependencies {
implementation 'androidx.recyclerview:recyclerview:1.2.1'
}
2. RecyclerView Layout
xml
CopyEdit
theory Page 16
CopyEdit
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
3. Item Layout (item_row.xml)
xml
CopyEdit
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item Name"/>
4. Adapter (Kotlin)
kotlin
CopyEdit
class MyAdapter(private val items: List<String>) : RecyclerView.Adapter<MyAdapter.ViewHolder>() {
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_row, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.itemView.findViewById<TextView>(R.id.textView).text = items[position]
}
override fun getItemCount() = items.size
}
5. Set RecyclerView in Activity
kotlin
CopyEdit
val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = MyAdapter(listOf("Item 1", "Item 2", "Item 3"))
Conclusion
• Use ConstraintLayout for modern apps.
• Prefer RecyclerView over ListView.
• Follow Material Design Guidelines.
• Test UI with different screen sizes.
1. Activity Class :
• The Activity class is a crucial component of Android applications.
• Every app has at least one Activity, which acts as the entry point for interacting with users.
• Unlike traditional programming languages where main() is the entry point, Android initiates code execution in an Activity instance through
specific lifecycle callback methods.
2. Activity Lifecycle Methods :
• onCreate() :
• Called when the activity is first created.
• Used to initialize essential components of the activity.
• Takes a Bundle object parameter (savedInstanceState) which contains the previous state data if the activity is being re-initialized.
setContentView(R.layout.activity_main)
4. Declaring Activities in Manifest :
• Every activity must be declared in the AndroidManifest.xml file within the <application> tag.
• The main activity should have an <intent-filter> with MAIN action and LAUNCHER category.
theory Page 17
<activity android:name=".SecondActivity"></activity>
5. Permissions :
• Any service or feature (like Internet, Bluetooth) requires permissions declared in the manifest.
<uses-permission android:name="android.permission.INTERNET"/>
6. AppCompatActivity :
• Extends the Activity class and provides compatibility with older versions of Android.
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
14. uses-feature : Specifies hardware features required by the app.
<uses-feature android:name="android.hardware.camera" />
15. permission : Defines custom permissions.
<permission android:name="com.example.myapp.permission.ACCESS_DATA" />
16. Attributes :
• versionCode & versionName : Define the app's version.
android:versionCode="1"
android:versionName="1.0"
17. installLocation : Specifies whether the app should be installed on internal storage or SD card.
android:installLocation="auto"
18. Additional Elements :
• uses-library : Links against shared libraries.
<uses-library android:name="com.google.android.maps" />
• uses-configuration : Specifies input mechanisms supported by the app.
xml
Copy
1
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="30" />
theory Page 18
android:targetSdkVersion="30" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivity" />
</application>
</manifest>
Summary
• Understand the structure and importance of the AndroidManifest.xml file.
• Declare all necessary components (activities, services, etc.) within the manifest.
• Use attributes like versionCode, versionName, and installLocation appropriately.
• Specify required permissions and features to ensure proper functionality.
• Utilize intent filters to define how components interact with intents.
Services in Android
19. What is a Service?
• A Service is an Android component that allows an application to perform long-running operations in the background without a user interface.
• It ensures that tasks continue running even if the user switches to another app or the app's UI is destroyed.
20. Types of Android Services
• Foreground Services :
• Notify the user about ongoing operations (e.g., downloading files).
• Example: Music player showing a notification while playing music.
• Background Services :
• Perform tasks without notifying the user.
• Example: Syncing data in the background.
• Bound Services :
• Allow components (like Activities) to bind to the service for inter-process communication (IPC).
• Example: A chat app binding to a messaging service.
21. Lifecycle of Android Services
• Started Service (Unbounded) :
• Starts with startService() and runs indefinitely until stopped using stopService() or stopSelf().
• Bound Service :
• Starts when a component binds to it using bindService() and stops when all components unbind using unbindService().
22. Important Callback Methods
• onStartCommand() :
• Called when a component starts the service using startService().
• Returns an integer indicating how the system should handle the service if it gets terminated.
• onBind() :
• Mandatory to implement; called when a component binds to the service using bindService().
• Returns an IBinder object for communication with the service.
• onUnbind() :
• Called when all clients disconnect from the service.
• onRebind() :
• Called when new clients connect after all previous clients disconnected.
• onCreate() :
• Called when the service is first created.
• onDestroy() :
• Called when the service is no longer in use and is being destroyed.
23. Declaring Services in the Manifest
• Every service must be declared in the AndroidManifest.xml file within the <application> tag.
xml
Copy
1
Every Android project needs a Gradle for generating an apk from the .java and .xml files in the project.
Simply put, a Gradle takes all the source files (java and XML) and applies appropriate tools, e.g., converts
the java files into dex files and compresses all of them into a single file known as apk that is actually used.
theory Page 19
the java files into dex files and compresses all of them into a single file known as apk that is actually used.
There are two types of build.gradle scripts
• Top-level build.gradle
• Module-level build.gradle
CardView is a new widget in Android that can be used to display any sort of data by providing a rounded
corner layout along with a specific elevation. CardView is the view that can display views on top of each
other. The main usage of CardView is that it helps to give a rich feel and look to the UI design. This widget
can be easily seen in many different Android Apps. CardView can be used for creating items in listview or
inside RecyclerView. The best part about CardView is that it extends Framelayout and it can be displayed on
all platforms of Android. Now we will see the simple example of CardView implementation.
theory Page 20
26 February 2025 22:33
Open a Webpage
fun openWebsite(url: String) {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
startActivity(intent)
}
Usage
button.setOnClickListener {
openWebsite("https://www.google.com")
}
intents Page 21
menu
26 February 2025 23:00
Op ons en ( op Right en )
Concept: Appears at the top-right of the app when clicking the three-dot menu.
Steps to Implement:
men main.xml m
m
I m c c c
menu_main.xml (res/menu/menu_main.xml)
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/option1"
android:title="Option 1"/>
<item
android:id="@+id/option2"
android:title="Option 2"/>
</menu>
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main, menu) // Inflate menu
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.option1 -> Toast.makeText(this, "Option 1 clicked", Toast.LENGTH_SHORT).show()
R.id.option2 -> Toast.makeText(this, "Option 2 clicked", Toast.LENGTH_SHORT).show()
}
return super.onOptionsItemSelected(item)
}
}
Trick to Remember:
M.O.I. → Menu XML, OnCreateOptionsMenu, Item Click
op p en ( on Clic en )
Concept: Appears near a button when clicked.
Steps to Implement:
c m m
m
c
menu_popup.xml (res/menu/menu_popup.xml)
xml
CopyEdit
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/edit"
android:title="Edit"/>
<item android:id="@+id/save"
android:title="Save"/>
</menu>
menu Page 23
</menu>
activity_main.xml
xml
CopyEdit
<Button
android:id="@+id/btnPopup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Popup"
android:layout_centerInParent="true"/>
MainActivity.kt
kotlin
CopyEdit
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val btnPopup = findViewById<Button>(R.id.btnPopup)
btnPopup.setOnClickListener {
val popup = PopupMenu(this, btnPopup)
popup.menuInflater.inflate(R.menu.menu_popup, popup.menu)
popup.setOnMenuItemClickListener { item ->
when (item.itemId) {
R.id.edit -> Toast.makeText(this, "Edit clicked", Toast.LENGTH_SHORT).show()
R.id.save -> Toast.makeText(this, "Save clicked", Toast.LENGTH_SHORT).show()
}
true
}
popup.show()
}
}
}
Trick to Remember:
B.P.I. → Button Click, Popup Menu XML, Item Click
Summary of 3 Menus
Menu Triggered By Steps to Implement Best Used For
Type
Options Clicking the top- onCreateOptionsMenu(), App-wide actions like
Menu right menu onOptionsItemSelected() settings, logout
Context Long-pressing a registerForContextMenu(), Actions related to a
Menu view (e.g., onCreateContextMenu(), specific item (e.g., delete,
TextView) onContextItemSelected() share)
Popup Clicking a button PopupMenu, Temporary actions related
Menu setOnMenuItemClickListener() to a button
menu Page 24
Geolocation ,notifications,shared pref
26 February 2025 23:32
Geocoder in Android
1. What is Geocoder?
○ Converts latitude & longitude into a human-readable address.
○ Requires internet access and location permissions.
2. Permissions Needed in AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
3. Simple XML Layout (activity_main.xml)
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fetching address..."
android:textSize="18sp"
android:padding="16dp"/>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.POST_NOTIFICATIONS), 101)
}
}
}
if (requestCode == 101) {
if (grantResults.isNotEmpty() && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Notification Permission Granted!", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Permission Denied! No notifications for you.",
Toast.LENGTH_SHORT).show()
}
}
}
}
Shared preference
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<EditText
android:id="@+id/etName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Enter Name" />
<Button
android:id="@+id/btnSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
<TextView
android:id="@+id/tvResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Saved Name will appear here" />
</LinearLayout>
import android.content.SharedPreferences
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
Geolocation
<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.location.Location
import android.os.Bundle
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices