Lectures content: (quizes at the end) LECTURE 1 Overview of Android 1. What is Android? o A platform developed by Google, based on the Linux kernel. o Open-source and optimized for ARM architecture. o Runs apps through virtual machines: Dalvik (older) or ART (current). 2. What makes Android more than just an OS? o Includes radio firmware (for GSM/CDMA/UMTS communication). o Features kernel support for hardware management. o Provides user-space libraries and application frameworks. Android Architecture 1. Kernel • Acts as the core Operating System. • Handles: o Hardware abstraction and device drivers. o Peripherals like audio, video, GPS, WiFi. o Memory management, power optimization (e.g., WAIT_LOCK). o Inter-process communication using Binder and AIDL for synchronous calls. 2. User Space Libraries • Libraries that serve as a bridge between the kernel and applications: o Examples: SQLite (database), WebKit (browser), OpenGL (graphics), Media Framework. o Bionic: Lightweight version of libc tailored for Android. 3. Hardware Abstraction Layer (HAL) • Provides a standard interface for hardware devices. • Includes hardware and vendor-dependent drivers (licensed as GPL). • Drivers are abstracted by services to adapt to hardware changes without impacting the Android framework. Android Runtime (Dalvik and ART) 1. Dalvik (Older Runtime) o Virtual machine optimized for mobile. o Features: ▪ Small memory footprint and fast garbage collection. ▪ Uses .dex files (converted from .class Java files). ▪ Just-In-Time (JIT) compilation for execution. 2. ART (Android Runtime) o Replaced Dalvik as the default runtime. o Features: ▪ Ahead-Of-Time (AOT) compilation for faster app launch. ▪ Supports .dex to .elf and optimized .odex formats. ▪ Includes memory allocators and performance enhancements. Programming on Android 1. Methods of Development • Dalvik/ART (Java/Kotlin): o • High speed, rich library support, recommended for standard apps. Progressive Web Apps (PWAs): o Runs in browsers using JavaScript. o Limited speed and access to system resources. • Native Development Kit (NDK): o For apps in C/C++. o High performance but limited libraries. o Suitable for low-level services (e.g., hardware interfacing). Application Structure 1. Activities: o Represent a single screen in the application. o Implementation: Extends the Activity class. o Can outlive the process through serialization. o Partially controlled by the programmer. o Not suitable for heavy processing tasks. 2. Services: o Designed for background processing. o Run in a separate process with low priority but are stable. 3. Content Providers: o Offer data access and sharing between apps. o Work with SQLite databases and are based on URLs. 4. Broadcast Receivers: o Observe and respond to public events like SCREEN_ON, SCREEN_OFF, BATTERY_STATUS_CHANGED. 2. Application Bundle (APK) • Packaged in an APK file containing: o .dex files: Compiled code. o Resources: XML layouts, images, etc. o Manifest: Includes app metadata, permissions, and a digital signature. 3. Tasks and Activities • A task is a stack of activities, usually within the same process. • Activities can be pushed (added) or popped (removed). • Tasks can include activities from other apps. Security in Android 1. Kernel-Level Security • Features SELinux policies, Ext3 file systems. • Each app runs in its own process with user-specific permissions. • File system permissions: o Apps can write only to specific directories (/data/package.name, /SDCard/). 2. Application-Level Security • • Permissions: o Declared in the app's manifest file. o Allow access to sensitive functions (e.g., GPS, network, phone calls). o User prompts: ▪ At install time (Android < 6). ▪ At runtime (Android >= 6). Communication between apps: o Requires permissions from the target app. o Not applicable to native services, which must check permissions explicitly. Android Libraries • Libraries for Dalvik/ART are distinct from user-space libraries. • Written in Java/Kotlin and provide access to: o Device features (e.g., phone, messaging, sensors). o System services (e.g., Window Manager, Audio Manager) LECTURE 2 Activity Lifecycle 1. Important Lifecycle Functions: o onCreate(...) o onStart(...) o onRestart(...) o onResume(...) o onPause(...) o onStop(...) o onDestroy(...) o Always call the parent function using super.<function>(...). 2. Storing and Loading State: o Store: onSaveInstanceState(Bundle state). o Load: onLoadInstanceState(Bundle state) or onCreate(Bundle savedInstance). Services 1. Service Implementation: o Extend the Service class. o Basic functions: o ▪ onCreate() ▪ onStart(Intent intent, int startID) ▪ onDestroy() Using AIDL (Android Interface Definition Language): ▪ onBind(Intent intent) ▪ onUnbind(). Content Providers and Broadcast Receivers 1. Content Providers: o Facilitate app data sharing. o Linked to SQLite for database operations. o Use URLs to manage resources. 2. Broadcast Receivers: o Observe system-wide or public events. o Examples of events: ▪ SCREEN_ON ▪ SCREEN_OFF ▪ BATTERY_STATUS_CHANGED. Context 1. What is Context? o Any application component (e.g., Activities, Services, Content Providers). o Generated by Dalvik/ART during startup and passed as a parameter. o Used by Broadcast Receivers to access resources and application information. App Manifest 1. Purpose: o A mandatory file in every app. o Contains: ▪ Application components. ▪ Components' properties. ▪ Permissions. ▪ Hardware and software requirements. Emulator vs. Real Phone 1. Emulator: o Boots a Linux-based environment. o Offers several versions for testing. o Runs separately from the host OS. 2. Real Phone: o Requires USB debugging for application development. o Preferred for testing when available. Application Template • Start with pre-defined templates provided by Android Studio. • Follow structured implementation guidelines for Activities, Services, and other components. LECTURE 3 Components (Widgets) • Widgets extend the View class and are placed within an Activity. • Types: o Static Widgets: ▪ o TextView, ProgressBar, ImageView, etc. Dynamic Widgets: ▪ Button, EditText, CheckBox, RadioButton, SeekBar, Spinner, Gallery, MapView, ListView, etc. Containers 1. Purpose: o Containers hold other View elements. 2. Types of Layouts: o LinearLayout: Aligns children in a single direction (vertical/horizontal). o RelativeLayout: Positions children relative to each other or the parent. o ConstraintLayout: Offers flexible positioning. o ScrollView: Enables scrolling content. o TableLayout: Organizes content into rows and columns. Resources 1. Location: Found in the res folder of the project. 2. Categories: o Images: Stored in drawable folders (e.g., ldpi, mdpi, hdpi). o UI Layouts: Stored in layout folders. o Constants: Defined in values/strings.xml. o Raw Resources: Unmodifiable resources stored in the raw folder. 3. Accessing Resources in Code: o o In Java: ▪ Drawable: R.drawable.name (e.g., R.drawable.icon). ▪ Layout: R.layout.name (e.g., R.layout.main). In XML: ▪ Drawable: @drawable/name. ▪ Layout: @layout/name. Building GUI with XML 1. Advantages: o Simplifies coding by separating design from logic. o No Java code is needed for layout definition. 2. Steps: o Define the layout in XML. o Use setContentView(R.layout.name) in the Activity to apply it. 3. Key Attributes: o xmlns:android: Required in the root element. o android:layout_width, android:layout_height: Mandatory for all views. o Common values: ▪ wrap_content: Adjust size to content. ▪ match_parent: Occupy the entire parent space. 4. Referencing Components in Java: o Assign android:id in XML using @+id/name. o Access in Java using R.id.name. Menus 1. Types: o Created programmatically or through XML. o Triggered by the MENU button or specific events. 2. Key Functions: o onCreateOptionsMenu(Menu menu): For menu creation. o onOptionsItemSelected(MenuItem item): To handle item selection. 3. Example: o XML menu file in res/menu/menu_name.xml. o Access it in Java using MenuInflater. Intents 1. Definition: o An intent is a messaging object used to request actions from other app components. 2. Intent Components: o Action: Specifies the desired action (e.g., android.intent.action.VIEW). o Data: URI or resource associated with the intent. o Category: Additional metadata (e.g., CATEGORY_LAUNCHER). o Type: MIME type of data. o Component: Specific destination component. o Extras: Additional key-value pairs for the action. 3. Key Functions: o Start an Activity: startActivity(Intent i). o Start a Service: startService(Intent i). o Send a Broadcast: sendBroadcast(Intent i, String permission). 4. Intent Filters: o Declared in AndroidManifest.xml. o Specify acceptable actions, data types, and categories for the component. Manifest 1. Purpose: o Declares app components (Activities, Services, etc.). o Specifies permissions. o Defines hardware and software requirements. 2. Key Information: Each app must include an AndroidManifest.xml file. o Toast Notifications 1. Definition: o A Toast is a brief message displayed to the user. 2. Usage: o Toast.makeText(Context context, String message, int duration).show(); o Duration options: ▪ Toast.LENGTH_SHORT. ▪ Toast.LENGTH_LONG. LECTURE 4 Processing in Activities 1. Where Processing Happens: o Activity methods (e.g., onCreate(), onStart()). o Observer methods (e.g., onClick()). 2. Challenges: o Avoid excessive processing in UI threads to prevent "Not Responding" errors. 3. Solutions: o Use Threads or Services for processing tasks. Threads in Android 1. Definition: o Threads split a program into multiple concurrent processes. o They share memory (e.g., variables). 2. Implementation: o Using the Thread Class: o class MyThread extends Thread { public void run() { o // Thread code here o } o o } o MyThread myThread = new MyThread(); myThread.start(); // NOT myThread.run() o Using the Runnable Interface: o class MyThread implements Runnable { public void run() { o // Thread code here o } o o } o Thread thread = new Thread(new MyThread()); thread.start(); 3. Runnable vs. Thread: o o Runnable: ▪ Flexible; allows extending other classes. ▪ Just implement the Runnable interface. Thread: ▪ Less flexible; must extend Thread class. 4. Stopping Threads: o A thread stops only when the run() method finishes execution. Services in Android 1. Definition: o Android component designed for background processing. o Runs independently of UI. 2. Types of Services: o Foreground: Noticeable to the user (e.g., media player). o Background: Runs without user awareness. o Bound: Provides a client-server interface using AIDL for inter-process communication (IPC). 3. Implementation Steps: o Extend the Service class. o Override essential methods: o void onCreate(); o void onStart(Intent intent, int startID); o void onDestroy(); void onBind(Intent intent); // For bound services o Declare the service in AndroidManifest.xml. o Start/stop services using: ▪ context.startService(Intent intent). ▪ context.stopService(Intent intent). 4. Example Task: o Prime number calculator service: ▪ Starts and runs in the background. ▪ Uses threads within the service. Android Interface Definition Language (AIDL) 1. Definition: o AIDL is Android's Remote Procedure Call (RPC) mechanism. o Facilitates communication between an Activity and a Service. 2. Syntax: o Similar to Java. o Supports limited data types: ▪ Primitive types (int, long, float, etc.). ▪ String. ▪ Lists and Maps (must contain AIDL-supported types). 3. Example AIDL File: package com.example.movies; interface IMoviesService { int getMovieCount(); String getMovieTitle(int index); String getMovieDirector(int index); } 4. Steps to Implement AIDL: o Create the AIDL interface. o Implement the interface in the service. o Bind the service to an Activity using a Binder. LECTURE 5 Broadcast Receivers 1. What are Broadcast Receivers? o An Android component that follows a publish/subscribe design pattern. o Used to listen for and respond to events. ▪ o Example: Battery low notification. Events are described through an Intent. 2. Types of Broadcasts: o o System Broadcasts: ▪ Sent by the Android System. ▪ Public events defined in the Intent class. ▪ Example: Battery low. Custom Broadcasts: ▪ Sent by apps. ▪ Defined within the application. 3. Broadcast Registration: o Static Registration (via AndroidManifest.xml): ▪ Always active. ▪ Example use case: Listening for system events. ▪ Requires setting android:exported="true" if receiving broadcasts from outside the app. ▪ Steps: 1. Declare the receiver using a <receiver> tag. 2. Add an intent filter for the receiver. o Dynamic Registration: ▪ Registered through Context. ▪ Active while the registering context is active. ▪ Steps: 1. Create an instance of the receiver. 2. Create an IntentFilter instance. 3. Decide if the receiver should be exported. 4. Register the receiver. 4. Sending Broadcasts: o Sender Declaration: o Intent intent = new Intent("custom.action.MY_EVENT"); sendBroadcast(intent); 5. Permissions in Broadcasts: o To restrict who can send or receive broadcasts: ▪ Sender: Attach a permission. ▪ Receiver: Declare a required permission. Shared Preferences 1. Definition: o Used to save small collections of data (e.g., settings, configurations). o Persistent across app sessions. o Stores data as key-value pairs. 2. Characteristics: o File-based storage using XML. o Data is stored in the app’s private storage area. o Multiple files can be used by an app. 3. Why Use Multiple Files?: o Organization: Group related data (e.g., settings, user data, cache). o Modular design: Different parts of the app can manage their data. o Performance optimization: Smaller files are faster to read (but too many files can complicate management). 4. Retrieving Shared Preferences: o By file name: SharedPreferences prefs = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE); o Activity default preferences: SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); 5. Writing to Shared Preferences: o Steps: 1. Create an editor: SharedPreferences.Editor editor = prefs.edit(); 2. Add a new value: 3. editor.putInt("key", value); editor.putString("key", "value"); 4. Save changes: ▪ apply(): Saves the in-memory reference and writes to disk asynchronously. ▪ commit(): Writes to disk synchronously. 6. Reading from Shared Preferences: o Example: o int myInt = prefs.getInt("key", defaultValue); String myString = prefs.getString("key", defaultValue); LECTURE 6 Fragments 1. What are Fragments? o Fragments are portions of the user interface (UI) within an activity. o Promote modularity and reusability. o Allow dynamic changes to the UI at runtime. o Exist within an activity, but fragments have their own lifecycle. 2. Fragment Lifecycle: o Fragments have lifecycle methods similar to activities: ▪ onAttach(), onCreate(), onCreateView(), onStart(), onResume(), onPause(), onStop(), onDestroyView(), onDestroy(), onDetach(). 3. How to Use a Fragment: o Step 1: Create a Fragment Class: ▪ Extend the Fragment class. ▪ Add the layout in the constructor or the onCreateView() method. ▪ Implement lifecycle methods as needed. o Step 2: Add the Fragment to an Activity: ▪ Static Method: ▪ ▪ Define the fragment in the activity’s layout XML using the <fragment> tag. Programmatic Method: ▪ Use the FragmentManager and FragmentTransaction classes in Java/Kotlin. Sensors 1. Overview: o Android sensors can be hardware (e.g., accelerometer, gyroscope) or software (e.g., proximity, gravity). o Used to enhance user interaction and gather environmental data. 2. Sensor Framework Components: o o o o SensorManager: ▪ Access available sensors. ▪ Register/unregister event listeners. ▪ Calibrate sensors. Sensor: ▪ Represents a specific sensor (e.g., accelerometer). ▪ Provides methods to get sensor properties and capabilities. SensorEvent: ▪ Represents an event from a sensor. ▪ Contains raw data, sensor type, accuracy, and timestamp. SensorEventListener: ▪ Interface to create callbacks for sensor events. ▪ Two main callbacks: ▪ onSensorChanged(): Called when the sensor value changes. ▪ onAccuracyChanged(): Called when sensor accuracy changes. 3. How to Interact with a Sensor: o Step 1: Get the SensorManager: SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); o Step 2: Retrieve a Sensor: Sensor accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); o Step 3: Implement Callbacks for SensorEventListener: sensorManager.registerListener(sensorEventListener, accelerometer, SensorManager.SENSOR_DELAY_NORMAL); o Step 4: Register the Listener: ▪ o Done using sensorManager.registerListener(...). Step 5: Unregister the Listener: ▪ Use sensorManager.unregisterListener(...) in lifecycle callbacks (e.g., onPause()). 4. Example Sensor Use Case: o Detect device motion using an accelerometer. o Adjust app behavior based on sensor data (e.g., screen orientation changes). Quizes: Question: Which of these is a method to find a view by its ID in an activity? a. getViewById() b. findById() c. findViewById() (Correct Answer) d. getElementById() Question: How does the LinearLayout arrange its kids? a. Vertically b. Horizontally c. Vertically or horizontally depending on the orientation specified (Correct Answer) d. In a row Question: The button is a: a. Static widget b. Dynamic widget (Correct Answer) Question: What class is the Button class extending? a. View b. TextView (Correct Answer) c. Button and TextView d. None Question: Which XML attribute is used to set the width and height of a view in an Android layout? a. layout_dimensions b. layout_gravity c. layout_width and layout_height (Correct Answer) Question: Why would you use AIDL over simpler service implementations in Android? a. To perform operations within the same application only. b. To enable communication between different applications. (Correct Answer) c. To handle background operations more efficiently than threads. d. To bypass declaring permissions in AndroidManifest.xml. Question: What is a key characteristic of a foreground service? a. It always runs on the main thread. b. It is noticeable to the user through a persistent notification. (Correct Answer) c. It automatically stops when the user closes the app. d. It only works for a fixed duration. Question: Why should long-running operations not be performed on the main thread in Android? a. It might block the user interface, causing an "Application Not Responding" (ANR) error. (Correct Answer) b. The main thread has no memory allocation for heavy operations. c. Android automatically kills the main thread if it takes too long. d. It violates Android's security model. Question: How are drawable resources referenced in Kotlin code? a. Using R.layout.<resource_name> b. Using @drawable/<resource_name> c. Using R.drawable.<resource_name> (Correct Answer) d. Using @layout/<resource_name> How do you start a thread in Android? a. By calling the run() method directly. b. By calling the inherited start() method on a thread object. c. By implementing the Runnable interface without calling start(). d. By declaring the thread in AndroidManifest.xml. What is the operating system that lays underneath Android? a. Ubuntu b. Linux c. None d. Windows Are you allowed to call parent functions when extending classes? a. Yes b. No When are lifecycle callbacks triggered? a. After entering the state b. Before entering the state Which one is not amongst Android's main components? a. All of the above are main components b. Notification c. Content Provider d. Service What is the file format used by Dalvik? a. .exe b. .d c. .class d. .dex