UNIT I — Introduction to Android
1.1 Android Development Environment
Android is an open-source, Linux-based mobile operating system maintained by Google. It powers smartphones, tablets, TVs,
wearables, and automotive systems. The development environment consists of the following components:
• Android Studio — Official IDE based on IntelliJ IDEA. Provides a visual layout editor, code editor, emulator, and
profiler in one package.
• Gradle — Build automation system that compiles source code, packages resources, and creates the final APK or
AAB file.
• Android Virtual Device (AVD) — Software-based emulator to test apps without a physical device.
• ADB (Android Debug Bridge) — Command-line tool to communicate with connected devices/emulators.
Example — Project Structure:
MyApp/
app/
src/main/
java/com/example/myapp/ ← Kotlin/Java source files
res/layout/ ← XML layout files
res/values/[Link] ← String resources
[Link] ← App blueprint
[Link] ← App-level build config
[Link] ← Project-level build config
1.2 Android SDK
The Android SDK (Software Development Kit) is a comprehensive set of development tools, libraries, and APIs required to
build Android applications.
SDK Component Purpose
Platform Tools (adb, fastboot) Communicate with devices, flash firmware
Build Tools (aapt, dx, d8) Compile resources and convert bytecode to DEX
format
SDK Platforms (API levels) Target-specific Android OS versions
Android Emulator Test apps without physical hardware
Support Libraries / Jetpack Backward-compatible APIs and architecture
components
• API Level represents the Android OS version. Example: API 33 = Android 13, API 34 = Android 14.
• In [Link]: minSdk (minimum supported), targetSdk (optimized for), compileSdk (compiled against).
android {
compileSdk 34
defaultConfig {
minSdk 21 // Android 5.0 (Lollipop)
targetSdk 34 // Android 14
}
}
1.3 Open Handset Alliance (OHA)
• OHA is a consortium of 84+ companies (Google, Samsung, HTC, Qualcomm, etc.) formed in November 2007.
• Goal: develop open standards for mobile devices to foster innovation and reduce costs.
• Android is OHA's primary product — released as open-source under the Apache License.
• Benefits: manufacturers can customize Android freely; developers target one platform across many devices.
1.4 Development Framework — Android Architecture
Android is built in layers. From bottom to top:
Layer Description Examples
Linux Kernel Core OS: memory, process, driver Camera, WiFi, Display drivers
management
Hardware Abstraction Layer (HAL) Standardizes hardware access Audio HAL, Bluetooth HAL
Android Runtime (ART) Runs compiled DEX bytecode Ahead-of-time (AOT) compilation
Native C/C++ Libraries Core system libraries OpenGL ES, SQLite, WebKit
Java API Framework Android SDK APIs available to Activity Manager, Content Providers
developers
System Apps Built-in applications Dialer, Contacts, Settings
1.5 Application Fundamentals
Every Android app runs in its own Linux process with a unique user ID (UID) providing sandbox security. Apps communicate
through well-defined interfaces.
Four Core Components:
• Activity — A single screen with a UI (e.g., login screen, home screen).
• Service — Background operation without UI (e.g., music player, file sync).
• BroadcastReceiver — Responds to system-wide broadcast announcements (e.g., battery low).
• ContentProvider — Manages access to shared structured data (e.g., Contacts database).
[Link] — Must declare all components, permissions, and hardware requirements:
<manifest package="[Link]">
<uses-permission android:name="[Link]"/>
<application>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="[Link]"/>
<category android:name="[Link]"/>
</intent-filter>
</activity>
</application>
</manifest>
1.6 Device Compatibility
• Apps declare hardware requirements with <uses-feature> so Google Play filters incompatible devices.
• Screen compatibility: use dp (density-independent pixels) and sp (scale-independent pixels for text).
• Provide resources for multiple screen densities: ldpi (120dpi), mdpi (160dpi), hdpi (240dpi), xhdpi (320dpi), xxhdpi
(480dpi), xxxhdpi (640dpi).
• Use qualifier folders: res/layout-large/, res/values-sw600dp/ for tablets.
1.7 System Permissions
Android enforces a permission model to protect user privacy and device resources.
Permission Type Granted By Example
Normal Auto-granted at install INTERNET, VIBRATE
Dangerous User must approve at runtime CAMERA, READ_CONTACTS,
(Android 6.0+) LOCATION
Signature Only apps with same signing cert System-level permissions
Special Granted via Settings manually WRITE_SETTINGS, OVERLAY
Runtime permission request example:
if ([Link](this, [Link])
!= PackageManager.PERMISSION_GRANTED) {
[Link](this,
arrayOf([Link]), REQUEST_CODE)
}
1.8 Android Development Tools
• Android Studio: Layout Editor (drag-and-drop UI design), Code Editor (Kotlin/Java with IntelliJ features), Android
Profiler (CPU, Memory, Network, Energy).
• ADB (Android Debug Bridge): adb install [Link], adb logcat, adb shell, adb push/pull files.
• AVD Manager: Create virtual devices with specific hardware profiles and API levels.
• Logcat: Real-time log viewer. Use Log.d(), Log.e(), Log.i() for debug messages.
• Lint: Static analysis tool. Detects bugs, performance issues, accessibility problems.
• ProGuard/R8: Shrinks, obfuscates, and optimizes code for release builds.
UNIT II — Getting Started with Mobility
2.1 Mobility Landscape
• Mobile devices now outnumber desktop computers globally. Smartphones are primary internet access points in many
countries.
• Categories: Smartphones, Tablets, Wearables (smartwatches), IoT devices, Android TV, Android Auto.
• Key challenges in mobile development: limited battery, diverse screen sizes, intermittent connectivity, varying
CPU/RAM, and multiple OS versions in the field.
2.2 Mobile Platforms
Platform Developer Language Market Share
Android Google / OHA Kotlin, Java ~72% globally
iOS Apple Swift, Objective-C ~27% globally
HarmonyOS Huawei ArkTS, Java Growing in China
KaiOS KaiOS Technologies HTML5, JS Feature phones
Mobile App Types:
• Native Apps: Built for one platform. Best performance, full API access. Example: WhatsApp Android (Kotlin).
• Web Apps: Run in browser. No install needed but limited device access. Example: Progressive Web Apps (PWAs).
• Hybrid Apps: Web tech wrapped in native shell. Example: Ionic, Cordova.
• Cross-platform Native: Single codebase, near-native performance. Example: Flutter (Dart), React Native (JavaScript).
2.3 Android Terminologies
APK: Android Package Kit — the installable app file (ZIP archive containing DEX bytecode + resources).
AAB: Android App Bundle — newer format; Play Store generates optimized APKs per device.
DEX: Dalvik Executable — bytecode format optimized for Android Runtime (ART).
ART: Android Runtime — executes DEX files using AOT (ahead-of-time) compilation since Android 5.0.
R class: Auto-generated class mapping resource names to integer IDs (e.g., [Link].activity_main).
Context: Interface to global app information — access resources, start activities, get system services.
Fragment: Reusable portion of UI within an Activity. Has its own lifecycle.
2.4 Application Context
• Application Context: Tied to the application lifecycle. Use for singletons, database initialization, registering for global
broadcasts.
• Activity Context: Tied to the Activity lifecycle. Use for UI operations (inflating views, showing dialogs, starting
activities).
• Use getApplicationContext() for long-lived objects to avoid memory leaks.
// Application Context — safe for long-lived use
val db = [Link](applicationContext, AppDatabase::[Link],
"mydb").build()
// Activity Context — needed for UI
val dialog = [Link](this).setTitle("Hello").create()
2.5 Activities
• An Activity represents one screen. Every Activity must be declared in [Link].
• The launcher Activity has MAIN action + LAUNCHER category in its intent-filter.
• Activities are managed in a Back Stack — LIFO (last in, first out).
• Launch modes: standard (default), singleTop, singleTask, singleInstance — control how activities are created/reused.
2.6 Services
• Service runs in background without UI. Runs on the main thread — must spawn worker threads for heavy work.
• Started Service: Runs until stopSelf() or stopService() is called. Returns START_STICKY to restart after kill.
• Bound Service: Client binds with bindService(). Destroyed when all clients unbind.
• Foreground Service: Must display a persistent notification (required on Android 8.0+). Used for music players,
navigation.
2.7 Intents
Intent is a messaging object used to request an action from another component.
• Explicit Intent: Targets a specific class by name. Used for intra-app navigation.
• Implicit Intent: Declares an action; system finds a matching component. Example: share text, open URL.
// Explicit Intent — start a specific Activity
val intent = Intent(this, DetailActivity::[Link])
[Link]("userId", 42)
startActivity(intent)
// Implicit Intent — open a URL in any browser
val intent = Intent(Intent.ACTION_VIEW, [Link]("[Link]
startActivity(intent)
2.8 Receiving and Broadcasting Intents
• sendBroadcast(intent) — sends a broadcast to all matching BroadcastReceivers.
• [Link](context, intent) — called when a matching broadcast is received.
• Static registration (Manifest): receives broadcasts even when app is not running.
• Dynamic registration (registerReceiver()): only receives while the app is running; must call unregisterReceiver() to
prevent leaks.
class BatteryReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val level = [Link](BatteryManager.EXTRA_LEVEL, -1)
Log.d("Battery", "Level: $level%")
}
}
// Register dynamically:
registerReceiver(BatteryReceiver(), IntentFilter(Intent.ACTION_BATTERY_CHANGED))
2.9 Setting Up Dev Environment with Emulator
• Step 1: Download and install Android Studio from [Link].
• Step 2: Open SDK Manager — install desired API level SDK, Platform Tools, Build Tools, and Emulator.
• Step 3: Open AVD Manager — create a new virtual device. Choose hardware profile (e.g., Pixel 6), select system
image (API level + ABI: x86_64), configure RAM and storage.
• Step 4: Enable Hardware Acceleration — HAXM (Intel) or WHPX (AMD/Windows) for faster emulation.
• Physical device alternative: Enable Developer Options (tap Build Number 7 times) → Enable USB Debugging →
Connect via USB.
UNIT III — Building Blocks of Mobile Apps
3.1 App User Interface Designing
• Android UIs are defined declaratively in XML layout files stored in res/layout/.
• Layouts are inflated in Activities using setContentView([Link].activity_main) or in Fragments using LayoutInflater.
• Jetpack Compose is the modern alternative — defines UI in Kotlin code using composable functions (no XML
needed).
3.2 Layouts
Layout Type Description Best Use
LinearLayout Arranges children in a single row or Simple forms, toolbars
column
RelativeLayout Positions children relative to each Overlapping views
other or parent
ConstraintLayout Flat hierarchy using constraint rules Complex, responsive UIs
FrameLayout Stacks children on top of each other Fragments, overlays
GridLayout Arranges children in a grid of Calculators, image grids
rows/columns
RecyclerView Scrollable list/grid with view Long lists, feeds
recycling
3.3 User Interface Controls (Widgets)
Android provides a rich set of UI controls. All extend the View class.
• TextView: Displays text. Attributes: text, textSize, textColor, gravity.
• EditText: Editable text field. Attributes: hint, inputType (text, number, password, email).
• Button: Clickable button. Handle click via setOnClickListener{} or android:onClick in XML.
• ImageView: Displays images. Use Glide or Picasso libraries for loading from URLs.
• CheckBox: Boolean selection. Use isChecked to read state.
• RadioButton / RadioGroup: Mutually exclusive options within a RadioGroup.
• Switch / ToggleButton: On/off toggle. Use isChecked.
• Spinner: Dropdown selection list. Use ArrayAdapter to populate.
• SeekBar: Horizontal slider for range selection.
• ProgressBar: Shows task progress (determinate or indeterminate).
• RecyclerView: Efficient scrollable list. Requires Adapter + ViewHolder + LayoutManager.
• AlertDialog: Modal popup with buttons. Builder pattern to construct.
• Toast: Brief non-interactive pop-up message.
• Snackbar: Action-able brief message at bottom of screen (Material Design).
// Button click example
val btn = findViewById<Button>([Link])
[Link] {
[Link](this, "Clicked!", Toast.LENGTH_SHORT).show()
}
// Spinner example
val spinner = findViewById<Spinner>([Link])
val adapter = [Link](this,
[Link].planets_array, [Link].simple_spinner_item)
[Link] = adapter
3.4 VUIs and Text-to-Speech (TTS) Techniques
Voice User Interfaces (VUIs) allow users to interact using voice instead of touch.
• TextToSpeech API: Converts text strings into spoken audio output. Steps: instantiate TTS, implement OnInitListener,
call speak().
• SpeechRecognizer API: Converts spoken audio to text. Uses RecognizerIntent.ACTION_RECOGNIZE_SPEECH.
• Google Assistant / Voice Actions: Apps can register voice actions that trigger Activities via Intents.
class MainActivity : AppCompatActivity(), [Link] {
private lateinit var tts: TextToSpeech
override fun onCreate(savedInstanceState: Bundle?) {
[Link](savedInstanceState)
tts = TextToSpeech(this, this) // Initialize TTS
}
override fun onInit(status: Int) {
if (status == [Link]) {
[Link] = [Link] // Set language
[Link](1.0f) // Normal speed
[Link](1.0f) // Normal pitch
[Link]("Hello Android!", TextToSpeech.QUEUE_FLUSH, null, null)
}
}
override fun onDestroy() {
[Link](); [Link]() // Always release resources
[Link]()
}
}
3.5 Designing the Right UI
• Clarity: Users should always understand what an element does before interacting with it.
• Consistency: Follow Material Design guidelines for colors, typography, spacing, and component behavior.
• Feedback: Every action should produce immediate visual/haptic/audio feedback.
• Accessibility: Minimum touch target 48dp x 48dp. Use contentDescription on ImageViews. Support TalkBack screen
reader.
• Responsive Design: Use ConstraintLayout with percentage-based constraints. Use DP/SP units never pixels.
• Fragments: Modular UI pieces. Combine differently on phones (one at a time) vs tablets (side by side).
3.6 Activity States and Lifecycle
Understanding the Activity lifecycle is critical for saving state, managing resources, and avoiding crashes.
Callback When Called What to Do
onCreate() Activity first created Initialize UI, bind views, restore
saved state
onStart() Becomes visible to user Start animations, register listeners
onResume() Gains user focus (interactive) Resume camera, sensors, start
updates
onPause() Partially obscured or interrupted Pause animations, save draft data
onStop() No longer visible Release heavy resources, stop
updates
onRestart() Stopped, then started again Refresh data
onDestroy() About to be destroyed Release all resources, cancel
threads
• onSaveInstanceState(Bundle): Called before onStop(). Save UI state (text entered, scroll position).
• onRestoreInstanceState(Bundle) or savedInstanceState in onCreate(): Restore that state.
• Configuration Changes (screen rotation): Activity is destroyed and recreated. Use ViewModel to survive this.
3.7 Interaction Among Activities
• Start Activity: startActivity(Intent(this, TargetActivity::[Link]))
• Pass Data: [Link]("key", value) → retrieve with [Link]("key")
• Get Result Back: Use Activity Result API — registerForActivityResult(StartActivityForResult()) { result -> ... }
• Back Stack: Android maintains a Task (stack of Activities). Back button pops the top Activity.
• Launch Modes control stack behavior: singleTask ensures only one instance exists in the stack.
UNIT IV — Sprucing Up Mobile Apps
4.1 Threads and Sync Tasks
Android has a single Main Thread (UI Thread). All UI updates MUST happen on this thread. Blocking it for more than 5
seconds triggers an ANR (App Not Responding) dialog.
• Thread / Runnable: Basic Java concurrency. runOnUiThread{} posts back to main thread.
• Handler + Looper: Post Runnable or Message objects to a thread's message queue.
• Kotlin Coroutines (recommended): Lightweight concurrency. [Link] for network/disk, [Link] for UI
updates.
• WorkManager: For deferrable, guaranteed background work that must complete even if the app or device restarts
(e.g., uploading photos, syncing data).
Sync Tasks — SyncAdapter:
• SyncAdapter syncs app data with a remote server in the background, efficiently batching network requests.
• Works with AccountManager and ContentProvider. Triggered by time interval, network availability, or data change.
• System manages sync scheduling to optimize battery usage (groups syncs from multiple apps).
// Coroutine example — network call off main thread
[Link] {
val result = withContext([Link]) {
[Link](userId) // Network call on IO thread
}
_user.value = result // Update LiveData on main thread
}
4.2 Services — States and Lifecycle
A Service performs long-running background operations. It has no UI.
• Started Service Lifecycle: onCreate() → onStartCommand() → [running] → onDestroy()
• Bound Service Lifecycle: onCreate() → onBind() → [bound to clients] → onUnbind() → onDestroy()
• onStartCommand() return values: START_STICKY (restart after kill, null intent), START_NOT_STICKY (don't
restart), START_REDELIVER_INTENT (restart with original intent).
• Foreground Service (Android 8.0+): Must call startForeground() with a NotificationId within 5 seconds of start.
class MusicService : Service() {
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
// Show foreground notification
startForeground(NOTIF_ID, buildNotification())
// Start playing music in a coroutine
return START_STICKY
}
override fun onBind(intent: Intent?): IBinder? = null
override fun onDestroy() { [Link](); [Link]() }
}
4.3 Notifications
• Notification Channel: Required on Android 8.0+. Groups notifications by category with importance level
(IMPORTANCE_HIGH shows as heads-up).
• Build using [Link]. Set smallIcon (required), contentTitle, contentText, PendingIntent (action on
tap).
• Styles: BigTextStyle (long text), BigPictureStyle (image), InboxStyle (list of lines), MessagingStyle (chat).
• Android 13+: Apps must request POST_NOTIFICATIONS runtime permission.
// Create channel (do once, e.g., in Application class)
val channel = NotificationChannel("news_ch", "News",
NotificationManager.IMPORTANCE_DEFAULT)
[Link](channel)
// Build and show notification
val notification = [Link](this, "news_ch")
.setSmallIcon([Link].ic_notification)
.setContentTitle("Breaking News")
.setContentText("Tap to read the full story")
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.build()
[Link](1, notification)
4.4 Broadcast Receivers
• Responds to system-wide broadcast events. onReceive() must complete within 10 seconds or system kills it.
• Static registration in Manifest: receives broadcasts even when app is stopped (limited in Android 8.0+ for implicit
broadcasts).
• Dynamic registration: more flexible, must unregister in onStop()/onDestroy() to prevent memory leaks.
4.5 Telephony and SMS APIs
• TelephonyManager: Provides access to telephony services — network operator, device IMEI, call state, signal
strength.
• PhoneStateListener: Monitors call state changes (CALL_STATE_IDLE, CALL_STATE_RINGING,
CALL_STATE_OFFHOOK).
• SmsManager: Send SMS messages programmatically. Requires SEND_SMS permission.
• Receive SMS: Listen for [Link].SMS_RECEIVED broadcast. Requires RECEIVE_SMS
permission.
// Send SMS
val sms = [Link]()
[Link]("+919876543210", null, "Hello from Android!", null, null)
// Detect call state
val tm = getSystemService(TELEPHONY_SERVICE) as TelephonyManager
[Link](object : PhoneStateListener() {
override fun onCallStateChanged(state: Int, phoneNumber: String?) {
when (state) {
TelephonyManager.CALL_STATE_RINGING -> Log.d("Call", "Incoming:
$phoneNumber")
TelephonyManager.CALL_STATE_IDLE -> Log.d("Call", "Idle")
}
}
}, PhoneStateListener.LISTEN_CALL_STATE)
4.6 Native Data Handling
4.6.1 On-Device File I/O
• Internal Storage: Private to your app. Deleted when app is uninstalled. getFilesDir() returns path.
• External Storage: Shared storage (removable or emulated). Requires READ/WRITE_EXTERNAL_STORAGE
permission on older APIs; scoped storage on Android 10+.
• Cache files: getExternalCacheDir() and getCacheDir() — may be cleared by system when storage is low.
4.6.2 SharedPreferences
• Key-value store for primitive types (String, Int, Boolean, Float, Long, Set<String>).
• Ideal for app settings, user preferences, simple state. Data persists across app restarts.
• Use DataStore (Jetpack) as the modern replacement for SharedPreferences — supports Flow for reactive reading.
// Write
val prefs = getSharedPreferences("app_prefs", MODE_PRIVATE)
[Link]() { putString("username", "Rahul"); putBoolean("dark_mode", true) }
// Read
val username = [Link]("username", "Guest") // default = "Guest"
4.6.3 SQLite Database
• SQLite is a lightweight, embedded relational database included in every Android device.
• Use SQLiteOpenHelper — subclass it, override onCreate() to create tables, onUpgrade() to migrate schema.
• Room (Jetpack) is the recommended abstraction over SQLite. Uses annotations for type-safe queries.
Room Annotation Purpose Example
@Entity Maps a Kotlin class to a database @Entity(tableName = "students")
table
@PrimaryKey Marks the primary key field @PrimaryKey(autoGenerate = true)
@Dao Marks a Data Access Object @Dao interface StudentDao
interface
@Query Defines a SQL query @Query("SELECT * FROM
students")
@Insert Insert operation @Insert(onConflict = REPLACE)
@Database Marks the database class @Database(entities =
[Student::class], version = 1)
4.6.4 Content Providers
• Manages structured data shared between apps. Uses a URI scheme: content://authority/table/id
• ContentResolver is the client-side interface to query/insert/update/delete data.
• Built-in providers: Contacts (ContactsContract), Media (MediaStore), Calendar (CalendarContract).
// Query contacts using ContentResolver
val cursor = [Link](
[Link].CONTENT_URI,
arrayOf([Link].DISPLAY_NAME),
null, null,
[Link].DISPLAY_NAME + " ASC"
)
cursor?.use {
while ([Link]()) {
val name =
[Link]([Link]([Link].DISPLAY_NAME))
Log.d("Contact", name)
}
}
UNIT V — Factors in Developing Mobile Applications
5.1 Mobile Software Engineering
Mobile Software Engineering applies traditional SE principles to the unique constraints of mobile platforms.
Key Characteristics of Mobile Applications:
• Context-aware: Apps adapt to location, time, device orientation, and ambient conditions.
• Always-on connectivity: Apps handle online/offline states gracefully with local caching.
• Resource-constrained: Must be efficient in battery, CPU, memory, and network usage.
• Frequent updates: Mobile apps update more frequently than desktop software (weekly/monthly cycles).
• Touch-first UX: Interactions designed for fingers, not mouse and keyboard.
• Security-sensitive: Store credentials securely; handle permissions carefully.
• Interruptible: Phone calls, notifications can interrupt the app at any time — handle lifecycle properly.
• Diverse hardware: Must work across thousands of device models with varying specs.
5.2 Frameworks and Tools
Category Framework/Tool Purpose
Architecture Jetpack (ViewModel, LiveData, MVVM, lifecycle-aware components
Navigation)
Networking Retrofit + OkHttp Type-safe REST API calls
Image Loading Glide / Coil Efficient image caching and display
Dependency Injection Hilt (Dagger-based) Manage dependencies, improve
testability
Async / Concurrency Kotlin Coroutines + Flow Non-blocking async operations
Local Database Room SQLite abstraction with ORM
Testing JUnit, Espresso, Mockito Unit, UI, and mock testing
Analytics / Crash Firebase Crashlytics Track crashes and performance
CI/CD GitHub Actions, Bitrise, Fastlane Automate build, test, deploy
5.3 Generic UI Development
• MVVM Architecture: Model (data/business logic) — ViewModel (UI logic, LiveData/StateFlow) — View
(Activity/Fragment, observes ViewModel).
• Jetpack Compose: Modern declarative UI. Composable functions describe what UI should look like given the current
state. No XML layouts.
• Material3 (Material You): Google's design system. Dynamic color theming adapts to user's wallpaper.
• Jetpack Navigation: Manages fragment/activity navigation, back stack, deep links with a visual navigation graph.
// Jetpack Compose example
@Composable
fun Greeting(name: String) {
Column(modifier = [Link]([Link])) {
Text(text = "Hello, $name!", style = [Link])
Button(onClick = { /* action */ }) { Text("Click Me") }
}
}
5.4 Performance and Multithreading
• Target 60 fps (16ms per frame) or 120 fps on high-refresh devices. Missed frames appear as jank.
• Never block the main thread. Use [Link] for network/disk, [Link] for CPU-intensive work.
• Android Profiler: Real-time graphs of CPU, Memory, Network, and Energy usage.
• Memory Leaks: Common causes — holding Activity reference in a singleton, non-unregistered listeners, static Views.
Detect with LeakCanary library.
• ViewHolder Pattern in RecyclerView: Reuses inflated views to avoid costly repeated inflation during scroll.
• Lazy Loading: Load data and images only when needed. Use Paging 3 library for large datasets.
5.5 Android Graphics
• Canvas API: Low-level 2D drawing. Create a custom View, override onDraw(canvas: Canvas). Use Paint to set color,
stroke width, text size.
• Drawable: XML-defined shapes, gradients, state selectors for button states (pressed, focused, disabled).
• OpenGL ES: For 3D graphics and games. GLSurfaceView provides an OpenGL rendering surface. Alternatives:
Unity, libGDX.
• Animations: ObjectAnimator (animates View properties), TransitionManager (screen transitions), Lottie (JSON-based
vector animations), MotionLayout (complex motion and widget animation).
// Canvas drawing example
class CircleView(context: Context) : View(context) {
private val paint = Paint().apply {
color = [Link]
style = [Link]
}
override fun onDraw(canvas: Canvas) {
[Link](width / 2f, height / 2f, 100f, paint)
}
}
5.6 Mobile Agents and Peer-to-Peer Architecture
Mobile Agents are autonomous software programs that can move between network nodes and execute tasks on behalf of a
user. They reduce network traffic by bringing computation to the data.
• Properties: Autonomous (act independently), mobile (migrate across nodes), reactive (respond to environment),
adaptive (learn and adjust behavior).
• Use cases: distributed data collection, network monitoring, e-commerce brokering.
Peer-to-Peer (P2P) Architecture: Direct device-to-device communication without a central server.
• Wi-Fi Direct API: Android devices discover and connect directly at Wi-Fi speeds without a router or internet. Used for
file transfer, screen casting.
• Bluetooth / BLE: Short-range P2P communication. BLE (Bluetooth Low Energy) is used for IoT sensors, beacons,
wearables.
• NFC: Very short range (< 4cm) P2P. Used for payment (Google Pay), pairing, data exchange.
5.7 Android Multimedia
• MediaPlayer: Play audio/video. Lifecycle: Idle → Initialized → Prepared → Started → Paused/Stopped → End.
Always call release() when done.
• ExoPlayer (now Media3): Google's powerful, extensible media player. Supports HLS, DASH, smooth streaming,
DRM, offline playback. Recommended over MediaPlayer.
• CameraX (Jetpack): Simplified camera API. Handles lifecycle, rotation, device quirks automatically. Supports
Preview, ImageCapture, VideoCapture, ImageAnalysis.
• AudioRecord / AudioTrack: Low-level PCM audio recording and playback for advanced audio processing.
• SoundPool: Pool of short audio clips with low-latency playback — ideal for game sound effects.
• MediaRecorder: Records audio and video to a file. Set source, output format, encoder, then start().
UNIT VI — Platforms and Additional Issues
6.1 Development Process
• Requirements: Gather functional (features) and non-functional (performance, security) requirements. Consider target
devices and OS versions.
• Architecture Design: Choose architecture pattern (MVVM, Clean Architecture), define data flow, plan API contracts.
• Implementation: Write Kotlin/Java code, XML layouts or Compose UI, handle lifecycle events.
• Testing: Unit tests, integration tests, UI tests, device testing (multiple screen sizes and OS versions).
• Deployment: Sign APK, generate AAB, upload to Google Play. Configure staged rollout (e.g., 10% users first).
• Maintenance: Monitor crashes (Crashlytics), user reviews, performance metrics. Regular updates for compatibility
and security patches.
6.2 Architecture and Design Patterns
Pattern Description Components
MVVM Separates UI from business logic Model, View (Activity/Fragment),
via ViewModel ViewModel
Clean Architecture Three concentric layers with strict Presentation, Domain, Data
dependency rules
Repository Pattern Abstracts data sources behind one ViewModel calls Repository; Repo
interface decides remote vs local
Observer Pattern UI observes data streams (reactive) LiveData, StateFlow, RxJava
Observable
6.3 Technology Selection
• Native Android (Kotlin): Best performance, full API access, best UX. Choose when platform-specific features (NFC,
Bluetooth, Camera) are central.
• Flutter: Single Dart codebase for Android + iOS + Web + Desktop. Excellent performance with Skia/Impeller
rendering engine.
• React Native: JavaScript with near-native bridge to platform components. Large ecosystem; performance below
native for complex UIs.
• Decision factors: team skill set, time-to-market, performance requirements, feature parity needs, long-term
maintenance cost.
6.4 Testing Mobile Applications
Testing Pyramid for Android:
• Unit Tests (70%): Test individual functions, classes, ViewModels in isolation. Use JUnit 4/5, Mockito, Turbine (Flow
testing). Run on JVM — fast.
• Integration Tests (20%): Test interactions between components (e.g., DAO + database, Repository + API). Use
AndroidX Test with Robolectric or real device.
• UI / Instrumented Tests (10%): Test actual user interactions. Use Espresso for View-based UIs, Compose UI Test for
Compose. Runs on emulator or device.
// Espresso UI test example
@Test
fun loginButton_displaysWelcomeMessage() {
onView(withId([Link])).perform(typeText("user@[Link]"))
onView(withId([Link])).perform(typeText("secret123"))
onView(withId([Link])).perform(click())
onView(withId([Link])).check(matches(isDisplayed()))
}
• Firebase Test Lab: Run tests on real devices in Google's data center. Catch device-specific issues.
• Monkey Testing: adb shell monkey -p [Link] 1000 — sends 1000 random events to find crashes.
6.5 Security and Hacking of Android Applications
Common Myths vs Reality:
Myth Reality
"My app is safe because it’s on the Play Store" APKs can be decompiled. Play Store reviews aren’t
security audits.
"HTTPS means my data is safe" Without certificate pinning, MITM attacks can intercept
even HTTPS traffic.
"Users won’t know how my app works internally" APKs can be decompiled with tools like jadx, apktool to
reverse-engineer code.
"My database is secure because it’s internal storage" Rooted devices can read internal storage. Databases
must be encrypted.
"I don’t need security if it’s just a simple app" Even simple apps store user data. Any data leak
erodes user trust.
Common Attacks:
• Reverse Engineering: Decompile APK with jadx/apktool to extract source code, API keys, business logic.
• Man-in-the-Middle (MITM): Intercept network traffic using tools like Burp Suite on the same Wi-Fi network.
• SQL Injection: Malicious SQL in user inputs can corrupt or expose database data.
• Insecure Data Storage: Storing passwords or tokens in SharedPreferences (plaintext), unencrypted files, or logs.
• Intent Injection: Malicious apps send crafted Intents to exported components to trigger unintended actions.
Security Best Practices:
• ProGuard/R8: Obfuscates class/method names. Makes decompiled code nearly unreadable. Enable in release
builds.
• Android Keystore: Store cryptographic keys in hardware-backed secure enclave. Keys never leave the device in
plaintext.
• Certificate Pinning: Embed server’s certificate or public key in the app. Reject any other certificate, preventing MITM.
• Network Security Config: [Link] disables cleartext (HTTP) traffic, pins certificates.
• Encrypt Database: Use SQLCipher to encrypt the entire SQLite database with a passphrase.
• Parameterized Queries: Always use Room’s @Query with parameters or SQLite’s compileStatement to prevent SQL
injection.
• Validate All Inputs: Sanitize data from users, Intents, and external sources before processing.
// Certificate pinning with OkHttp
val certificatePinner = [Link]()
.add("[Link]", "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
.build()
val client = [Link]()
.certificatePinner(certificatePinner)
.build()
6.6 Active Transactions and Data Security
An Active Transaction ensures a set of database operations is treated as a single atomic unit. Either all operations succeed
(commit) or all are rolled back on failure.
• ACID Properties: Atomicity (all-or-nothing), Consistency (data remains valid), Isolation (transactions don’t interfere),
Durability (committed data persists).
• Without transactions, partial writes (e.g., money deducted but not credited) leave data in an inconsistent state.
SQLite Transaction Example:
// SQLite raw transaction
val db = [Link]
[Link]()
try {
[Link]("UPDATE accounts SET balance = balance - 500 WHERE id = 1")
[Link]("UPDATE accounts SET balance = balance + 500 WHERE id = 2")
[Link]() // Commit only if both succeed
} finally {
[Link]() // Rolls back if setTransactionSuccessful() was never called
}
Room Transaction Example:
// Room @Transaction ensures atomic operation
@Dao
interface BankDao {
@Transaction
suspend fun transferFunds(fromId: Int, toId: Int, amount: Double) {
deduct(fromId, amount) // Both operations in one atomic transaction
credit(toId, amount)
}
}
Securing Data During Transactions:
• Encrypt sensitive fields before inserting: Use AES encryption via Android Keystore-backed keys.
• Use SQLCipher for full database encryption: All data at rest is encrypted.
• Secure network transmission: HTTPS with certificate pinning for all API calls transferring sensitive data.
• Avoid logging sensitive data: Never Log.d() passwords, tokens, or personal data.
• Token-based authentication: Use short-lived JWT tokens. Refresh tokens stored in EncryptedSharedPreferences
(uses Keystore internally).
• Wipe sensitive data from memory: Overwrite char arrays with zeros after use; avoid keeping secrets in String objects
(immutable, stays in heap).
// EncryptedSharedPreferences — secure token storage
val masterKey = [Link](context)
.setKeyScheme([Link].AES256_GCM)
.build()
val securePrefs = [Link](
context, "secure_prefs", masterKey,
[Link].AES256_SIV,
[Link].AES256_GCM
)
[Link] { putString("auth_token", "eyJhbGciOiJIUzI1NiJ9...") }
Quick Revision — All Short Answer Topics
a) Android SDK
A toolkit (libraries, APIs, tools) to build Android apps. Key parts: Platform Tools (adb), Build Tools, SDK Platforms (API levels),
Emulator. Apps specify minSdk and targetSdk in [Link].
b) System Permissions
Security model controlling resource access. Normal permissions auto-granted; Dangerous permissions (Camera, Location)
need runtime user approval (Android 6.0+). Declared in [Link].
c) Mobile Platforms
Major platforms: Android (72% share, open-source, Kotlin/Java), iOS (27% share, closed, Swift), HarmonyOS (Huawei). App
types: Native, Web, Hybrid, Cross-platform (Flutter, React Native).
d) Intents
Messaging objects to communicate between components. Explicit Intents target a specific class (intra-app). Implicit Intents
specify an action and let the system find a handler. Carry data via Extras. Used to start Activities, Services, and send
Broadcasts.
e) Text-to-Speech Techniques
Android TTS API converts text to spoken audio. Initialize TextToSpeech with OnInitListener. Set language ([Link]),
setSpeechRate(), setPitch(), then call speak(). Always shutdown() in onDestroy(). SpeechRecognizer converts voice to text.
f) Sync Task
SyncAdapter syncs app data with a remote server in the background. System batches syncs from multiple apps to save
battery. Requires AbstractThreadedSyncAdapter, ContentProvider, and AccountManager. Triggered by schedule, network
availability, or data changes. WorkManager is the modern alternative for guaranteed background tasks.
g) SQLite
Embedded relational database in Android. Use SQLiteOpenHelper (onCreate, onUpgrade) or Room (modern ORM using
@Entity, @Dao, @Database annotations). Supports full SQL. Transactions ensure atomicity. Encrypt with SQLCipher for
sensitive data.
h) Android User Interface Controls
Views: TextView, EditText, Button, ImageView, CheckBox, RadioButton, Switch, Spinner, SeekBar, ProgressBar,
RecyclerView. Containers: LinearLayout, RelativeLayout, ConstraintLayout, FrameLayout. Dialogs: AlertDialog,
DatePickerDialog. Feedback: Toast, Snackbar.
i) Multithreading
Android has one Main/UI Thread. All UI updates on main thread. Background work via Kotlin Coroutines
([Link]/Default/Main), Thread/Runnable, Handler+Looper, WorkManager. ANR occurs if main thread is blocked > 5
seconds.
j) Mobile Apps Testing
Testing Pyramid: Unit Tests (JUnit, Mockito — fast, JVM-based), Integration Tests (AndroidX Test, Robolectric), UI Tests
(Espresso, Compose UI Test — on device). Firebase Test Lab for real device testing. Monkey testing for random event stress
testing.
Shared Preferences
Key-value storage for primitive data types. Persists across app restarts. Ideal for settings, flags, user preferences. API:
getSharedPreferences() → edit() → put*() → apply(). Modern replacement: Jetpack DataStore (supports Flow, coroutines).
Sensitive data: use EncryptedSharedPreferences.
VUI (Voice User Interface)
Interface controlled by voice commands. Components: TextToSpeech (output), SpeechRecognizer (input), Voice Actions
(Activity invocation via Intents). Used in accessibility apps, hands-free scenarios, smart assistants. Google Assistant
integration via App Actions.
Peer-to-Peer Architecture
Direct device communication without a central server. Android implementations: Wi-Fi Direct (WifiP2pManager — high speed,
no router needed), Bluetooth/BLE (short range, low power), NFC (< 4cm, payment/pairing). Advantages: no server costs, low
latency, works offline. Disadvantages: discovery complexity, security challenges.
Mobile Agents
Autonomous software programs that can migrate across network nodes and execute tasks independently. Properties: mobility,
autonomy, reactivity, adaptability. Use cases: distributed data collection, network monitoring, e-commerce price comparison
agents. Reduce network load by moving computation to the data source. Less common now due to microservices and cloud
architectures.