CS710 — Final Term Summary (Lectures 23–44)
📘 Lecture 23 — Mobile & Pervasive Computing
📖 Overview: This lecture continues the exploration of Windows Phone 7 operating system architecture, focusing on version history updates, the structural building blocks of the OS, and the file system organization that supports system and user data management. Understanding this structure is critical for mobile application developers and system architects.
🗂️ Topics Covered
The lecture covers the version history of Windows Phone 7, including key updates like "NoDo" and "Mango". It then explains the structure of the operating system at the building level, detailing how different layers interact. Finally, it describes the file system architecture, specifically IMGFS, TexFAT, and the Microsoft Unified Storage System for user data.
📝 Lecture Summary
Version History
Windows Phone 7 underwent several version updates during its lifecycle. The original RTM (Release to Manufacturing) version was 7.0.7004.0. An intermediate test update, 7.0.7008.0, contained no functionality changes. New phones shipped with version 7.0.7389.0, which included all features of OS version 7.0.7390.0. The "NoDo" update (7.0.7390.0) introduced copy/paste functionality, performance improvements, and market search enhancements. The major "Mango" update added third-party multitasking, Internet Explorer 9 (IE9), and Twitter integration, among other features.
💡 Why this matters: Knowing the version history helps developers understand which API features are available on different devices and why certain updates were critical for the ecosystem's evolution.
Structure of the OS – Building
The lecture presents structural diagrams showing how the Windows Phone 7 operating system is built. The OS architecture includes multiple layers:
- Hardware at the bottom
- Kernel layer above hardware
- Core System Services including:
- Graphics subsystem
- Media subsystem
- Communication services
- Security services
- Application Framework layer
- Applications at the top
The structure shows that applications interact with the application framework, which in turn uses core system services that communicate with the kernel and hardware. This layered architecture ensures stability, security, and abstraction of hardware details from application developers.
Structure of the OS – File
Windows Phone 7 uses two file systems: IMGFS (Image File System) and TexFAT (Transactional Extended File Allocation Table).
- IMGFS is intended for system files, containing the operating system image.
- TexFAT is an 'extended' version of FAT that can handle files larger than 4GB.
🔑 Definition — TexFAT: A transactional version of the FAT file system that supports files larger than 4GB and provides transaction-based write operations for data integrity.
For user files, the OS employs the Microsoft Unified Storage System. This system ensures that applications and users cannot distinguish between files stored in internal flash memory and files stored on a memory card. The unified storage abstracts the physical storage media, presenting a single logical view of all user data.
📌 Example: When a user saves a photo on a Windows Phone 7 device, the Microsoft Unified Storage System automatically determines whether to store it in internal flash memory or on an external SD card. The user and applications see only one unified file system location, regardless of the physical storage medium used.
⭐ Key Takeaways
The critical points from Lecture 23 include the version history of Windows Phone 7, with "NoDo" and "Mango" being the most significant updates. The OS uses a layered architecture with hardware, kernel, core services, application framework, and application layers. Two file systems exist: IMGFS for system files and TexFAT for user and large files. The Microsoft Unified Storage System makes internal and external storage indistinguishable to applications and users. Understanding this structure is essential for mobile developers creating apps for the Windows Phone 7 platform.
🧠 Quick Revision Questions
- What were the three major version updates for Windows Phone 7 mentioned in the lecture, and which one introduced third-party multitasking?
- Name the two file systems used by Windows Phone 7 and describe their primary purposes.
- What is the function of the Microsoft Unified Storage System in the Windows Phone 7 OS?
- Explain the layered architecture of the Windows Phone 7 OS as shown in the "Structure of the OS – Building" section.
- What file size limitation does TexFAT overcome that standard FAT cannot handle?
📘 Lecture 24 — Structure of the OS – File
📖 Overview: This lecture examines the structure of the Windows Phone 7 operating system, focusing on its file system components (IMGFS and TexFAT) and graphics framework. It covers system requirements and update mechanisms for Windows Phone 7, highlighting differences from desktop Windows systems.
🗂️ Topics Covered
This lecture details the two file systems used in Windows Phone 7: IMGFS for system files and TexFAT for user files larger than 4GB, explaining Microsoft Unified Storage System that merges internal flash and memory card storage. It introduces the graphics architecture with direct hardware access for high-performance rendering, lists hardware requirements for Windows Phone 7 devices, and describes the update mechanism used for system patches and new features.
📝 Lecture Summary
Structure of the OS – File
Windows Phone 7 uses two file systems to manage storage. IMGFS is designed for system files and is not user-accessible. TexFAT is an extended version of the FAT file system that can handle files larger than 4GB, intended for user data. The operating system also employs a Microsoft Unified Storage System, which ensures that applications and users cannot distinguish between files stored in internal flash memory and files on an external memory card.
🔑 Definition — IMGFS: A file system intended for system files only, not user-accessible. 🔑 Definition — TexFAT: An extended version of the FAT file system capable of handling files larger than 4GB. 🔑 Definition — Microsoft Unified Storage System: A system that makes internal flash memory and memory card storage appear as a single unified storage space to applications and users.
Structure of the OS – Graphics
Windows Phone 7 uses a graphics framework that provides direct hardware access for high-performance rendering. The architecture is designed to support smooth animations and touch interactions, leveraging hardware acceleration to ensure responsive user experiences. This approach differs from desktop Windows, where graphics are more abstracted from hardware.
💡 Why this matters: Direct hardware access in mobile graphics ensures that user interface interactions (swipes, taps, animations) remain smooth even with limited mobile processor resources.
Windows 7 – Requirements
Windows Phone 7 imposes specific hardware requirements on devices to ensure consistent performance and user experience. These requirements include minimum specifications for processors, memory, screen resolution, and sensor capabilities. The requirements help guarantee that all Windows Phone 7 devices can run applications and the operating system smoothly.
Windows 7 – Updates
Windows Phone 7 uses a update mechanism to deliver system patches, bug fixes, and new features. Updates are delivered over-the-air (OTA) and are managed by carriers before release. The update system is designed to be minimal and focused, as mobile platforms have limited storage and bandwidth compared to desktop systems.
⭐ Key Takeaways
Students must remember that Windows Phone 7 uses two distinct file systems—IMGFS for system files and TexFAT for large user files—and the Unified Storage System blends internal and external storage. The graphics architecture provides direct hardware access for performance. Hardware requirements ensure consistency across devices, and updates are delivered OTA with carrier approval. These design choices prioritize reliability and performance in a mobile environment.
🧠 Quick Revision Questions
- What are the two file systems used by Windows Phone 7, and what type of files does each handle?
- How does the Microsoft Unified Storage System treat internal flash memory versus a memory card?
- Why does the Windows Phone 7 graphics framework use direct hardware access?
- What is the purpose of hardware requirements for Windows Phone 7 devices?
- How are updates delivered in Windows Phone 7, and who manages their release?
📘 Lecture 25 — Structure of the OS – Building
📖 Overview: This lecture examines the software architecture and framework details of operating systems for mobile and pervasive computing, with a specific focus on the structure required for building Windows 7. It explores how applications are hosted and the runtime environment that supports them, emphasizing the architectural layers and requirements for modern OS construction.
🗂️ Topics Covered
The lecture covers the structure of the operating system during the building phase, detailing the software architecture that underpins Windows 7, including its requirements. It further delves into framework details that define the OS structure, and concludes with a discussion on app hosting and runtime mechanisms that enable application execution within the pervasive computing environment.
📝 Lecture Summary
Structure of the OS – Building
This section introduces the overall concept of constructing an operating system. The building phase involves assembling the core components that form the OS foundation. For Windows 7, specific requirements must be met regarding hardware compatibility, memory management, and system resources to ensure proper operation. The structure defines how different layers interact, from kernel services to user interface components, creating a cohesive platform for application execution.
🔑 Definition — Building Phase: The stage in OS development where the core system components are integrated and configured to meet specified requirements. 📐 Formula: No specific formula provided. 📌 Example: When building Windows 7, the OS requires a minimum of 1GB RAM for 32-bit systems or 2GB for 64-bit systems, with a 1GHz processor and 16GB (32-bit) or 20GB (64-bit) available hard disk space, ensuring the structural components have adequate resources.
💡 Why this matters: Understanding the building requirements helps developers and system architects design compatible hardware and software for pervasive computing environments.
Software Architecture
The software architecture layer describes the high-level organization of the OS into modular components. Windows 7 architecture follows a layered design, separating user-mode processes from kernel-mode services. This architecture includes the hardware abstraction layer (HAL), kernel, executive services, and subsystems that manage I/O, memory, processes, and security. The architecture ensures stability and security by isolating critical system functions from user applications.
🔑 Definition — Software Architecture: The structural organization of an operating system's components and their interrelationships, defining how different modules communicate and cooperate. 📐 Formula: No specific formula provided. 📌 Example: In Windows 7 architecture, the kernel handles thread scheduling and interrupt handling, while the executive services manage memory management, process management, and I/O management, all built upon the HAL that abstracts hardware differences.
Framework Details
This section provides deeper framework details regarding the specific structures and interfaces that implement the architecture. The framework includes programming interfaces like Windows API, device driver frameworks (WDDM for graphics, KMDF/UMDF for drivers), and the Component Object Model (COM) that enables inter-process communication. These details define how developers create software that runs consistently across different hardware configurations.
🔑 Definition — Framework: A structured set of interfaces, tools, and conventions that provide a foundation for developing and running applications within the operating system. 📐 Formula: No specific formula provided. 📌 Example: Windows 7 uses the Windows Driver Framework (WDF) which includes Kernel-Mode Driver Framework (KMDF) for device drivers running in kernel space and User-Mode Driver Framework (UMDF) for drivers running in user space, providing better stability and isolation.
App Hosting and Run Time
The final section discusses how the OS supports application hosting and provides runtime environments for executing programs. This includes the Windows Runtime (WinRT) for modern apps, the Common Language Runtime (CLR) for .NET applications, and the traditional Win32 API for desktop applications. The OS manages process creation, memory allocation, thread scheduling, and resource access during runtime. It also handles application isolation, security enforcement, and inter-process communication.
🔑 Definition — Runtime Environment: The software layer that provides the necessary services and resources for an application to execute, including memory management, exception handling, and security checks. 📐 Formula: No specific formula provided. 📌 Example: When a user launches a .NET application on Windows 7, the Common Language Runtime (CLR) loads the application code, performs just-in-time compilation, manages garbage collection for memory, and ensures type safety and security through code access security policies.
💡 Why this matters: Understanding app hosting and runtime mechanisms is crucial for developing reliable software that runs efficiently across different Windows 7 configurations.
⭐ Key Takeaways
Students must remember that building an operating system like Windows 7 involves understanding specific hardware and software requirements that must be met. The software architecture follows a layered design with the HAL, kernel, and executive services working together to provide stability and security. Framework details such as the Windows API and device driver frameworks are essential for creating compatible software. App hosting and runtime environments like WinRT, CLR, and Win32 provide the necessary infrastructure for application execution, with each runtime offering different capabilities and security models. The building phase requires careful integration of these components to create a cohesive and reliable operating system.
🧠 Quick Revision Questions
- What are the minimum hardware requirements for building Windows 7 (32-bit version)?
- Name three key components of Windows 7's software architecture.
- What is the purpose of the Hardware Abstraction Layer (HAL) in the OS structure?
- Distinguish between KMDF and UMDF in the Windows Driver Framework.
- How does the Common Language Runtime (CLR) manage memory during application hosting?
📘 Lecture 26 — App Hosting and Run Time
📖 Overview: This lecture covers the Windows Phone 7 (WP7) execution model, detailing the various states an application can be in during its lifecycle. It explains how resources are managed during deactivation and activation, which is critical for building responsive and battery-efficient mobile applications.
🗂️ Topics Covered
The lecture explores the WP7 execution model with seven application states: Launch, Running, Closing, Deactivated, Activated, Dormant, and Tombstoned. It then delves into the application life cycle, followed by resource management strategies during deactivation and activation phases, ensuring smooth user experience and efficient system resource usage.
📝 Lecture Summary
WP7 Execution Model
The Windows Phone 7 execution model defines how applications transition through different states during their lifetime. There are seven key states an application can occupy: Launch, Running, Closing, Deactivated, Activated, Dormant, and Tombstoned. When the user launches an app, it enters the Launch state and then moves to Running. If the user presses the Start button or switches to another app, the current app becomes Deactivated. The system may put the app into a Dormant state (preserving memory) or a Tombstoned state (removing it from memory). When the user returns, the app is Activated. Finally, when the user explicitly closes the app, it enters the Closing state.
🔑 Definition — Deactivated: An application state where the app is no longer visible but may still be kept in memory by the system. 🔑 Definition — Dormant: An application state where the app is preserved entirely in memory but is not executing any code. 🔑 Definition — Tombstoned: An application state where the app has been removed from memory, but its state information is saved for potential restoration.
📌 Example: When a user receives a phone call while playing a game, the game becomes Deactivated. If the call is short, the game may remain Dormant in memory; if the call is long and memory is needed, the game becomes Tombstoned. When the call ends and the user returns, the game is Activated from either state.
💡 Why this matters: Proper handling of these states prevents data loss and provides a seamless user experience when switching between apps.
Application Life Cycle
The application life cycle on Windows Phone 7 follows a specific path: the app starts with Launch → then Running → then either Closing (if user exits) or Deactivated (if user leaves). From Deactivated, the app can go to Dormant (memory preserved) or directly to Tombstoned (memory cleared). When the user returns, the app transitions from Dormant/Tombstoned to Activated, then back to Running. This cycle ensures that the system can reclaim resources when needed while maintaining the ability to restore the app's previous state.
📐 Formula: Life Cycle Sequence: Launch → Running → (Closing / Deactivated → [Dormant or Tombstoned] → Activated → Running)
📌 Example: A weather app is Launched → enters Running to show today's forecast → user switches to email → app becomes Deactivated → after 5 minutes, system needs memory → app becomes Tombstoned → user returns to weather app → it is Activated and restores its state.
💡 Why this matters: Understanding this cycle is essential for saving application state correctly in the Deactivated event to avoid data loss.
Deactivation Resource Management
When an application is Deactivated, the system triggers the Deactivated event. During this event, the application must perform resource management tasks such as saving persistent data, releasing unmanaged resources (e.g., file handles, network connections), and saving the current application state (e.g., scroll position, user input). The goal is to free up system resources and ensure the app can be properly restored later. The system provides limited time for this process, so efficient code is required.
🔑 Definition — Resource Management: The process of releasing system resources (memory, file handles, network connections) when an application transitions to a non-running state.
📌 Example: In a drawing app, during the Deactivated event, the app saves the current drawing to isolated storage, closes the file stream, and releases the drawing surface memory. This ensures no data is lost and system resources are freed.
💡 Why this matters: Failing to manage resources during deactivation can lead to data loss and poor system performance when many apps are running.
Activation Resource Management
When an application is Activated (returning from Dormant or Tombstoned state), the system triggers the Activated event. During activation, the application must restore its state from previously saved data, re-establish network connections, reload resources, and reinitialize the user interface to its previous state. If the app was Tombstoned, it must reload its entire state from persistent storage; if it was Dormant, state restoration is faster because memory is still intact.
🔑 Definition — Activation: The process of bringing an application back to the Running state after it was Deactivated, including state restoration.
📌 Example: A social media app that was Tombstoned during a long phone call, upon Activation, re-reads the saved timeline position and user credentials from isolated storage, reconnects to the network, and displays the user's feed exactly where they left off.
💡 Why this matters: Proper activation resource management ensures a seamless user experience, making the app appear to have been running continuously even when it was tombstoned.
⭐ Key Takeaways
The WP7 execution model defines seven application states: Launch, Running, Closing, Deactivated, Activated, Dormant, and Tombstoned. The application life cycle follows a sequence from Launch to Running, then either Closing or Deactivation (which leads to Dormant or Tombstoned), and back through Activation to Running. During Deactivation, applications must perform resource management by saving state, releasing resources, and closing connections. During Activation, applications must restore state, re-establish connections, and reload resources. Students must understand the difference between Dormant (memory preserved) and Tombstoned (memory cleared) to implement proper state-saving logic. The most critical exam concept is handling the Deactivated event to save data and the Activated event to restore it, as this determines app reliability.
🧠 Quick Revision Questions
- What are the seven states in the WP7 execution model?
- What is the difference between Dormant and Tombstoned states?
- What actions must an application perform during the Deactivated event?
- What is the sequence of the application life cycle from Launch to Closing?
- How does resource management differ between activation from Dormant vs. Tombstoned states?
📘 Lecture 27 — Deactivation Resource Management
📖 Overview: This lecture explores the contrast between activation and deactivation approaches to resource management, focusing on content-centric computing challenges and solutions. It introduces structured data handling in the Mango framework, emphasizing how these systems maintain performance while managing power constraints.
🗂️ Topics Covered
The lecture covers Activation vs Deactivation Resource Management approaches, Content Centric Experience challenges and working mechanisms, Structured Data concepts and IO Performance considerations, and Structured Data implementation in the Mango framework.
📝 Lecture Summary
Activation Resource Management
This section covers the activation-based approach where resources are allocated and activated as needed by applications. The system proactively manages resources by anticipating demand and keeping components ready for immediate use. This approach prioritizes responsiveness over power efficiency.
💡 Why this matters: Activation management is common in desktop systems but can waste significant power in mobile devices.
Deactivation Resource Management
Deactivation resource management takes the opposite approach — resources are deactivated or put into low-power states by default, and only activated when explicitly required. This conservative strategy prioritizes power conservation over immediate responsiveness, making it more suitable for mobile and pervasive computing environments where battery life is critical.
🔑 Definition — Deactivation Resource Management: A resource management strategy where system resources are kept in low-power or inactive states as default, and only activated on demand to minimize energy consumption.
Content Centric Experience: Challenges
The content-centric experience faces several key challenges:
- Data discovery: Finding relevant content across distributed networks
- Content delivery: Ensuring timely delivery while managing network resources
- Caching strategies: Determining what content to cache and for how long
- Power management: Balancing content availability with battery constraints
- Network heterogeneity: Handling varying connectivity conditions
Content Centric Experience: Working
The working mechanism of content-centric systems involves:
- Content naming: Using meaningful names instead of host addresses
- Interest propagation: Broadcasting requests for named content
- Content routing: Forwarding requests to nodes that have the content
- Caching nodes: Intermediate nodes cache popular content for faster future access
- Power-aware scheduling: Deactivating unnecessary network components when idle
Structured Data and IO Performance
Structured data refers to information organized in a predefined format (like tables or records) that enables efficient storage, retrieval, and processing. IO performance in mobile systems is affected by:
- Read/write cycles: Flash memory has limited write endurance
- Access patterns: Sequential vs random access affects speed
- Data fragmentation: Scattered data reduces efficiency
- Cache effectiveness: Proper caching reduces physical IO operations
🔑 Definition — Structured Data: Data organized in a consistent, predictable format (rows, columns, records) that allows systematic access and manipulation.
Structured Data in Mango
Mango implements structured data handling with specific optimizations for mobile environments:
- Schema-based storage: Data organized using predefined schemas for efficient access
- Compression techniques: Reducing data size to minimize IO operations
- Indexing mechanisms: Creating indexes for faster queries without full scans
- Batched operations: Grouping writes to reduce flash wear
- Power-aware transactions: Committing data during active network periods
📐 Formula: IO Performance ≈ (Data Size × Access Frequency) / (Cache Hit Rate × Power Budget)
📌 Example: In Mango, if a contact list with 1000 records is accessed 50 times per day, and caching achieves an 80% hit rate, the physical IO operations are reduced from 50,000 to 10,000 per day, saving 80% of battery consumption.
⭐ Key Takeaways
The fundamental difference between activation and deactivation resource management is that activation prioritizes performance while deactivation prioritizes power savings, making the latter crucial for mobile devices. Content-centric computing addresses challenges of data discovery, caching, and delivery in pervasive networks. Structured data handling significantly improves IO performance by enabling efficient access patterns, indexing, and compression. Mango's implementation shows how batched operations and power-aware transactions can extend battery life while maintaining data integrity. Students must understand that choosing between activation and deactivation strategies depends on the specific application's performance vs power requirements.
🧠 Quick Revision Questions
- What is the primary difference between activation and deactivation resource management?
- List three major challenges in content-centric computing experience.
- How does structured data improve IO performance in mobile systems?
- What optimization techniques does Mango use for structured data handling?
- Why is a 50% cache hit rate significant for power consumption in mobile devices?
📘 Lecture 28 — LINQ to Everything
📖 Overview: This lecture addresses the challenge of querying diverse data sources in mobile applications, including relational databases with complex relationships, static reference data, web service caches, and local user data like contacts and appointments. It introduces the “LINQ to Everything” concept, where Language Integrated Query (LINQ) unifies data access across these varied sources, simplifying development and improving performance.
🗂️ Topics Covered
The lecture covers complex data scenarios with multiple tables and foreign keys, managing huge amounts of static reference data, caching web service data locally, filtering and querying user data (contacts and appointments), and the architecture of local storage code-first development. It also introduces new and updated APIs for accessing user data, including Chooser Tasks and the Microsoft.Phone.UserData namespace.
📝 Lecture Summary
Complex Scenarios
This section introduces the challenge of complex relationships and constraints in mobile databases. The Shopping List example demonstrates a typical mobile app database with 7 tables, hundreds of records, and 5 foreign keys, including tables for Lists, Stores, Categories, ItemReferenceData, ListItems, Favorites, and History. Each table has primary keys (PK) and foreign keys (FK) linking to other tables, such as ListItemId referencing ListId and StoreId. This structure enables persistent storage of user-specific data, like which items are in a list, at which store, and in which category, but requires careful query design to avoid performance issues on resource-constrained mobile devices. 💡 Why this matters: Understanding these relationships is crucial for writing efficient LINQ queries that join multiple tables while minimizing memory and processing overhead.
Huge amounts of static reference data
This topic addresses applications that rely on large, mostly unchanging datasets. The dictionary app example uses 3 tables, with one table containing 500k rows for words and their definitions. The schema includes a Words table with fields like WordId, Word, Pronunciation, Definition, AlternateSpellings, and Origin, linked to a Favorites table (with FavoriteId and AddedDate) via WordId. Static reference data is typically fetched once from a server and cached locally to reduce network calls and improve app responsiveness. LINQ is used to query this local cache efficiently, for example, to search for a word or retrieve all favorite words, without overwhelming the device’s limited memory. 💡 Why this matters: Properly handling large static datasets is essential for apps like dictionaries, encyclopedias, or product catalogs, where offline access and fast search are critical.
Web Services Cache
This section describes a hybrid approach to fetching reference data from the cloud and caching it locally on the device. The Web Services Cache pattern involves: 1) Fetching reference data (e.g., word definitions, product descriptions) from a cloud web service, 2) Storing it in a local database or cache (using SQLite or isolated storage), and 3) Combining it with user-specific data (e.g., user’s favorites, history). The example shows a Words table with web-sourced fields like Pronunciation and Definition, joined with a user-specific Favorites table. This approach ensures fast access to frequently used data while still allowing updates from the cloud when connectivity is available. LINQ queries can seamlessly combine local cache data with real-time web service calls using asynchronous patterns. 💡 Why this matters: This pattern is vital for mobile apps that need to work offline while providing fresh data when online, balancing performance with data freshness.
Users Data
This topic covers querying user-specific local data, such as contacts and appointments. Examples include: filtering contacts to find those with birthdays in the next month, and querying all appointments to find an available time for a meeting. These queries are performed using the Microsoft.Phone.UserData API, which provides read-only access to the phone’s built-in contacts and appointments databases. LINQ is used to filter, sort, and project this data into useful results. For instance, a query might filter contacts by checking if their birthday date falls within a future range, or find appointment slots by comparing start and end times. This data is local and private, so the API enforces security restrictions. 💡 Why this matters: These capabilities enable apps to provide personalized features like birthday reminders, scheduling assistants, and contact-based recommendations without requiring manual data entry.
Local Storage Data – Overview
This section provides an overview of how local storage data is filtered in mobile applications. The associated diagram shows a Filter abstract process that takes raw data (from contacts, appointments, or local databases) and applies criteria to produce filtered results. The key idea is that mobile apps often need to present only a subset of available data to the user due to screen space and performance constraints. LINQ expressions act as the filtering mechanism, allowing developers to write declarative queries (e.g., Where, OrderBy, Select) that are executed against local data stores. This enables efficient data retrieval without loading entire datasets into memory. 💡 Why this matters: Efficient filtering is crucial for responsive mobile UIs, especially when dealing with large contact lists or appointment calendars.
Architecture
This section discusses the architecture of local storage in mobile applications, specifically focusing on Code First Development. The associated diagram illustrates a flow where developers write code (classes and LINQ queries) that generates the local database schema (tables, relationships) at runtime. This is the Code First approach, where the data model is defined in C# or VB.NET code, and the database (e.g., SQL Server Compact Edition or SQLite) is created from that code. The “Code” block includes entity classes (like ListItem, Category) and LINQ queries that define how data is accessed. The “Local Database” block is created automatically based on these classes. This approach simplifies development by eliminating the need for separate database design tools and allows developers to work entirely in their familiar programming language. 💡 Why this matters: Code First development reduces the gap between object-oriented code and relational storage, enhancing productivity and reducing errors in mobile app data layers.
User Data – New and Updated APIs
This topic introduces the new and updated APIs for accessing user data in Windows Phone. It lists Chooser Tasks that allow the user to pick data from the device:
- EmailAddressChooserTask: Prompt user to select an email address from contacts.
- PhoneNumberChooserTask: Prompt user to select a phone number.
- AddressChooserTask: Prompt user to select a physical address.
Additionally, the Microsoft.Phone.UserData namespace provides direct programmatic access to:
- Contacts (e.g., names, numbers, emails)
- Appointments (e.g., dates, subjects, locations)
These APIs enable apps to integrate deeply with user data without building separate input forms. The Chooser Tasks are “launchers” that return the selected data via events. 💡 Why this matters: Using these standard APIs ensures a consistent user experience and leverages the phone’s existing data, reducing development effort and increasing app utility.
Microsoft.Phone.UserData
This section highlights important points about the Microsoft.Phone.UserData namespace:
- Contacts and Appointments APIs are read only – Apps cannot modify or delete contacts or appointments using these APIs; they can only query and read existing data.
- Third party social network data cannot be shared – Data from third-party social networks (e.g., Facebook contacts, Twitter followers) that is integrated into the phone’s contacts list cannot be accessed by other apps due to privacy restrictions.
These restrictions are by design to protect user privacy and data security. Developers must work within these constraints, meaning they cannot create new contacts or sync data back to the cloud without using separate authorizations (e.g., OAuth). 💡 Why this matters: Developers must be aware of these limitations when designing features that depend on user data, and plan for read-only access or alternative data sources.
Contact/Appointment Data Share
This topic likely discusses the concept of sharing contact and appointment data between apps. The lecture suggests that apps can consume contact and appointment data (read-only) but cannot share the raw data with third parties beyond the user’s explicit consent via Chooser Tasks. Data sharing is controlled by the operating system, which enforces per-app permissions. For example, an app can read a contact’s birthday to show a reminder, but it cannot export that birthday to another app without going through share contracts (like ShareTask). The LINQ queries performed against this data are local to the app and do not persist beyond the app’s lifecycle. 💡 Why this matters: Understanding data sharing limitations is essential for building compliant, privacy-respecting mobile apps that work within the platform’s security model.
⭐ Key Takeaways
The most critical concept from this lecture is that LINQ provides a unified query language to access diverse data sources—relational databases with complex schemas (7+ tables, many foreign keys), huge static reference data (500k+ rows), cached web service data, and read-only user data like contacts and appointments. Students must remember that mobile data access requires efficient filtering and caching strategies (e.g., fetching web data only once and storing locally) to optimize performance on resource-constrained devices. The Code First development approach simplifies database creation by generating schemas from code, while APIs like Microsoft.Phone.UserData and Chooser Tasks provide read-only access to personal data with strict privacy protections. Finally, understanding the distinction between static reference data and user-specific data is crucial for designing effective mobile data architectures.
🧠 Quick Revision Questions
- In the Shopping List example, how many tables and foreign keys are involved? What is the purpose of each of the major tables (ListItems, Favorites, History)?
- What is the “Web Services Cache” pattern, and how does LINQ help combine cloud data with local user-specific data?
- Describe two examples of filtering user data using LINQ with contacts and appointments APIs.
- What are the key restrictions of the Microsoft.Phone.UserData namespace regarding read/write access and social network data?
- Explain the Code First development approach and how it generates the local database schema from code.
📘 Lecture 29 — Rethinking Multitasking
📖 Overview: This lecture explores how to rethink multitasking in mobile and pervasive computing environments to enhance user experience (UX). It emphasizes keeping the UX great, getting more out of the phone, and avoiding user waiting times. The lecture provides practical strategies for balancing efficiency with user satisfaction.
🗂️ Topics Covered
The lecture covers three main areas: keeping the UX great through smooth multitasking design, getting more out of the phone by optimizing resource usage, and not keeping users waiting through efficient task management. Each topic is presented with actionable insights for mobile app developers and designers.
📝 Lecture Summary
Rethinking Multitasking
This introductory section sets the stage for rethinking multitasking in mobile computing. Traditional multitasking often degrades UX by causing lag, battery drain, or app crashes. The lecture argues for a new approach that prioritizes user satisfaction over raw performance.
🔑 Definition — Multitasking: The ability of a device to run multiple applications or processes simultaneously, allowing users to switch between tasks quickly. 📐 Formula: Efficiency = (Completed Tasks ÷ Total Time) – User Frustration Index → Maximizing completed tasks while minimizing user frustration 📌 Example: A user switches between a messaging app, a web browser, and a music player. If the music skips when switching apps, UX suffers. Solution: Preload audio buffers and keep music priority high in the system.
Keep the UX Great
This section focuses on maintaining high-quality user experience during multitasking. Key strategies include smooth transitions between apps, predictive resource allocation, and graceful degradation when resources are limited. The goal is to make multitasking feel seamless.
🔑 Definition — Graceful degradation: A design principle where a system continues to function acceptably even when parts of it fail or resources are constrained. 📐 Strategy: Prioritize visible UI elements over background processes → Users see smooth animations even if background tasks slow down. 📌 Example: When a user opens a camera app while streaming video, the video may pause briefly (graceful degradation) instead of crashing the entire device. 💡 Why this matters: Great UX in multitasking builds user trust and reduces frustration, directly impacting app retention.
Get More Out of the Phone
This section discusses optimizing device resources to maximize productivity. Techniques include efficient memory management, battery-aware task scheduling, and offloading heavy tasks to the cloud or specialized hardware (e.g., GPUs, neural engines).
🔑 Definition — Battery-aware task scheduling: A scheduling algorithm that prioritizes tasks based on their energy cost and current battery level to extend device usage time. 📐 Formula: Task Priority = (Task Importance × Expected Battery Cost)⁻¹ → Lower battery cost tasks get higher priority when battery is low 📌 Example: A phone with 15% battery should postpone heavy background syncing (e.g., photo uploads) and prioritize low-energy tasks like checking notifications. 💡 Why this matters: Getting more out of the phone extends usability and improves user satisfaction before needing a recharge.
Don’t Keep Users Waiting
This final section emphasizes minimizing user-perceived latency. Strategies include lazy loading (loading content only when needed), background pre-fetching, and skeleton screens (placeholder UI that shows structure before content loads). The goal is zero visible waiting time.
🔑 Definition — Lazy loading: A design pattern where content is loaded only when it becomes visible or requested by the user, reducing initial load time and memory usage. 📐 Formula: Perceived Wait Time ≤ 100ms for instant feel; ≤ 300ms for acceptable delay 📌 Example: Instead of loading all 100 posts in a social media feed at once, load the first 10 posts instantly, then load next batches as the user scrolls (lazy loading). 💡 Why this matters: Users associate waiting with poor UX and are likely to abandon apps with long load times.
⭐ Key Takeaways
For exams, remember these critical points: (1) Multitasking design must prioritize user experience over raw processing power. (2) Graceful degradation keeps UX acceptable even under resource constraints. (3) Battery-aware scheduling extends device usefulness. (4) Lazy loading and pre-fetching reduce perceived waiting time. (5) The goal is zero user waiting with smooth transitions between tasks.
🧠 Quick Revision Questions
- What is the primary goal of rethinking multitasking in mobile computing?
- How does graceful degradation improve UX during multitasking?
- Explain battery-aware task scheduling and give an example.
- What is lazy loading and how does it reduce perceived waiting time?
- What are the recommended maximum wait times for instant feel and acceptable delay?
📘 Lecture 30 — Windows Phone Harmony
📖 Overview: This lecture examines how Windows Phone rethought multitasking to balance UX performance with system resource optimization. It introduces background agents, their architecture, and how they enable efficient background processing without degrading the user experience.
🗂️ Topics Covered
The lecture covers the philosophy of rethinking multitasking for mobile, the relationship between multitasking and phone health, the concept of agents for getting more out of the phone, the components of multitasking, the end-to-end architecture, and background agent functionality.
📝 Lecture Summary
Rethinking Multitasking
Three core principles guide Windows Phone’s approach to multitasking. First, keep the UX great — the user interface must remain responsive and smooth. Second, get more out of the phone — maximize the device’s capabilities without overloading the system. Third, don’t keep users waiting — background tasks should never cause noticeable delays.
💡 Why this matters: On resource-constrained mobile devices, traditional PC-style multitasking can kill battery life and responsiveness. Windows Phone’s approach sacrifices full background execution for a consistently good user experience.
Multitasking and Phone Health
Managing multitasking is essential for maintaining overall phone health. The OS must continuously balance foreground user activity with background processing to prevent battery drain, memory exhaustion, and CPU overheating. Poor multitasking design leads to sluggish performance and shortened battery life.
Getting more out of the phone: agents
Windows Phone uses agents to handle background work efficiently. These agents monitor resource usage and align with system and user activity. They balance foreground and background processing by triggering processing on demand rather than running continuously. Agents leverage new OS services that provide structured APIs for background tasks.
Multitasking Components
The multitasking system consists of several key components working together:
- Background agents that run periodic or event-driven tasks
- Resource management policies that limit CPU, memory, and network usage for background processes
- Tombstoning — the process of suspending and potentially terminating background apps when memory is needed
- Fast application switching that allows quick return to recently used apps
End to End Architecture
The end-to-end architecture shows how foreground apps and background agents interact through the operating system. The OS acts as a mediator, controlling resource allocation and scheduling. Agents communicate with the OS through well-defined interfaces, and the system decides when to activate, suspend, or terminate each agent based on current phone state and resource availability.
Background Agent Functionality
Background agents have specific capabilities and constraints:
- They can perform periodic tasks (e.g., updating live tiles, fetching new data)
- They have limited execution time and memory budgets
- They cannot run continuously — the OS enforces resource quotas
- Agents must declare their intended usage through manifest files
- The system can defer or cancel agent execution based on battery level, network connectivity, or user activity
⭐ Key Takeaways
Windows Phone prioritized UX responsiveness over unrestricted multitasking, using tombstoning and resource-constrained background agents to balance user experience with system health. Agents monitor resource usage, align with system activity, and process on demand rather than continuously. The end-to-end architecture ensures that background tasks never degrade foreground performance. Developers must design agents within strict time and memory limits. Successful mobile multitasking requires the OS to actively manage resource allocation between foreground and background processes.
🧠 Quick Revision Questions
- What three principles guide Windows Phone’s approach to rethinking multitasking?
- How do background agents differ from traditional PC background processes?
- What is tombstoning and why is it necessary for phone health?
- List two constraints placed on background agents by the OS.
- Explain how the end-to-end architecture balances foreground and background processing.
📘 Lecture 31 — Windows Phone Harmony
📖 Overview: This lecture explores the multitasking architecture of Windows Phone, focusing on how the system monitors resource usage, aligns with system and user activity, and balances foreground and background processing. It explains the end-to-end architecture for background agents, their functionality, and how they enable efficient multitasking while preserving phone health.
🗂️ Topics Covered
The lecture covers Windows Phone multitasking and phone health principles including resource monitoring, foreground-background balance, and processing on demand. It presents the end-to-end architecture of background agents, detailing their functionality and additional features such as periodic and on-idle agents, mutex synchronization, and user control.
📝 Lecture Summary
Multitasking and Phone Health
The system monitors resource usage to ensure efficient operation. It aligns processing with system and user activity patterns. The architecture balances foreground and background tasks intelligently. Processing occurs on demand rather than continuously. New OS services support this multitasking paradigm.
💡 Why this matters: This multitasking approach ensures that background processes do not degrade phone performance or battery life while still enabling necessary background functionality.
End to End Architecture
The lecture presents an end-to-end architecture diagram showing how background agents are integrated into the Windows Phone system. This architecture supports seamless integration between foreground applications and background processing tasks.
Background Agent Functionality
Background agents provide specific functionality that runs when the phone is not actively in use by the user. These agents are designed to perform tasks without interfering with the foreground user experience.
Additional Functionality
Generic Background Agents
- Agents come in two types: – Periodic agents that run at regular intervals – On Idle agents that run when the phone is idle – May have one or both capabilities
- Initialized in foreground, run in background – Agents are set up while the app is active but execute when the app is not in focus
- Persisted across reboots – Agents survive phone restarts without needing reinitialization
- User control through CPL – Users can manage agents through the Control Panel
- Up to a maximum of 18 periodic agents – System enforces this limit to maintain performance
- Synchronize with foreground through mutex – Ensures data consistency between foreground and background processes
- Agent runs for up to 14 days (can be renewed) – Agents have a built-in expiration mechanism to prevent runaway processes
🔑 Definition — Periodic Agent: A type of background agent that runs at scheduled regular intervals to perform tasks.
🔑 Definition — On Idle Agent: A type of background agent that executes when the phone detects it is not being actively used.
🔑 Definition — Mutex: A synchronization primitive that prevents concurrent access to shared resources between foreground and background processes.
📐 Formula: Maximum periodic agents = 18 → The system limits the number of active periodic background agents to 18 to maintain performance and battery life.
📌 Example: A music application initializes a periodic background agent when the user opens the app. The agent is configured to check for new podcasts every hour. The agent persists across phone reboots, and the user can disable it through the Control Panel. The agent runs for 14 days, after which it must be renewed by the user opening the app again. If the user has 18 other periodic agents already running, the system will not allow this new agent to be added.
⭐ Key Takeaways
The Windows Phone multitasking model prioritizes phone health by monitoring resource usage and balancing foreground and background processing on demand. Background agents are the primary mechanism for background tasks, coming in periodic and on-idle varieties. These agents are initialized in the foreground but run in the background, persist across reboots, and are user-controllable through the Control Panel. The system enforces a strict limit of 18 periodic agents and a 14-day maximum runtime per agent. Mutex synchronization ensures data consistency between foreground and background processes without conflicts.
🧠 Quick Revision Questions
- What are the two types of background agents in Windows Phone, and when does each run?
- How does the system ensure data consistency between foreground and background processes?
- What is the maximum number of periodic agents allowed, and why is this limit enforced?
- For how many days can a background agent run before it needs renewal?
- How are background agents persisted, and how can users control them?
📘 Lecture 32 — Generic Background Agents
📖 Overview: This lecture covers background processing capabilities in Windows Phone 7, focusing on how applications can perform tasks while not in the foreground. It explores the security model that governs background behavior, including chambers, capabilities, sandboxing, and application deployment, as well as practical mechanisms like background transfers, audio agents, generic agents, and dormant app states.
🗂️ Topics Covered
Background transfers provide a way to keep users from waiting during data operations. The WP7 security model uses chambers, capabilities, and sandboxing to protect the system. Content sharing enables applications to exchange data. Audio agents and generic agents allow background processing for specific scenarios. Dormant apps and graphics composition manage system resources efficiently.
📝 Lecture Summary
Don’t Keep Users Waiting: Background Transfers
Background transfers allow applications to perform data uploads and downloads without keeping the user waiting. This technique is essential for mobile applications that need to synchronize data or download content while the user interacts with other parts of the app or switches to another application. The system manages these transfers efficiently to maintain responsiveness and battery life.
💡 Why this matters: Without background transfers, users would experience frozen interfaces during data operations, making the application feel unresponsive and poorly designed.
Multitasking Cheat Sheet
The multitasking cheat sheet provides a quick reference for how Windows Phone 7 handles multiple applications running simultaneously. It outlines the limitations and capabilities of background tasks, helping developers understand what operations can continue when an application is not in the foreground.
Services and Frameworks
Windows Phone 7 provides specific services and frameworks that enable background processing while maintaining security and performance. These include APIs for background file transfers, location services, audio playback, and periodic background agents.
🔑 Definition — Background Agent: A component that runs periodically in the background to perform specific tasks such as updating live tiles or checking for new data.
WP7 Security Model
The security model is built around protection requirements that prevent malicious applications from accessing system resources or user data without permission. It uses chambers, capabilities, and sandboxing to enforce security boundaries.
🔑 Definition — Security Model: A framework defining how applications access system resources and user data while protecting against unauthorized access.
Chambers
Chambers are isolated execution environments that restrict what an application can do based on its privilege level. There are four chamber types that provide different levels of access to system resources.
📐 Formula: Chamber Hierarchy → TCB > ERC > SRC > LPC (from highest to lowest privilege)
| Chamber Type | Full Name | Description |
|---|---|---|
| TCB | Trusted Computing Base | Highest privilege level, used by core OS components |
| ERC | Elevated Rights Chamber | For system services requiring elevated access |
| SRC | Standard Rights Chamber | For standard applications with declared capabilities |
| LPC | Least Privileged Chamber | Most restricted, for applications with minimal needs |
📌 Example: An application that needs access to the phone's camera would run in the SRC and declare the camera capability. An application that only needs network access might run in the LPC with just networking capabilities declared.
Capabilities
Each application must disclose its capabilities to users through multiple channels. Capabilities represent the permissions an application needs to access specific features or data on the phone.
🔑 Definition — Capability: A declared permission that an application needs to access a specific system resource or user data.
Capabilities are disclosed in three ways:
- Marketplace listing: Displayed on the application details page in the Windows Phone Marketplace
- Purchase prompt: Explicit prompt upon application purchase for capabilities with legal requirements for explicit disclosure and consent collection
- In-app disclosure: Shown within the application when the user is about to use the location capability for the first time
📌 Example: When a user downloads a mapping application from the Marketplace, they see "This app needs access to your location" on the app details page. During purchase, they see another prompt. When they first use the map feature, a third prompt appears asking "Allow [App Name] to use your location?"
Sandbox
The sandbox is an isolated environment that restricts what applications can do. Every application on Windows Phone 7 runs in its own isolated chamber, defined by the capabilities it declares.
🔑 Definition — Sandbox: An isolated execution environment that prevents applications from accessing resources or data outside their declared capabilities.
Key characteristics:
- Each application runs in its own isolated chamber
- Applications are defined by their declared capabilities
- Third-party applications distributed via the Marketplace cannot remain active in the background
💡 Why this matters: This sandbox model prevents malicious applications from accessing other apps' data or system resources, but it also limits background processing capabilities for most applications.
Application Deployment
Application deployment follows strict security procedures to ensure only trusted applications can be installed on Windows Phone.
Key deployment requirements:
- Developer registration: Developers must register with Microsoft before submitting applications to the Marketplace Hub
- Code signing: All applications are code-signed by VeriSign to verify authenticity
- Managed code only: The development model uses "managed code only" which provides additional security protections
📐 Formula: Security Protection = Least Privilege + Application Isolation + Managed Code + Code Signing
📌 Example: A developer wants to publish a weather app. They must register with Microsoft, develop it using managed code (like C#), ensure minimal capabilities are declared, and have VeriSign sign the application package before it appears in the Marketplace.
Apps, Contents and Isolation
Applications and their contents remain isolated from each other. Each application has its own storage area that other applications cannot access, protecting user data and preventing interference between applications.
Content Sharing for Applications
Content sharing enables applications to exchange data with each other through controlled mechanisms. While applications are isolated, specific APIs allow sharing of content like images, contacts, or files when the user initiates the sharing action.
Getting More Out of the Phone: Audio Agents
Audio agents allow applications to play audio in the background. This is one of the limited background capabilities available to third-party applications, enabling music players, podcasts, and other audio applications to continue playing when the user switches to another app.
Getting More Out of the Phone: Generic Agents
Generic agents are periodic background agents that can run for a limited time to perform specific tasks. These agents run on a schedule determined by the system and have strict time and resource limits to prevent battery drain and performance issues.
🔑 Definition — Generic Agent: A background component that runs periodically to perform tasks like updating live tiles, checking for new data, or synchronizing content.
📌 Example: A news application uses a generic agent to check for new articles every hour. The agent runs for up to 15 seconds, updates the live tile with the latest headline, and then terminates.
Don’t Keep Users Waiting: Dormant Apps
Dormant apps are applications that have been suspended but remain in memory. When the user returns to a dormant app, it can resume quickly without a full restart. This provides a fast user experience while conserving resources.
🔑 Definition — Dormant App: An application that is suspended in memory and can be quickly resumed when the user returns to it.
📌 Example: A user opens a weather app, checks the forecast, then switches to check email. The weather app becomes dormant. When they tap the weather app icon again, it resumes instantly showing the same data without reloading.
Graphics Composition
Graphics composition is the process of combining visual elements from multiple applications on the screen. The system manages how different UI elements from foreground apps, background apps, and system components are layered and displayed together efficiently.
⭐ Key Takeaways
Chambers provide four levels of isolation (TCB, ERC, SRC, LPC) with different privilege levels for applications. Capabilities must be disclosed through three channels: Marketplace listing, purchase prompt, and in-app disclosure (for location). The sandbox model isolates each application in its own chamber, and third-party apps cannot remain active in the background. Application deployment requires developer registration with Microsoft, VeriSign code signing, and managed code development. Background processing is limited to specific scenarios like audio agents, generic agents (periodic, time-limited), and background transfers, with dormant apps providing fast resume capability.
🧠 Quick Revision Questions
- What are the four chamber types in the WP7 security model, and how do their privilege levels compare?
- Through which three channels must applications disclose their capabilities to users?
- Why can't third-party applications distributed through the Marketplace remain active in the background?
- What are the three security requirements for deploying an application in the Windows Phone Marketplace?
- What is the difference between an audio agent and a generic agent in terms of background processing?
📘 Lecture 33 — Research In Motion
📖 Overview: This lecture covers Research In Motion (RIM), the company behind the BlackBerry smartphone, its market growth, development model, application ecosystem, and operating system architecture. It is significant for understanding how a pioneering mobile platform achieved cultural and commercial success through push email and enterprise integration.
🗂️ Topics Covered
The lecture begins with an introduction to Research In Motion and the BlackBerry, its historical roots in pager technology, and wireless email innovation. It then discusses market share statistics and growth rates, the Java ME-based development model with RIM APIs, the application store ecosystem, and the proprietary BlackBerry OS architecture with emphasis on the MIDP wrapper and MDS applications.
📝 Lecture Summary
Research In Motion
BlackBerry and its OS are produced by Research In Motion (RIM), recognized as the cultural icon of the office environment and workforce. RIM is Ontario-based, founded in 1984 by Mike Lazaridis. It entered the wireless market by making pagers, such as the inter@active (RIM-900) for Ericsson, and enabled wireless email on GSM and CDMA networks. RIM released the BlackBerry in 2002.
💡 Why this matters: The BlackBerry's origin in pager technology shaped its focus on reliable, real-time messaging, which became its key differentiator.
Market Share
Actual handset shipment numbers placed BlackBerry closer to 16% market share, with yearly growth of 80% in 2007-08. RIM also offered its push email services to other platforms including Symbian, Windows Mobile, and Palm OS. The company added 1.2 million new users in Q4 2007, and by 2008 the US user base had reached 12 million users. The consumer BlackBerry Internet Service was available in 91 countries worldwide on over 500 mobile service operators using various mobile technologies.
Development Model
BlackBerry applications are written using Java ME. RIM provides a JDE (Java Development Environment) and an Eclipse plug-in. It uses the Mobile Information Device Profile (MIDP), which defines a common interface for low-level features on mobile devices. Users can download and run any application, but code signing is needed for certain functions—though it does not guarantee correct code.
🔑 Definition — MIDP (Mobile Information Device Profile): A specification that defines a common interface for low-level features on mobile devices, enabling Java ME applications to run across different handsets.
🔑 Definition — Code signing: A security mechanism required for certain BlackBerry functions; it authenticates the developer but does not verify the correctness of the code.
Applications
Many popular apps are available for BlackBerry. Users can obtain applications through the web, desktop connect, or the device's IM homepage. In October 2008, RIM announced their own Application Store built directly into the BlackBerry, competing with Apple and Google's app stores. The store offers both free and paid applications.
🔑 Definition — RIM Application Store: A marketplace for BlackBerry applications, announced in October 2008, integrated into the device to compete with Apple's App Store and Google's Android Market.
OS Architecture
The BlackBerry OS is proprietary, with no significant information publicly available. Hardware access is achieved through a RIM-developed JVM (Java Virtual Machine) via two types of applications: standard Java ME applications and MDS (Mobile Data System) applications. Legacy devices supported C++, but no longer do. RIM focuses on building cross-platform functionality with Symbian OS, Windows Mobile, and Desktop Connect. This suggests nothing specific about the underlying OS, with the main focus on the RIM API that wraps MIDP.
🔑 Definition — MDS (Mobile Data System): A RIM-developed framework that provides additional APIs for Java ME applications to access network and device features beyond standard MIDP.
📌 Example: A BlackBerry developer writing a push email client would use the RIM API wrapping MIDP, perhaps utilizing MDS APIs for network access, while the underlying proprietary OS remains hidden from the developer. This allows the app to run across different BlackBerry devices without modification.
⭐ Key Takeaways
The most critical points for exam preparation are: BlackBerry was developed by Research In Motion (RIM), founded in 1984, and evolved from pagers to smartphones with pioneering wireless email on GSM/CDMA. The platform achieved 80% annual growth in 2007-08 and a 16% market share, with push email services extended to other mobile OSes. Applications are developed using Java ME with MIDP, using RIM's JDE or Eclipse plug-in, and require code signing for privileged functions. RIM launched its own Application Store in October 2008 to compete with Apple and Google. The BlackBerry OS is proprietary and undocumented, exposing hardware through a RIM JVM that supports standard Java ME and MDS applications, with the RIM API wrapping MIDP.
🧠 Quick Revision Questions
- What company produces the BlackBerry and its operating system?
- How did RIM's initial product line (pagers) influence the BlackBerry's core feature?
- What was the approximate market share and yearly growth rate of BlackBerry in 2007-08?
- What development environment and Java specification are used for BlackBerry applications?
- Why is code signing required for certain BlackBerry functions, and what does it not guarantee?
📘 Lecture 34 — Development Model
📖 Overview: This lecture explores the BlackBerry mobile platform's development model, architecture, and security framework, then transitions to cover the iPhone platform's history, development tools, and application structure. Understanding these two contrasting approaches to mobile development is essential for comprehending how different platforms solved the challenges of mobile application creation and deployment.
🗂️ Topics Covered
This lecture covers the BlackBerry development model using Java ME with RIM's JDE and Eclipse plug-in, the proprietary BlackBerry OS architecture, network architecture connecting through RIM's central NOC to BES servers, MDS (Mobile Data Services) for web and enterprise applications, application structure with .cod and .alx files, OTA deployment methods, security model with sensitive APIs, and code signing. The lecture then transitions to iPhone history from 1976 Apple founding through iPhone 3G launch, market share data, iPhone development model with SDK and developer program, development tools including Xcode and Interface Builder, Objective-C language features, application framework based on Darwin and XNU kernel, Mach-O binary format, iPhone runtime model with sandboxing, application structure with bundles, MVC design pattern, and memory management using reference counting.
📝 Lecture Summary
Development Model
BlackBerry applications are written using Java ME. RIM provides a Java Development Environment (JDE) and an Eclipse plug-in for development. The Mobile Information Device Profile (MIDP) defines a common interface for low-level features on mobile devices. Users can download and run any application, but code signing is needed for certain functions, though it does not guarantee correct code.
OS Architecture
The BlackBerry OS is proprietary, with no significant information publicly available. Hardware access occurs through a RIM-developed JVM via standard JavaME applications and MDS (Mobile Data System) applications. Legacy devices supported C++, but this is no longer the case. RIM focused on building cross-platform functionality with Symbian-OS, Windows Mobile, and Desktop Connect. The architecture suggests nothing specific about the underlying OS, focusing mainly on the RIM API that wraps MIDP.
Network Architecture
All BlackBerry devices connect to RIM's central NOC (Network Operations Center) through a carrier. The NOC connects to all BES (BlackBerry Enterprise Server) systems on site. BES can attach to additional middleware services for expanded functionality.
💡 Why this matters: This centralized architecture through NOC is what made BlackBerry's push email and enterprise connectivity so reliable and secure, as all data traffic is routed and managed through RIM's infrastructure.
MDS (Mobile Data Services)
MDS focuses mainly on web and enterprise services. It serves as a runtime container for processing pushed data, making it ideal for Rapid Application Development with minimal coding required, sometimes none. BlackBerry enterprise servers perform all the data processing and management, including WSDL and Database operations. The backend can be arbitrarily complex.
Application Structure
JavaME applications like MIDlets contain .jar and .jad files. These are converted to proprietary .cod files for BlackBerry, which are compiled code that is optionally signed and preverified. The Rapc tool converts .jar/.jad files to .cod files. .alx files are used to load applications via the BlackBerry Desktop Manager software and are XML-based BlackBerry application descriptors.
Over the Air (OTA) Deployment
Standard MIDlets and .cod files can be obtained over the air (OTA). The provider puts both a .jad file and either a .cod or a .jar file. Users select the .jad file from a browser. The MDS server provides a built-in transcoder that converts .jar files into .cod files during deployment.
MDS Applications
MDS applications are the simplest to develop on the client side, though they can be arbitrarily complex on the server end. They are considered "Browser Based," essentially laying out HTML forms where all data is received in expected form. These can be developed into browse-able pages using cHTML. The MDS Server defines a WSDL or SQL-DB Schema, and MDS uses standard wrappers to call these accessors. MDS apps use compression and encryption features to securely send data through cell carriers.
Security Model in Brief
The BlackBerry security model includes class files being verified for interface compliance, a limited API set (CLDC), downloading and management within the JVM, no user-defined class loaders, no Java Native Interface or user extensions, and system classes cannot be overridden.
Sensitive APIs
Use of the BlackBerry and RIM API is restricted, tracked for security and export reasons, and not available in the simulator. The JVM checks for valid code signatures. Developers send code hashes to a webservice and receive a RIM-signed signature. Verification occurs at both link time and runtime.
🔑 Definition — Code Signing: A security mechanism where developers submit code hashes to RIM to receive a signed signature that is verified by the JVM at link time and runtime before sensitive APIs can be accessed.
Company History
Apple Computer, Inc. was founded on April 1, 1976 with the Apple I. Products included Apple II, Apple III, and Lisa. In 1984, the Macintosh introduced the mouse and GUI, establishing Apple's "ease of use" philosophy. In 1998, the iMac was designed by Jony Ive, who also designed the iPod and iPhone.
iPhone History
In 1999, Apple began registering trademarks and domain names including iPhone.org. In 2004, Apple and Motorola worked on a phone with iTunes. September 7, 2005 saw the release of the ROKR. On January 9, 2007, the iPhone was announced, and Apple Computer, Inc. became Apple, Inc. The iPhone launched June 29, 2007. On March 6, 2008, the SDK was released; before that, only web applications were available. July 11, 2008 brought the iPhone 3G and the AppStore.
Market Share and Predictions
iPhone had 12.9% market share in Q3 2008, up from 3.4% one year earlier, ranking 3rd after Symbian (49.8%) and RIM (15.9%). In Q4 2008, 6.9 million units were sold, compared to 1.1 million one year earlier. Predictions estimated 45 million total in 2009. By the end of fiscal year 2010, 73.5 million iPhones were sold total. By 2010/2011, the iPhone had barely 4% market share of all cellphones, but Apple still pulled in more than 50% of the total profit from global cellphone sales.
Development Model
A free (with registration) SDK is available, requiring an Intel-based Mac. The SDK allows code development and testing, including a simulator for the iPhone. However, loading code onto an actual iPhone requires joining the iPhone Developer Program.
iPhone Developers Program
The iPhone Developer Program allows developers to load applications on the iPhone and publish applications in the AppStore. Developers set the price, which can be free, with a minimum price of $0.99 and maximum price of $999. Apple takes 30% of application cost for each copy sold. Three different "levels" exist for the developer program.
Development Tools
The SDK is based around Xcode, which is used to develop Mac OS X, iPhone OS, and Apple applications. Other included utilities are Instruments for real-time code profiling, Dashcode for rapid development of widgets and web apps for iPhone, Simulator for testing, and Interface Builder for drag-and-drop interface creation.
iPhone Applications
iPhone applications are written in Objective-C, a superset of C. It is described as "another object-oriented C-like language" with SmallTalk influence, where "messages" are sent to objects following an event-driven model. Even though the SDK is available, Apple does not release all API information; things like CoverFlow and certain hardware APIs are not published.
Applications
The AppStore provides over 20,000 different applications requiring Apple approval to be published. A wide variety of applications are available, from games and social networking to finance and business.
Application Framework
The OS Architecture is based on Darwin, which is open source with a BSD-like system maintained by Apple and the community. Three different "variants" exist: PowerPC and Intel x86 for Mac OS X (released as open source), and ARM for iPhone OS (not released).
Darwin
The Darwin kernel is XNU, a hybrid kernel based on the Mach 3 microkernel and various FreeBSD components. It features an object-oriented device driver framework/API called I/O Kit. The binary format is Mach-O, similar to ELF, a.out, EXE, and COM formats.
🔑 Definition — Mach-O: A binary format that can contain binary code for multiple CPU architectures, known as a "Universal Binary," enabling seamless transition between architectures.
Mach-O
A Mach-O file can contain binary code for multiple CPU architectures, for example, 32-bit (G4) and 64-bit (G5) PowerPC along with Intel x86. This is known as a "Universal Binary" enabling seamless transition between architectures. Rosetta was used during the PowerPC to Intel switch for compatibility.
iPhone Runtime
The iPhone runtime model differs from PCs with short ("bursty") usage and a single foreground application. Currently no "background" processes are allowed for 3rd party app developers. Apple has released guidelines on writing applications that fit this usage model. The app is notified of pending termination and advised to save state. Applications are sandboxed, running in their own virtual address space. No swapping is done; instead, an event is sent to the app to notify it to free some memory. If more memory is still needed, the application can be killed by the OS.
💡 Why this matters: The sandboxing and single-foreground-app model prioritizes security and battery life over multitasking, which was a deliberate design choice for the iPhone that shaped how all iOS apps behave.
Application Structure
iPhone applications are distributed in a bundle containing an executable file, png files, .nib files, Info.plist, and .lproj files for localization.
Application Lifecycle
Applications are based on event handling for their lifecycle management.
MVC Design Pattern
The MVC (Model-View-Controller) design pattern separates an application into three components: View for the user interface, Model for the engine/data, and Controller as the link between the two.
Objective-C
Objective-C is an object-oriented superset of C, different from C++. It includes some nice features like automatic generation of setters and getters according to properties. It has some difficulties related to the message-passing system.
Memory Management
The iPhone has no garbage collector. Instead, it uses reference counting with methods including Alloc, Release, Retain, Autorelease, and copy.
📐 Formula: Reference Counting → Objects track how many references point to them; when the count reaches zero, the object is deallocated
📌 Example: When a developer creates an object using alloc, its reference count becomes 1. Each retain call increments the count, and each release call decrements it. When the count reaches 0, the object is automatically deallocated. autorelease defers the release to a later point, while copy creates a new object with a reference count of 1.
⭐ Key Takeaways
This lecture contrasts two major mobile platforms: BlackBerry's Java ME-based development with centralized NOC/BES architecture, MDS services, and code signing security, versus Apple's iPhone with Objective-C development, Xcode tools, Mach-O universal binaries, sandboxed runtime with no background processes, MVC design pattern, and reference-counted memory management. The critical distinctions include BlackBerry's enterprise-focused proprietary OS with OTA deployment of .cod files compared to iPhone's consumer-focused AppStore model with Apple approval and revenue sharing. Both platforms emphasize security differently: BlackBerry through code signing and JVM verification, while iPhone uses sandboxing and restricted API access. Understanding the iPhone's market disruption—from 3.4% to 12.9% market share in one year and 50% of industry profit with only 4% market share—highlights the platform's disproportionate financial success. The architectural differences in runtime behavior (bursty usage vs. constant connectivity), memory management (reference counting vs. no garbage collection), and development models (MIDP/Java ME vs. Objective-C/SDK) represent fundamental design decisions that shaped modern mobile computing.
🧠 Quick Revision Questions
- What are the three main application types for BlackBerry development, and how do they differ in complexity between client and server sides?
- Explain the purpose of the NOC (Network Operations Center) in BlackBerry's network architecture and how it connects to BES servers.
- What is a "Universal Binary" in Mach-O format, and how does it enable multi-architecture support?
- Describe the iPhone runtime model's memory management approach: why is there no garbage collector, and how does reference counting work?
- Compare the BlackBerry code signing process with the iPhone's AppStore approval model—what security mechanisms does each platform employ?
📘 Lecture 35 — Frameworks and APIs
📖 Overview: This lecture explores the architectural layers and frameworks of iPhone OS (iOS), including its core system layers, media frameworks, and the Cocoa Touch UI layer. It also covers system protection mechanisms like sandboxing and code signing, the controversial topics of jailbreaking and SIM unlocking, and provides a comprehensive introduction to the Android development framework, including the Dalvik Virtual Machine and SDK setup.
🗂️ Topics Covered
The lecture covers the iPhone OS layered architecture (Core OS, Cross Layer Services, Media, Cocoa Touch), undocumented APIs, system protection through sandboxing and code signing, jailbreaking and its vulnerabilities, SIM unlocking, the Android development framework with Dalvik VM, Android SDK components, development environment setup, creating an Android Virtual Device (AVD), and building the first Android application.
📝 Lecture Summary
iPhone OS based on a layered architecture
The iPhone OS is structured with four basic layers: Core OS Layer, Cross Layer Services, Media Layer, and Cocoa Touch Layer. Each layer provides specific functionalities and APIs for application development.
Core OS Layer
This foundational layer contains three basic frameworks:
- CFNetwork — APIs related to networking including sockets, FTP, HTTP, and Bonjour.
- Security — Handles certificate management, random number generation, and crypto-related functions.
- System — Provides BSD and POSIX related functions.
🔑 Definition — CFNetwork: A framework providing low-level networking APIs for sockets, FTP, HTTP, and Bonjour services.
Cross Layer Services
These services operate across multiple layers and include:
- Address Book — Contact information used by SMS and Phone applications.
- Core Foundation — Access to basic data structures like strings and other basic system functions.
- Core Location — Location-based information providing GPS access.
- Foundation — Base for all Objective-C objects including root NSObject class, NSString, and NSArray.
- System Configuration — Manages system configuration settings.
🔑 Definition — Core Foundation: A framework providing access to fundamental data structures and system functions, forming the base for Objective-C object management.
Media Layer
Includes multiple frameworks for multimedia handling: Audio Toolbox, Audio Unit, AV Foundation, Core Audio, Core Graphics, Media Player, OpenGL ES, and Quartz Core.
💡 Why this matters: The Media Layer provides all the audio, video, and graphics rendering capabilities essential for creating rich multimedia applications on iOS.
Cocoa Touch Layer
This top layer provides user interface components:
- Address Book UI — User interface for the Address Book.
- UIKit — Contains all user interface components for building iOS applications.
Undocumented APIs
Not all APIs are documented. Examples include CoverFlow and hardware APIs like the proximity sensor. Using undocumented APIs is a reason for application rejection from the AppStore. However, Google uses such APIs in their voice search application and was accepted into the AppStore. Notably, Eric Schmidt (CEO, Google) sat on Apple’s board of directors during this time.
🔑 Definition — Undocumented APIs: Private or non-public APIs that developers are not officially allowed to use, with usage risking AppStore rejection.
System Protection
iOS employs multiple protection mechanisms:
- Sandboxed applications — Each app runs in its own sandboxed environment.
- Code signing — Applications must be signed by Apple. Developer’s certificates are signed with Apple’s root certificate for development and testing. Code is reviewed by Apple before publication in the App Store. The review process is a mystery but seems thorough. Jailbreaking circumvents this protection.
🔑 Definition — Sandboxing: A security mechanism where each application runs in an isolated environment, preventing access to other apps' data or system resources.
JailBreaking
Two firmwares can be modified with different results:
- Application processor firmware modification — Allows unsigned code to run (applications from outside the AppStore). This is actual jailbreaking.
- Baseband processor firmware modification — Allows carriers other than the intended one. This is SIM unlocking.
Similar to other OSes, the iPhone OS loads in stages:
- Boot ROM loads the LLB (Low-Level Bootloader)
- LLB loads the Firmware
- At each stage, signature checks perform validation
In theory, signature checks occur at every stage, but the boot ROM does not perform a signature check on the LLB — a security flaw. More recently, the LLB is subject to a buffer overflow vulnerability that allows unsigned code to be loaded, overriding the signature checks of all subsequent stages.
🔑 Definition — Jailbreaking: The process of modifying the application processor firmware to allow unsigned code to run on iOS devices, circumventing Apple's security measures.
📌 Example: The boot ROM does not verify LLB signatures, creating a vulnerability where unsigned code can be loaded early in the boot process, bypassing all later security checks.
SIM Unlocking
Jailbreaking is only half the battle. Users remain tied to a specific carrier. Furthermore, jailbreaking can lead to more vulnerabilities.
🔑 Definition — SIM Unlocking: Modifying the baseband processor firmware to allow the device to work with carriers other than the intended one.
Android Development Framework
Android applications are written with Java as the programming language but executed by a custom virtual machine called Dalvik rather than a traditional Java VM. Each Android application runs in a separate process within its own Dalvik instance, relinquishing all responsibility for memory and process management to the Android run time, which stops and kills processes as necessary to manage resources. Dalvik and the Android run time sit on top of a Linux kernel that handles low-level hardware interaction, including drivers and memory management, while a set of APIs provides access to all the underlying services, features, and hardware.
🔑 Definition — Dalvik Virtual Machine: The custom virtual machine used by Android to execute Java applications, optimized for mobile devices with limited resources.
Dalvik Virtual Machine
One of the key elements of Android is the Dalvik virtual machine. The Dalvik VM uses the device’s underlying Linux kernel to handle low-level functionality including security, threading, and process and memory management. It’s also possible to write C/C++ applications that run directly on the underlying Linux OS.
Android Software Development Kit (SDK)
The Android SDK includes everything needed to start developing, testing, and debugging Android applications:
- The Android APIs
- Development Tools
- Android Virtual Device Manager and Emulator
- Full Documentation
- Sample Code
🔑 Definition — Android SDK: A comprehensive software development kit providing APIs, tools, emulators, documentation, and sample code for building Android applications.
Application Development Environment
Required components:
- Android SDK
- The Java development kit
- IDE of Choice — Eclipse
- Versions of the SDK, Java, and Eclipse are available for Windows, MacOS, and Linux
Setting Up the Environment
Steps to set up:
- Download Eclipse
- Download ADT from https://dl-ssl.google.com/android/eclipse/
Create an AVD
An Android Virtual Device can be configured with various parameters:
- Maximum virtual machine heap size
- Screen pixel density
- SD Card support
- The existence of DPad, touchscreen, keyboard, and trackball hardware
- Accelerometer and GPS support
- Available device memory
- Camera hardware (and resolution)
🔑 Definition — Android Virtual Device (AVD): A virtual device configuration used with the Android emulator to simulate specific hardware configurations for testing applications.
Emulator
The Android emulator allows developers to run and test applications on virtual devices without physical hardware.
Creating First Android Application
The lecture concludes by showing the initial steps for creating the first Android application using the configured development environment.
⭐ Key Takeaways
The iPhone OS architecture consists of four layers (Core OS, Cross Layer Services, Media, Cocoa Touch) with specific frameworks like CFNetwork and UIKit. System protection through sandboxing and code signing creates a secure but restrictive environment, leading to jailbreaking that exploits boot chain vulnerabilities like the missing LLB signature check. Android differs fundamentally by using the Dalvik VM on top of a Linux kernel, with each app running in its own process and memory managed by the runtime. Setting up Android development requires the SDK, JDK, and Eclipse IDE with ADT plugin, allowing creation of AVDs with configurable hardware parameters. Understanding these frameworks and APIs is essential for developing applications on both iOS and Android platforms.
🧠 Quick Revision Questions
- What are the four basic layers of the iPhone OS architecture?
- Why does the boot ROM's failure to check the LLB signature create a security vulnerability?
- What is the difference between jailbreaking and SIM unlocking?
- How does the Dalvik Virtual Machine differ from a traditional Java Virtual Machine in Android?
- What components are needed to set up an Android development environment, and what is the purpose of an AVD?
📘 Lecture 36 — Android Development Framework
📖 Overview: This lecture introduces the Android Development Framework, covering the Dalvik Virtual Machine, the Android SDK, and the foundational components of Android applications. It also provides a comparative look at "Hello World" implementations for Android, BlackBerry, and Windows Phone 7, and explains key building blocks like Activities, Services, and the Application Manifest.
🗂️ Topics Covered
The lecture covers the Android development environment, including the Dalvik Virtual Machine and the Android SDK. It details the "Hello World" application in Android, BlackBerry, and WP7 styles, and then explores the types of Android applications and their core building blocks. Finally, it explains the Application Manifest and introduces Location Based Services with necessary permissions.
📝 Lecture Summary
Android Development Framework
Android applications are written in Java but are executed by a custom virtual machine called Dalvik, not a traditional Java VM. Each Android application runs in its own process within its own Dalvik instance, with the Android runtime managing memory and process, stopping or killing processes as needed for resource management.
Dalvik Virtual Machine
The Dalvik VM is a key element of Android. It utilizes the device’s underlying Linux kernel to handle low-level functions like security, threading, and process and memory management. It is also possible to write C/C++ applications that run directly on the underlying Linux OS.
Android Software Development Kit (SDK)
The Android SDK includes all necessary tools to start developing, testing, and debugging Android applications. It contains:
- The Android APIs
- Development Tools
- Android Virtual Device Manager and Emulator
- Full Documentation
- Sample Code
Application Development Environment
The required environment includes the Android SDK, the Java Development Kit (JDK), and an IDE of choice, such as Eclipse. Versions of the SDK, Java, and Eclipse are available for Windows, macOS, and Linux.
Hello World – Android Style
package com.example.helloworld;
import android.app.Activity;
import android.os.Bundle;
public class HelloWorld extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
Views
To display a user interface, the onCreate method must call setContentView(). This defines the UI layout for the activity.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
Defining UI – XML Way
UI layout can be defined in an XML file, such as main.xml, which is created by the Android project template.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, HelloWorld" />
</LinearLayout>
Defining UI – Coding Way
UI can also be defined programmatically in Java code.
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloAndroid extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("Hello, Android");
setContentView(tv);
}
}
Hello World – BlackBerry Style
The development environment for BlackBerry includes:
- Sun JDK
- Eclipse SDK
- BlackBerry JDE Plug-in for Eclipse
- BlackBerry JDE Component Packs 4.3 – 4.7
Here is the main application class:
package com.rim.samples.helloworld;
import net.rim.device.api.ui.UiApplication;
public class HelloWorld extends UiApplication {
public static void main(String[] args) {
HelloWorld theApp = new HelloWorld();
theApp.enterEventDispatcher();
}
public HelloWorld() {
pushScreen(new HelloWorldScreen());
}
}
Here is the application screen class:
final class HelloWorldScreen extends MainScreen {
public HelloWorldScreen() {
super();
LabelField title = new LabelField("HelloWorld Sample",
LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH);
setTitle(title);
add(new RichTextField("Hello World!"));
}
public boolean onClose() {
Dialog.alert("Goodbye!");
System.exit(0);
return true;
}
}
Hello World – WP7 Style
The environment for Windows Phone 7 (WP7) uses Microsoft Visual Studio and Windows Phone Developer Tools, which include:
- Windows Phone SDK 7.1
- Visual Studio 2010 Express for Windows Phone
- Windows Phone Emulator Resources
- Silverlight 4 Tools For Visual Studio
- XNA Game Studio 4.0
- Microsoft Expression Blend for Windows Phone
XAML is used for UI definition.
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
</Grid>
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" Name="MessageTextBox" FontSize="{StaticResource PhoneFontSizeExtraLarge}" Margin="20,20,10,20"/>
<Button Grid.Column="1" Name="ClickMeButton" Content="Click Me"
HorizontalAlignment="Right" Padding="4" Margin="10,20,20,20" />
</Grid>
<Grid Grid.Row="2">
<TextBlock Name="BannerTextBlock" Style="{StaticResource PhoneTextExtraLargeStyle}"
Foreground="#FFFF9A00" HorizontalAlignment="Stretch"
TextWrapping="Wrap" TextAlignment="Center" FontWeight="Bold" />
</Grid>
</Grid>
C# is used for event handling.
private void ClickMeButton_Click(object sender, RoutedEventArgs e) {
BannerTextBlock.Text = MessageTextBox.Text;
MessageTextBox.Text = String.Empty;
}
Types of Android Applications
There are four main types of Android applications:
- Foreground: Applications that are visible and directly interact with the user.
- Background: Applications that run without a direct user interface.
- Intermittent: Applications that run in the background but perform tasks at regular intervals or in response to events.
- Widget: Small, focused applications that run on the home screen.
Building Blocks of Android App
The fundamental components of an Android application are:
- Activities: Represent a single screen with a user interface.
- Services: Run in the background to perform long-running operations.
- Content Providers: Manage a shared set of application data.
- Intents: A messaging object used to request an action from another app component.
- Broadcast Receivers: Respond to system-wide broadcast announcements.
- Widgets: Small application views that can be embedded in other applications (like the home screen).
- Notifications: A way to alert the user of events without stealing focus.
Application Manifest
The AndroidManifest.xml file is essential for every Android application and declares its components, permissions, and features.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.my_domain.my_app"
android:versionCode="1"
android:versionName="0.9 Beta">
</manifest>
It includes nodes to define SDK versions, hardware configurations, and features.
<uses-sdk android:minSdkVersion="4"
android:targetSdkVersion="5">
</uses-sdk>
<uses-configuration android:reqTouchScreen="finger"
android:reqNavigation="trackball"
android:reqHardKeyboard="true"
android:reqKeyboardType="qwerty"/>
<uses-feature android:glEsVersion="0x00010001"
android:name="android.hardware.camera" />
<supports-screens android:smallScreens="false"
android:normalScreens="true"
android:largeScreens="true"
android:anyDensity="false" />
The <application> node declares the application's icon, theme, and name.
<application android:icon="@drawable/icon"
android:theme="@style/my_theme"
android:name="MyApplication"
android:debuggable="true">
</application>
All application components (Activities, Services, etc.) are declared within the <application> node.
<activity android:name=".MyActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:enabled="true" android:name=".MyService"></service>
<provider android:permission="com.paad.MY_PERMISSION"
android:name=".MyContentProvider"
android:enabled="true"
android:authorities="com.paad.myapp.MyContentProvider">
</provider>
<receiver android:enabled="true"
android:label="My Intent Receiver"
android:name=".MyIntentReceiver">
</receiver>
To use a system feature (like location), the manifest must include the appropriate permission.
<uses-permission android:name="android.permission.ACCESS_LOCATION"/>
Location Based Services
An application can get GPS coordinates using the LocationManager system service. However, the emulator does not have GPS sensors and must be seeded with GPS coordinates for testing.
import android.location.Location;
import android.location.LocationManager;
...
public void getLocation() {
try {
LocationManager locMgr = (LocationManager)
getSystemService(LOCATION_SERVICE);
Location recentLoc = locMgr.
getLastKnownLocation(LocationManager.GPS_PROVIDER);
Log.i(DEBUG_TAG, "loc: " + recentLoc.toString());
}
catch (Exception e) {
Log.e(DEBUG_TAG, "Location failed", e);
}
}
💡 Why this matters: Without permissions, the application will fail or crash. The emulator cannot provide real GPS data, so testing location features requires manual simulation.
Manifest Permissions
The following are some common permissions declared in the AndroidManifest.xml:
- ACCESS_MOCK_LOCATION: Allows an application to create mock location providers for testing.
- ACCESS_NETWORK_STATE: Allows applications to access information about networks.
- BATTERY_STATS: Allows an application to collect battery statistics.
- BLUETOOTH: Allows applications to connect to paired bluetooth devices.
- CALL_PHONE: Allows an application to initiate a phone call without user confirmation.
- CAMERA: Required to be able to access the camera device.
- INTERNET: Allows applications to open network sockets.
⭐ Key Takeaways
Android applications run on the Dalvik virtual machine, each in its own process, with the Android runtime managing all resources. The fundamental building blocks of any app are Activities, Services, Content Providers, Intents, Broadcast Receivers, Widgets, and Notifications, all of which must be declared in the AndroidManifest.xml file. The manifest is also where permissions are declared to access protected APIs like the camera or location. For testing location-based features, you must provide mock GPS coordinates to the emulator.
🧠 Quick Revision Questions
- What is the name of the custom virtual machine that executes Android applications, and how does it differ from a traditional Java VM in terms of process management?
- List the four types of Android applications and the seven core building blocks of an Android app.
- If you want an activity to be the main launcher entry point for your application, how must you declare it in the AndroidManifest.xml file?
- What is the main challenge when testing Location Based Services on the Android emulator, and how is it addressed?
- Name three building blocks of an Android application that must be declared in the AndroidManifest.xml, and give one example of a permission you might require for a location-based app.
📘 Lecture 37 — Hello World – WP7 Style
📖 Overview: This lecture introduces the process of creating a Windows Phone 7 (WP7) application using Microsoft Visual Studio 2010 Express for Windows Phone. It guides students through setting up the development environment, understanding the project structure, and building a simple "Hello Phone" application using Silverlight for Windows Phone and XAML markup.
🗂️ Topics Covered
This lecture covers the installation of Windows Phone Developer Tools including Visual Studio 2010 Express, the Windows Phone Emulator, Silverlight 4 Tools, XNA Game Studio 4.0, and Microsoft Expression Blend. It explains how to create a new Windows Phone Application project and reviews the solution structure in Solution Explorer, including key files like App.xaml, MainPage.xaml, ApplicationIcon.png, Background.png, SplashScreenImage.jpg, and manifest files (AppManifest.xml, WMAppManifest.xml). The lecture also demonstrates modifying the XAML markup to add controls (TextBox, Button) and a TextBlock, handling the Click event in C# code-behind, and deploying the application to the Windows Phone Emulator.
📝 Lecture Summary
Microsoft Visual Studio and Windows Phone Developer Tools
The development environment for Windows Phone 7 applications requires installing the Windows Phone Developer Tools. These tools are available at developer.windowsphone.com and include the Windows Phone SDK 7.1, which provides Visual Studio 2010 Express for Windows Phone, the Windows Phone Emulator Resources, Silverlight 4 Tools For Visual Studio, XNA Game Studio 4.0, and Microsoft Expression Blend for Windows Phone.
🔑 Definition — Windows Phone SDK 7.1: A comprehensive software development kit that includes Visual Studio 2010 Express for Windows Phone, emulator resources, Silverlight 4 tools, XNA Game Studio 4.0, and Expression Blend for creating Windows Phone applications.
Creating a New Project
To start developing, navigate to File menu → New Project. In the New Project dialog, select the Silverlight for Windows Phone category under installed templates and choose the Windows Phone Application template. Set the name to HelloPhone, the location to Ex1-CreatingWP7AppsWithVisualStudio in the Source folder, change the solution name to Begin, and click OK.
🔑 Definition — Silverlight for Windows Phone: A subset of Microsoft Silverlight designed specifically for building rich, interactive applications that run on Windows Phone devices.
Solution Structure Review
After creating the project, the Solution Explorer displays the solution structure. Any Visual Studio solution is a container for related projects; in this case, it contains a single Silverlight for Windows Phone project named HelloPhone. The key files include:
- App.xaml / App.xaml.cs: Defines the entry point of the application, initializes application-scoped resources, and displays the application user interface.
- MainPage.xaml / MainPage.xaml.cs: Defines a page with the user interface of the application.
- ApplicationIcon.png: An image file with an icon that represents the application icon in the phone’s application list.
- Background.png: An image file with an icon that represents the application icon in the start screen.
- SplashScreenImage.jpg: This is the image that will first be displayed when the application launches. The splash screen gives the user immediate feedback that the application is launching and will remain displayed until the navigation to the first page has been completed. Your splash screen can look similar to your first page in order to give the appearance that the application is loading quickly.
- Properties\AppManifest.xml: An application manifest file required to generate the application package.
- Properties\AssemblyInfo.cs: Contains the name and version metadata that is embedded into the generated assembly.
- Properties\WMAppManifest.xml: A manifest file that includes specific metadata related to a Windows Phone Silverlight application, including specific features available only for Silverlight for Windows Phone.
- References folder: A list of libraries (assemblies) that provide services and functionality that the application requires to work.
🔑 Definition — SplashScreenImage.jpg: The image displayed immediately when an application launches, providing user feedback that the application is starting. It remains visible until navigation to the first page is complete.
App.xaml and Application-Level Resources
The App.xaml file contains XAML markup with an Application root element and inside it an Application.Resources section. Here you can define application-level resources such as colors, brushes, and style objects used throughout the application. The XAML code also initializes the ApplicationLifetimeObjects property of the Application to create a PhoneApplicationService object. The PhoneApplicationService class provides access to various aspects of the application’s lifetime, including management of the application’s idle behavior and management of the application’s state when it becomes active or inactive.
🔑 Definition — PhoneApplicationService: A class that manages the lifetime of a Windows Phone application, including idle behavior and state management when the application becomes active or inactive.
RootFrame and Navigation
The RootFrame property in the Application class identifies the starting page of the application. All Windows Phone applications have a single top-level container element whose data type is PhoneApplicationFrame. The frame hosts one or more PhoneApplicationPage elements that present content for the application. It also handles navigation between pages. The application code-behind file shows global event handlers.
🔑 Definition — PhoneApplicationFrame: The single top-level container element in a Windows Phone application that hosts PhoneApplicationPage elements and handles page navigation.
MainPage.xaml and XAML Markup
The generated project includes a default document that contains XAML markup defining the main UI of the application, MainPage.xaml. The XAML document provides a blank canvas to which you add controls to create your application’s user interface. Extensible Application Markup Language (XAML) is a declarative language used to define UI elements.
🔑 Definition — Extensible Application Markup Language (XAML): A declarative markup language developed by Microsoft for initializing structured values and objects, particularly used for creating user interfaces in Silverlight and Windows Phone applications.
Application Icon
The ApplicationIcon.png file contains the icon that identifies the application in the quick launch screen of the phone device. You can double-click the item in Solution Explorer to open the file in a registered image editing application on your machine, for example, Paint.exe.
Project Properties
The Windows Phone project properties window allows you to modify some phone-specific properties. These properties relate to the deployment and appearance of the application on the device. The parameters are stored in the WMAppManifest.xml file.
Deployment to Emulator
To test the application, verify that the target of the deployment is the Windows Phone Emulator. Ensure that Windows Phone 7 Emulator is selected in the Select Target drop down next to the Start Debugging button on the toolbar. Press F5 to launch the application in the Windows Phone Emulator. A device emulator window appears, and there is a pause while Visual Studio sets up the emulator environment and deploys the application image. Once ready, the emulator shows the Start page and shortly thereafter, your application appears in the emulator window.
Modifying XAML Markup - Adding Rows and Controls
In the XAML markup generated by the default Windows Phone application template, locate the Grid container element named LayoutRoot. Its purpose is to arrange the elements on the page. Inside its RowDefinition property, insert an additional row between the two existing rows and set the value of its Height property to Auto. This row will soon include a textbox and a button.
🔑 Definition — Grid: A layout control that defines a flexible grid area consisting of columns and rows, used for arranging elements on a page.
The root Grid element contains other nested elements, each assigned to a different row by defining a Grid.Row property. Locate the Grid element named TitlePanel. Set the Text property of the first TextBlock element inside the inner Grid to the string "Windows Phone 7". Similarly, set the Text property of the second TextBlock element to the string "Hello Phone".
The XAML for adding a TextBox and Button to the ContentPanel grid is:
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" Name="MessageTextBox" FontSize="{StaticResource PhoneFontSizeExtraLarge}" Margin="20,20,10,20"/>
<Button Grid.Column="1" Name="ClickMeButton" Content="Click Me" HorizontalAlignment="Right" Padding="4" Margin="10,20,20,20" />
To complete the design of the page, add a third row to contain the banner with the message entered by the user. Insert the following XAML markup immediately before the end tag of the outer grid:
<Grid Grid.Row="2">
<TextBlock Name="BannerTextBlock" Style="{StaticResource PhoneTextExtraLargeStyle}" Foreground="#FFFF9A00" HorizontalAlignment="Stretch" TextWrapping="Wrap" TextAlignment="Center" FontWeight="Bold" />
</Grid>
Creating Event Handlers
Click the button labeled "Click Me" on the designer surface to select it, then press F4 to open its Properties window. In the Properties panel, click the Events tab to display a window with a list of available events. Locate the Click event in this list, then type ClickMeButton_Click in the text box located next to this event. Press ENTER to generate an event handler with this name and open the code-behind file to display the method stub generated by Visual Studio.
🔑 Definition — Click event: An event that occurs when a user clicks a button control, triggering the associated event handler method.
Code-Behind Implementation
The method implementation (initially empty) is in the MainPage.xaml.cs file. Insert the following code inside the body of the ClickMeButton_Click method:
private void ClickMeButton_Click(object sender, RoutedEventArgs e)
{
BannerTextBlock.Text = MessageTextBox.Text;
MessageTextBox.Text = String.Empty;
}
This code assigns the text entered in the MessageTextBox to the BannerTextBlock and then clears the MessageTextBox by setting its Text property to String.Empty.
📐 Formula: BannerTextBlock.Text = MessageTextBox.Text → Copies the user's input from the text box to the banner text block.
MessageTextBox.Text = String.Empty → Clears the input text box after copying.
📌 Example: If a user types "Hello World!" into the MessageTextBox and clicks the "Click Me" button, the BannerTextBlock will display "Hello World!" and the MessageTextBox will be cleared.
💡 Why this matters: This demonstrates the fundamental Model-View-ViewModel (MVVM) pattern in Windows Phone development, where the XAML view handles the UI layout while the C# code-behind manages event-driven logic.
⭐ Key Takeaways
The most critical concepts from this lecture include: understanding the complete Windows Phone SDK 7.1 toolset including Visual Studio 2010 Express, Silverlight 4, XNA Game Studio 4.0, and Expression Blend. You must memorize the structure of a Windows Phone Application project in Solution Explorer, especially the roles of App.xaml (application entry point, resources, and PhoneApplicationService), MainPage.xaml (primary UI page using XAML), and support files like ApplicationIcon.png, Background.png, SplashScreenImage.jpg, and the manifest files (AppManifest.xml and WMAppManifest.xml). The Grid control is the primary layout container, and you must know how to modify its RowDefinitions to organize controls, set Text properties on TextBlock elements, and define ColumnDefinitions for side-by-side placement. Finally, handling the Click event on a Button and manipulating TextBlock.Text and TextBox.Text properties in code-behind is essential for interactive applications. Deployment to the Windows Phone Emulator via F5 is the standard testing workflow.
🧠 Quick Revision Questions
- What are the five main components included in the Windows Phone SDK 7.1?
- Which file in the Windows Phone Application project defines the entry point and application-scoped resources?
- What is the purpose of the SplashScreenImage.jpg file, and when does it disappear?
- How do you add a new row to the LayoutRoot Grid in XAML, and what property defines its height?
- In the ClickMeButton_Click event handler, what two operations are performed on the MessageTextBox and BannerTextBlock?
📘 Lecture 38 — Application Manifest
📖 Overview: This lecture explores the structure and components of the Android Application Manifest file (AndroidManifest.xml), explaining how it defines application metadata, permissions, and hardware requirements. It also introduces Location Based Services (LBS) in Android, including how to obtain GPS coordinates and the necessary permissions, before concluding with the types of Android applications and their building blocks.
🗂️ Topics Covered
The lecture begins with a detailed examination of the AndroidManifest.xml file, covering its root structure and key nodes including uses-sdk, uses-configuration, uses-feature, supports-screens, and the application node with components like activities, services, providers, and receivers. It then introduces Location Based Services, explaining how to seed GPS coordinates in the emulator, retrieve location data using LocationManager, and handle Android logging. The topic of manifest permissions is covered, followed by the types of Android applications (foreground, background, intermittent, widget) and the core building blocks of an Android app, including activities, services, content providers, intents, broadcast receivers, widgets, and notifications.
📝 Lecture Summary
Application Manifest
Each Android project includes a manifest file, AndroidManifest.xml, which defines the structure and metadata of your application, its components, and its requirements. It includes nodes for each of the components (Activities, Services, Content Providers, and Broadcast Receivers) that make up your application and, using Intent Filters and Permissions, determines how they interact with each other and with other applications.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.my_domain.my_app"
android:versionCode="1"
android:versionName="0.9 Beta">
[ ... manifest nodes ... ]
</manifest>
uses-sdk and uses-configuration
The uses-sdk node lets you define a minimum, maximum, and target SDK version that must be available on a device in order for your application to function properly. The uses-configuration nodes specify each combination of input mechanisms supported by your application, such as a device with a finger touchscreen, a trackball, and either a QWERTY or twelve-key hardware keyboard.
<uses-sdk android:minSdkVersion="4"
android:targetSdkVersion="5">
</uses-sdk>
<uses-configuration android:reqTouchScreen="finger"
android:reqNavigation="trackball"
android:reqHardKeyboard="true"
android:reqKeyboardType="qwerty"/>
<uses-configuration android:reqTouchScreen="finger"
android:reqNavigation="trackball"
android:reqHardKeyboard="true"
android:reqKeyboardType="twelvekey"/>
uses-feature and supports-screens
uses-feature nodes specify each of the hardware features your application requires. You can also use the uses-feature node to specify the minimum version of OpenGL required by your application. The supports-screen node lets you specify the screen sizes your application can, and can't, support.
<uses-feature android:glEsVersion="0x00010001"
android:name="android.hardware.camera" />
<supports-screens android:smallScreens="false"
android:normalScreens="true"
android:largeScreens="true"
android:anyDensity="false" />
Application and Activity Nodes
A manifest can contain only one application node. It uses attributes to specify the metadata for your application (including its title, icon, and theme). The <application> node also acts as a container that includes the Activity, Service, Content Provider, and Broadcast Receiver tags used to specify the application components. An activity tag is required for every Activity displayed by your application, using the android:name attribute to specify the Activity class name. Trying to start an Activity that's not defined in the manifest will throw a runtime exception. Each Activity node supports <intent-filter> child tags that specify which Intents launch the Activity.
<application android:icon="@drawable/icon"
android:theme="@style/my_theme"
android:name="MyApplication"
android:debuggable="true">
[ ... application nodes ... ]
</application>
<activity android:name=".MyActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Service, Provider, and Receiver Nodes
As with the activity tag, create a new service tag for each Service class used in your application. Service tags also support <intent-filter> child tags to allow late runtime binding. Provider tags specify each of your application's Content Providers, which are used to manage database access and sharing within and between applications. By adding a receiver tag, you can register a Broadcast Receiver without having to launch your application first. Broadcast Receivers are like global event listeners that, once registered, will execute whenever a matching Intent is broadcast by the system or an application. By registering a Broadcast Receiver in the manifest you can make this process entirely autonomous. If a matching Intent is broadcast, your application will be started automatically and the registered Broadcast Receiver will be run.
<service android:enabled="true" android:name=".MyService"></service>
<provider android:permission="com.paad.MY_PERMISSION"
android:name=".MyContentProvider"
android:enabled="true"
android:authorities="com.paad.myapp.MyContentProvider">
</provider>
<receiver android:enabled="true"
android:label="My Intent Receiver"
android:name=".MyIntentReceiver">
</receiver>
uses-permission
As part of the security model, uses-permission tags declare the permissions you've determined your application needs to operate properly. The permissions you include will be presented to the user before installation commences. Permissions are required for many of the native Android services, particularly those with a cost or security implication (such as dialing, receiving SMS, or using the location-based services).
<uses-permission android:name="android.permission.ACCESS_LOCATION"/>
Location Based Services
Your application knows how to say Hello, but it doesn't know where it's located. Now is a good time to become familiar with some simple location-based calls to get the GPS coordinates. The problem is that the emulator does not have GPS sensors. The emulator does not have location sensors, so the first thing you need to do is seed your emulator with GPS coordinates.
💡 Why this matters: Without seeding GPS coordinates in the emulator, you cannot test location-based features during development.
Steps to seed GPS coordinates:
- Press the Home key to return to the Home screen
- Launch the Maps application from the Application drawer
- Click the Menu button
- Choose the My Location menu item (looks like a target)
- Click the DDMS perspective in the top-right corner of Eclipse
- In the Emulator Control pane (left side), scroll down to Location Controls
- Manually enter the longitude and latitude (note they are in reverse order)
- Click Send
Code for getting location:
import android.location.Location;
import android.location.LocationManager;
....
public void getLocation() {
try {
LocationManager locMgr = (LocationManager)
getSystemService(LOCATION_SERVICE);
Location recentLoc = locMgr.
getLastKnownLocation(LocationManager.GPS_PROVIDER);
Log.i(DEBUG_TAG, "loc: " + recentLoc.toString());
}
catch (Exception e) {
Log.e(DEBUG_TAG, "Location failed", e);
}
}
A new method called getLocation() is added to your class and a call to this method is made in your onCreate() method. The getLocation() method gets the last known location on the phone and logs it as an informational message. If the operation fails for some reason, the method logs an error. Android logging features are in the Log class of the android.util package.
🔑 Definition — Android Logging Levels:
- Log.e() — Log errors
- Log.w() — Log warnings
- Log.i() — Log informational messages
- Log.d() — Log Debug messages
- Log.v() — Log Verbose messages
Your application requires special permissions to access location-based functionality. You must register this permission in your AndroidManifest.xml file.
Steps to add location permissions:
- Double-click the AndroidManifest.xml file
- Switch to the Permissions tab
- Click the Add button and choose Uses Permission
- In the right pane, select
android.permission.ACCESS_FINE_LOCATION(Allows an application to access fine, e.g., GPS, location) - Save the file
ACCESS_COARSE_LOCATION Allows an application to access coarse (e.g., Cell-ID, WiFi) location
Manifest Permissions
Key manifest permissions covered in the lecture include:
- ACCESS_MOCK_LOCATION — Allows an application to create mock location providers for testing
- ACCESS_NETWORK_STATE — Allows applications to access information about networks
- BATTERY_STATS — Allows an application to collect battery statistics
- BLUETOOTH — Allows applications to connect to paired bluetooth devices
- CALL_PHONE — Allows an application to initiate a phone call without going through the Dialer user interface for the user to confirm the call being placed
- CAMERA — Required to be able to access the camera device
- INTERNET — Allows applications to open network sockets
Types of Android Applications
There are four main types of Android applications:
- Foreground: An application that's useful only when it's in the foreground and is effectively suspended when it's not visible. Games and map mashups are common examples.
- Background: An application with limited interaction that, apart from when being configured, spends most of its lifetime hidden. Examples include call screening applications and SMS auto-responders.
- Intermittent: Expects some interactivity but does most of its work in the background. Often these applications will be set up and then run silently, notifying users when appropriate. A common example would be a media player.
- Widget: Some applications are represented only as a home-screen widget.
Building Blocks of Android App
The core building blocks of an Android application are:
-
Activities: Your application's presentation layer. Every screen in your application will be an extension of the Activity class. Activities use Views to form graphical user interfaces that display information and respond to user actions. In terms of desktop development, an Activity is equivalent to a Form.
-
Services: The invisible workers of your application. Service components run in the background, updating your data sources and visible Activities and triggering Notifications. They're used to perform regular processing that needs to continue even when your application's Activities aren't active or visible.
-
Content Providers: Shareable data stores. Content Providers are used to manage and share application databases. They're the preferred means of sharing data across application boundaries. This means that you can configure your own Content Providers to permit access from other applications and use Content Providers exposed by others to access their stored data. Android devices include several native Content Providers that expose useful databases like the media store and contact details.
-
Intents: An inter-application message-passing framework. Using Intents you can broadcast messages system-wide or to a target Activity or Service, stating your intention to have an action performed. The system will then determine the target(s) that will perform any actions as appropriate.
-
Broadcast Receivers: Intent broadcast consumers. If you create and register a Broadcast Receiver, your application can listen for broadcast Intents that match specific filter criteria. Broadcast Receivers will automatically start your application to respond to an incoming Intent, making them perfect for creating event-driven applications.
-
Widgets: Visual application components that can be added to the home screen. A special variation of a Broadcast Receiver, widgets let you create dynamic, interactive application components for users to embed on their home screens.
-
Notifications: A user notification framework. Notifications let you signal users without stealing focus or interrupting their current Activities. They're the preferred technique for getting a user's attention from within a Service or Broadcast Receiver. For example, when a device receives a text message or an incoming call, it alerts you by flashing lights, making sounds, displaying icons, or showing messages.
⭐ Key Takeaways
The AndroidManifest.xml file is the essential configuration file that defines all application components, permissions, and hardware/software requirements. Every Activity, Service, Content Provider, and Broadcast Receiver must be declared in the manifest, with activities requiring intent filters for launching. Location-Based Services require explicit permissions (ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION) declared in the manifest, and the emulator must be seeded with GPS coordinates for testing. Android applications are categorized into foreground, background, intermittent, and widget types, each with distinct usage patterns. The seven core building blocks of Android apps are Activities, Services, Content Providers, Intents, Broadcast Receivers, Widgets, and Notifications, each serving a specific role in creating functional, interactive mobile applications.
🧠 Quick Revision Questions
- What is the purpose of the
uses-configurationnode in the Android manifest, and what input mechanisms can it specify? - Explain the difference between
ACCESS_FINE_LOCATIONandACCESS_COARSE_LOCATIONpermissions. - What happens if you try to start an Activity that is not defined in the AndroidManifest.xml file?
- List and describe the four types of Android applications covered in this lecture.
- What are the seven building blocks of an Android application, and briefly describe the role of each?
📘 Lecture 39 — Activity Life Cycle
📖 Overview: This lecture explains the Android Activity Life Cycle, which defines how activities move through different states from creation to destruction. Understanding this life cycle is critical for developers to manage resources efficiently, handle user interactions properly, and prevent data loss during transitions like screen rotations or incoming calls.
🗂️ Topics Covered
The lecture covers the definition and analogy of an Activity, explains the five states of an activity (Starting, Running, Paused, Stopped, Destroyed), provides a complete code example showing all callback methods (onCreate, onStart, onRestart, onResume, onPause, onStop, onDestroy), and demonstrates the life cycle through LogCat output from various user interactions like pressing Back, Home, or Phone buttons.
📝 Lecture Summary
Activity Life Cycle
An activity is usually a single screen that the user sees on the device at one time. An application typically has multiple activities, and the user flips back and forth among them. Activities are the most visible part of an application. Using a website analogy: just like a website consists of multiple pages, an Android application consists of multiple activities. Just like a website has a "home page," an Android app has a "main" activity — usually the one shown first when you launch the application. Navigation between activities works similarly to web browsing; you can jump from an activity in one application to an activity in a completely separate app. For example, from the Contacts app you could launch the activity to compose a text message in the Messaging application.
The activity life cycle refers to the set of states an activity goes through from creation to destruction, managed by the Activity Manager. The transition from starting state to running state is one of the most expensive operations in terms of computing time and directly affects battery life. This is why Android does not automatically destroy activities that are no longer shown — the user might want to come back to them, so they are kept around for a while.
🔑 Definition — Activity: A single screen that the user sees on the device at one time, typically with which the user can interact.
States of an Activity
Starting state: When an activity doesn't exist in memory, it is in a starting state. While starting up, the activity goes through a whole set of callback methods that developers can implement. Eventually, the activity reaches a running state. This transition is expensive in computing time and affects battery life.
Running state: The activity currently on the screen and interacting with the user. We say this activity is in focus — all user interactions such as typing, touching the screen, and clicking buttons are handled by this one activity. There is only one running activity at any given time. The running activity has priority in getting memory and resources to run as quickly as possible, because Android wants to ensure it is responsive to the user.
Paused state: When an activity is not in focus (not interacting with the user) but still visible on the screen. This is not typical because device screens are usually small, and an activity either takes up the whole screen or none. This often occurs with dialog boxes that come up in front of an activity. All activities go through a paused state en route to being stopped. Paused activities still have high priority for memory and resources because they are visible and cannot be removed without appearing strange to the user.
Stopped state: When an activity is not visible but still in memory. A stopped activity can be brought back to the front to become running again, or it can be destroyed and removed from memory. The system keeps stopped activities around because restarting them is far cheaper than starting from scratch — all objects are already loaded in memory. However, stopped activities can be removed from memory at any point.
Destroyed state: A destroyed activity is no longer in memory. The Activity Manager decided this activity is no longer needed and removed it. Before destruction, the activity can perform certain actions such as saving unsaved information. However, there is no guarantee that your activity will be stopped prior to being destroyed — a paused activity can also be destroyed. For this reason, it is better to do important work (like saving unsaved data) en route to a paused state rather than a destroyed state.
💡 Why this matters: Properly handling the activity life cycle prevents data loss and ensures a smooth user experience. For example, if a user receives a phone call while filling out a form, you must save the form data in onPause() rather than onDestroy() because the activity might be destroyed directly from the paused state.
Life Cycle Callback Methods
The lecture provides a complete Java implementation of an Activity class with all life cycle callback methods:
package net.learn2develop.Activities;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
String tag = "Events";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d(tag, "In the onCreate() event");
}
public void onStart() { super.onStart(); Log.d(tag, "In the onStart() event"); }
public void onRestart() { super.onRestart(); Log.d(tag, "In the onRestart() event"); }
public void onResume() { super.onResume(); Log.d(tag, "In the onResume() event"); }
public void onPause() { super.onPause(); Log.d(tag, "In the onPause() event"); }
public void onStop() { super.onStop(); Log.d(tag, "In the onStop() event"); }
public void onDestroy() { super.onDestroy(); Log.d(tag, "In the onDestroy() event"); }
}
The LogCat output demonstrates the life cycle in action:
When the activity is first loaded:
12-28 13:45:28.115: DEBUG/Events(334): In the onCreate() event
12-28 13:45:28.115: DEBUG/Events(334): In the onStart() event
12-28 13:45:28.115: DEBUG/Events(334): In the onResume() event
Sequence: onCreate() → onStart() → onResume()
When pressing the Back button:
12-28 13:59:46.266: DEBUG/Events(334): In the onPause() event
12-28 13:59:46.806: DEBUG/Events(334): In the onStop() event
12-28 13:59:46.806: DEBUG/Events(334): In the onDestroy() event
Sequence: onPause() → onStop() → onDestroy()
When reopening the app from Home button (long press):
12-28 14:00:54.115: DEBUG/Events(334): In the onCreate() event
12-28 14:00:54.156: DEBUG/Events(334): In the onStart() event
12-28 14:00:54.156: DEBUG/Events(334): In the onResume() event
Note: The activity was completely destroyed, so it goes through the full creation sequence again.
When pressing the Phone button (activity goes to background):
12-28 14:01:16.515: DEBUG/Events(334): In the onPause() event
12-28 14:01:17.135: DEBUG/Events(334): In the onStop() event
Notice: onDestroy() is NOT called — the activity remains in memory (stopped state).
When returning from Phone dialer (Back button):
12-28 14:02:17.255: DEBUG/Events(334): In the onRestart() event
12-28 14:02:17.255: DEBUG/Events(334): In the onStart() event
12-28 14:02:17.255: DEBUG/Events(334): In the onResume() event
Sequence: onRestart() → onStart() → onResume()
This shows a stopped activity being brought back to the foreground without recreating it.
📐 Life Cycle Callback Sequence Patterns:
- Creation:
onCreate()→onStart()→onResume() - Full destruction:
onPause()→onStop()→onDestroy() - Background (stopped):
onPause()→onStop() - Return from background:
onRestart()→onStart()→onResume()
⭐ Key Takeaways
The activity life cycle is fundamental to Android development because it dictates how your app behaves during transitions like incoming calls, screen rotation, or app switching. The most critical concepts to remember are: there are five states (Starting, Running, Paused, Stopped, Destroyed) with corresponding callback methods (onCreate, onStart, onResume, onPause, onStop, onDestroy), and only one activity is in the Running state at any time. The expensive nature of creating activities means Android keeps stopped activities in memory when possible, restarting them via onRestart() rather than recreating them. Crucially, important data like unsaved user input should be saved in onPause() rather than onDestroy() because an activity can go from paused directly to destroyed. The LogCat output patterns demonstrate these transitions clearly and are essential to memorize for understanding application behavior during testing.
🧠 Quick Revision Questions
- What are the five states of an activity in the Android activity life cycle?
- Why does Android keep stopped activities in memory instead of destroying them immediately?
- What is the sequence of callback methods called when an activity is first created from scratch?
- Why should unsaved data be saved in onPause() rather than onDestroy()?
- What callback sequence is executed when a stopped activity is brought back to the foreground (e.g., after pressing Back from the phone dialer)?
📘 Lecture 40 — Activity Life Cycle
📖 Overview: This lecture continues the exploration of the Android Activity Life Cycle by demonstrating the sequence of callback methods triggered by user actions such as pressing the Back, Home, and Phone buttons. It also introduces Content Providers, explaining how they enable data sharing between applications in Android.
🗂️ Topics Covered
The lecture first demonstrates the Activity Life Cycle in action by pressing the Back button, Home button, and Phone button on the Android Emulator, showing the corresponding LogCat output for each event sequence. It then introduces the concept of Content Providers as interfaces for sharing data between applications, listing several built-in providers like Browser, CallLog, Contacts, MediaStore, and Settings, and noting that custom content providers can also be created.
📝 Lecture Summary
Activity Life Cycle
The lecture provides a practical demonstration of the Activity Life Cycle by showing the LogCat output when different buttons are pressed. Pressing the Back button results in a full destruction sequence: onPause(), onStop(), and onDestroy() are called. Pressing and holding the Home button and then clicking the Activities icon triggers a recreation sequence: onCreate(), onStart(), and onResume(). Pressing the Phone button pushes the activity to the background, triggering onPause() and onStop(), but notably onDestroy() is not called, indicating the activity remains in memory. When the phone dialer is exited by pressing the Back button, the activity becomes visible again, triggering onRestart(), onStart(), and onResume().
💡 Why this matters: Understanding these specific callback sequences is critical for correctly handling application state during user navigation and multitasking.
🔑 Definition — Activity Life Cycle: The set of callback methods (onCreate(), onStart(), onResume(), onPause(), onStop(), onDestroy(), onRestart()) that are called as an activity transitions between different states (running, paused, stopped, destroyed).
📌 Example — Back Button: When the Back button is pressed, the output shows:
onPause()eventonStop()eventonDestroy()event This indicates the activity is fully removed from memory.
📌 Example — Home Button (then click Activities icon): The output shows:
onCreate()eventonStart()eventonResume()event This indicates a full restart and recreation of the activity.
📌 Example — Phone Button: The output shows:
onPause()eventonStop()event Note:onDestroy()is NOT called, meaning the activity is still in memory.
📌 Example — Exiting Phone Dialer (pressing Back): The output shows:
onRestart()eventonStart()eventonResume()event This shows the activity is brought back from memory without being recreated.
Content Provider
This section introduces Content Providers as interfaces for sharing data between applications. By default, Android runs each application in its own sandbox, isolating all application data from other applications. While small amounts of data can be passed via intents, content providers are better suited for sharing persistent data between potentially large datasets. The Android system uses this mechanism extensively. Several built-in content providers are listed: Browser (stores browser bookmarks and history), CallLog (stores missed calls and call details), Contacts (stores contact details; the Contacts Provider exposes all user contact data to various applications), MediaStore (stores media files such as audio, video, and images; responsible for storing and sharing media across applications), and Settings (stores device settings and preferences; the Settings Provider exposes system settings to various applications). The lecture notes that besides these built-in providers, you can also create your own content providers.
🔑 Definition — Content Provider: An interface for sharing persistent data between different Android applications. They are the standard mechanism for exposing data from one application to other applications in a secure and controlled manner.
🔑 Definition — Sandbox: The default execution environment for each Android application where all data belonging to that application is totally isolated from other applications on the system.
⭐ Key Takeaways
The Back button triggers onPause(), onStop(), and onDestroy(), fully removing the activity from memory. Pressing and holding Home and selecting the activity triggers onCreate(), onStart(), and onResume(), indicating a complete recreation. The Phone button triggers onPause() and onStop() but NOT onDestroy(), showing the activity remains in memory. Content Providers are essential for sharing persistent data between Android applications, as applications run in isolated sandboxes by default. Android provides several built-in content providers (Browser, CallLog, Contacts, MediaStore, Settings), and developers can create custom ones for data sharing.
🧠 Quick Revision Questions
- What sequence of life cycle methods is called when the Back button is pressed?
- What is the difference in the life cycle method sequence between pressing the Home button (then selecting the activity) and pressing the Phone button?
- When the Phone button is pressed and the activity is pushed to the background, which life cycle method is NOT called, indicating the activity remains in memory?
- What is the primary purpose of a Content Provider in Android?
- List at least three built-in Content Providers provided by the Android system.
📘 Lecture 41 — Content Provider
📖 Overview: This lecture introduces Android Content Providers, a standard interface for sharing data between applications. It explains how content providers separate data storage from user interface, how to query them using URIs, and demonstrates practical implementation with the Contacts Provider, including the use of Cursors and required permissions.
🗂️ Topics Covered
The lecture covers the definition and purpose of Content Providers, including their standard methods (insert, update, delete, query). It explains how the Contacts app uses a separate Contacts Provider for data storage. It details the URI format for querying content providers, introduces Cursors and Cursor Adapters for accessing query results, shows code examples for retrieving contacts using managedQuery() and getContentResolver(), and lists predefined query string constants for various Android system providers.
📝 Lecture Summary
Content Provider
Content providers are relatively simple interfaces that expose data to other applications through standard methods: insert(), update(), delete(), and query(). These methods resemble standard database methods, making it easy to implement a content provider as a proxy to a database. However, developers are more likely to use existing content providers than to write their own.
The Contacts app uses Contacts Provider, a totally separate application, to retrieve data about users' contacts. The Contacts app itself does not store any contacts data, and Contacts Provider has no user interface. This separation of data storage and user interface offers greater flexibility for mashing up various parts of the system. For example, a user could install an alternative address book application that uses the same data as the default Contacts app, or install widgets on the Home screen to toggle WiFi, Bluetooth, or GPS features.
To query a content provider, you specify the query string in the form of a URI (Uniform Resource Identifier), with an optional specifier for a particular row. The format of the query URI is:
📐 Formula: content://<authority>/<data_path>/<id>
→ Plain-English meaning: The URI starts with the standard prefix "content://", followed by the provider's authority name, the type of data requested, and optionally a specific record ID.
🔑 Definition — Authority: Specifies the name of the content provider (e.g., "contacts" for the built-in Contacts provider, or a fully qualified name like "com.wrox.provider")
🔑 Definition — Data Path: Specifies the kind of data requested (e.g., "people" for all contacts)
The URI content://contacts/people requests all contacts, while content://contacts/people/2 requests contact number 2 specifically.
💡 Why this matters: Understanding the URI structure is essential for correctly accessing any data exposed by content providers, including system data like contacts, media, and settings.
Content Providers – Cursors
Cursors provide an interface for random read-write access to the result set returned by a database query. Cursor Adapters are adapters that expose data from a Cursor to a ListView widget, which shows items in a vertically scrolling list.
The lecture demonstrates how to query the Contacts Provider in an activity:
public class MainActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Uri allContacts = Uri.parse("content://contacts/people");
Cursor c = managedQuery(allContacts, null, null, null, null);
// ...
}
}
The managedQuery() method of the Activity class retrieves a managed cursor. A managed cursor handles all the work of unloading itself when the application pauses and requerying itself when the application restarts.
🔑 Definition — managedQuery(): A method that returns a managed Cursor, automatically handling its lifecycle based on the activity's lifecycle
The statement Cursor c = managedQuery(allContacts, null, null, null, null); is equivalent to:
Cursor c = getContentResolver().query(allContacts, null, null, null, null);
startManagingCursor(c); // allows the activity to manage the Cursor’s lifecycle
The getContentResolver() method returns a ContentResolver object, which helps resolve a content URI with the appropriate content provider.
For an application to access the Contacts application, the READ_CONTACTS permission must be declared in the AndroidManifest.xml file:
<uses-permission android:name="android.permission.READ_CONTACTS" />
Some examples of predefined query string constants for accessing system content providers include:
- Browser.BOOKMARKS_URI
- Browser.SEARCHES_URI
- CallLog.CONTENT_URI
- MediaStore.Images.Media.INTERNAL_CONTENT_URI
- MediaStore.Images.Media.EXTERNAL_CONTENT_URI
- Settings.CONTENT_URI
⭐ Key Takeaways
Content Providers enable data sharing between different Android applications by separating data storage from the user interface. Queries are performed using a structured URI format (content://authority/data_path/id), and results are returned via Cursors, which provide random read-write access. Using managedQuery() or getContentResolver().query() with startManagingCursor() ensures proper cursor lifecycle management. Applications must declare appropriate permissions (like READ_CONTACTS) in the manifest to access other providers' data. Predefined constants simplify access to common system data like browser bookmarks, call logs, media store, and system settings.
🧠 Quick Revision Questions
- What are the four standard methods that a Content Provider must implement?
- What is the complete URI format for querying a content provider, and what does each component represent?
- What is the difference between
managedQuery()and usinggetContentResolver().query()? - Which permission is required in AndroidManifest.xml to access the Contacts provider?
- Name three predefined query string constants for accessing system content providers.
📘 Lecture 42 — Intents
📖 Overview: This lecture covers Android Intents, which are asynchronous messages that trigger components like activities and services. It explains the difference between explicit and implicit intents, and demonstrates how to use them to perform common actions like opening web pages, dialing numbers, and picking contacts.
🗂️ Topics Covered
The lecture covers the definition and types of Intents (explicit and implicit), examples of implicit intents using standard Android actions (ACTION_VIEW, ACTION_DIAL, ACTION_PICK), intent components (action, data, type, category), intent resolution, passing data via setData() and setType(), and defining intent filters in AndroidManifest.xml for custom inter-activity communication.
📝 Lecture Summary
Intents
Intents are messages sent among major building blocks (activities, services, broadcasts). They trigger an activity to start, tell a service to start/stop, or are simply broadcasts. Intents are asynchronous, meaning the sending code does not wait for them to complete.
An intent can be explicit (the sender clearly specifies which component should receive it) or implicit (the sender specifies the type of receiver). For example, an activity can send an intent saying it simply wants someone to open a web page. Any application capable of opening a web page can "compete" to complete the action. When there are competing applications, the system asks the user which one to use. Users can also set a default app, similar to replacing a default web browser on a desktop.
💡 Why this matters: This mechanism allows users to replace any app on the system with a custom one, such as downloading a different SMS application or browser.
🔑 Definition — Intent: A messaging object used to request an action from another app component, either explicitly or implicitly.
📐 Implicit Intent Examples:
-
View a web page:
Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://www.amazon.com")); startActivity(i); -
Dial a telephone number:
Intent i = new Intent(android.content.Intent.ACTION_DIAL, Uri.parse("tel:+651234567")); startActivity(i); -
View a map location:
Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("geo:37.827500,-122.481670")); startActivity(i); -
Pick a contact (expects a result):
Intent i = new Intent(android.content.Intent.ACTION_PICK); i.setType(ContactsContract.Contacts.CONTENT_TYPE); startActivityForResult(i, request_Code);
📌 Example — Dialer without number: To simply display the dialer without specifying a number, omit the data portion:
Intent i = new Intent(android.content.Intent.ACTION_DIAL);
📌 Example — Contact picker with result: Because you expect a result from the Contacts application, use startActivityForResult() and implement onActivityResult() to obtain the result.
Intent Components
An Intent object contains several components:
- Action: Defines what you want to do (e.g., ACTION_VIEW, ACTION_DIAL, ACTION_PICK).
- Data: Contains the data for the target activity to act upon (e.g., URI for a web page, telephone number, or geo location).
- Type: For some intents, no data is needed. Instead, you specify the MIME type using
setType(). For example, to pick a contact, specify the action and then indicate the MIME type. - Category: Groups activities into logical units for further filtering by Android.
Data can also be passed using the setData() method. For example:
Intent i = new Intent(android.content.Intent.ACTION_VIEW);
i.setData(Uri.parse("http://www.amazon.com"));
The Android OS looks for all activities that can satisfy the request; this process is known as intent resolution.
📐 Example — Using setType() with contacts:
Intent i = new Intent(android.content.Intent.ACTION_PICK);
i.setType(ContactsContract.Contacts.CONTENT_TYPE);
i.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
Intent Filters
To allow other activities to invoke your activity, you specify the action and category within the <intent-filter> element in the AndroidManifest.xml file.
Simple example where one activity calls another using a custom action:
<intent-filter>
<action android:name="net.learn2develop.ACTIVITY2" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
📌 Example — Adding category via code:
Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://www.amazon.com"));
i.addCategory("net.learn2develop.Apps");
startActivity(i);
Corresponding AndroidManifest.xml entry:
<activity android:name=".MyBrowserActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="net.learn2develop.MyBrowser" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="net.learn2develop.Apps" />
<data android:scheme="http" />
</intent-filter>
</activity>
If you omit the addCategory() statement, the code will still invoke MyBrowserActivity because it matches the default category "android.intent.category.DEFAULT".
📌 Example — Mismatched category causes exception:
Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://www.amazon.com"));
i.addCategory("net.learn2develop.OtherApps");
startActivity(i);
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="net.learn2develop.MyBrowser" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="net.learn2develop.Apps" />
<category android:name="net.learn2develop.OtherApps" />
<data android:scheme="http" />
</intent-filter>
Here, the category "net.learn2develop.OtherApps" does not match any in the intent filter, so a run-time exception will be raised.
⭐ Key Takeaways
Intents are asynchronous messages that trigger components, with explicit intents naming a specific target and implicit intents specifying the type of receiver. Implicit intents support standard actions like ACTION_VIEW (web, maps), ACTION_DIAL (phone), and ACTION_PICK (contacts), and can include data via URIs or MIME types. Intent components include action, data, type, and category, with intent resolution matching these to intent filters defined in AndroidManifest.xml. When a result is expected from another activity, use startActivityForResult() and implement onActivityResult(). Custom intent filters allow your activity to be invoked by other apps; mismatched categories will throw a runtime exception.
🧠 Quick Revision Questions
- What is the difference between explicit and implicit intents?
- How do you create an intent to view a web page and start it?
- What method do you use when you expect a result from another activity?
- What are the four components of an Intent object?
- What happens if you add a category to an intent that does not match any intent filter in AndroidManifest.xml?
📘 Lecture 43 — Intents
📖 Overview: This lecture explores the Android Intent framework, explaining how applications communicate through intents, intent filters, and the Android intent resolution process. It also covers Services for background operations and Broadcast Receivers for inter-application messaging, culminating in practical SMS application development.
🗂️ Topics Covered
The lecture covers Intents and their components (Action, Data, Type, Category), intent resolution and matching against intent filters, Services lifecycle and implementation with code examples, Broadcast Receivers for handling system-wide intents, and SMS application development including sending and receiving SMS messages programmatically.
📝 Lecture Summary
Intents
An Intent is an inter-application message-passing framework. Using Intents you can broadcast messages system-wide or to a target Activity or Service, stating your intention to have an action performed. The system will then determine the target(s) that will perform any actions as appropriate.
An Intent object contains several components:
- Action: The action portion defines what you want to do
- Data: While the data portion contains the data for the target activity to act upon
- Type: For some intents, there is no need to specify the data. For example, to select a contact from the Contacts application, you specify the action and then indicate the MIME type using the
setType()method - Category: Besides specifying the action, the data, and the type, an Intent object can also specify a category. A category groups activities into logical units so that Android can use it for further filtering.
You can also pass the data to the Intent object using the setData() method. In this example, you indicate that you want to view a web page with the specified URL. The Android OS will look for all activities that are able to satisfy your request. This process is known as intent resolution.
Intent i = new Intent(android.content.Intent.ACTION_VIEW);
i.setData(Uri.parse("http://www.amazon.com"));
Intent i = new Intent(android.content.Intent.ACTION_PICK);
i.setType(ContactsContract.Contacts.CONTENT_TYPE);
i.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
Intent filters are declared in the AndroidManifest.xml file within <intent-filter> elements. They specify what intents an activity can handle:
<intent-filter>
<data android:mimeType="video/mpeg" android:scheme="http" ... />
<data android:mimeType="audio/mpeg" android:scheme="http" ... />
</intent-filter>
Consider what the browser application does when the user follows a link on a web page. It first tries to display the data (as it could if the link was to an HTML page). If it can't display the data, it puts together an implicit intent with the scheme and data type and tries to start an activity that can do the job. If there are no takers, it asks the download manager to download the data. That puts it under the control of a content provider, so a potentially larger pool of activities (those with filters that just name a data type) can respond.
Intents are matched against intent filters not only to discover a target component to activate, but also to discover something about the set of components on the device. For example, the Android system populates the application launcher, the top-level screen that shows the applications that are available for the user to launch, by finding all the activities with intent filters that specify the "android.intent.action.MAIN" action and "android.intent.category.LAUNCHER" category. It then displays the icons and labels of those activities in the launcher. Similarly, it discovers the home screen by looking for the activity with "android.intent.category.HOME" in its filter.
🔑 Definition — Intent Resolution: The process by which Android finds activities that can handle a given Intent by matching it against intent filters. 📌 Example: A simple intent filter declaration:
<intent-filter>
<action android:name="net.learn2develop.ACTIVITY2" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
This example shows one activity calling another using the "net.learn2develop.ACTIVITY2" action. An activity can invoke another activity using the Intent object. In order for other activities to invoke your activity, you need to specify the action and category within the <intent-filter> element in the AndroidManifest.xml file.
💡 Why this matters: Understanding intent resolution is critical for creating applications that can properly communicate and be discovered by other apps on the Android system.
When adding categories:
Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://www.amazon.com"));
i.addCategory("net.learn2develop.Apps");
startActivity(i);
With corresponding manifest:
<activity android:name=".MyBrowserActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="net.learn2develop.MyBrowser" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="net.learn2develop.Apps" />
<data android:scheme="http" />
</intent-filter>
</activity>
You add the category to the Intent object using the addCategory() method. If you omit the addCategory() statement, the preceding code will still invoke the MyBrowserActivity activity because it will still match the default category "android.intent.category.DEFAULT".
If you specify a category that does not match any in the intent filter, a run-time exception will be raised:
Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://www.amazon.com"));
i.addCategory("ALTERNATIVE");
startActivity(i);
This code would raise a run-time exception if the filter doesn't contain the "ALTERNATIVE" category.
💡 Why this matters: Category matching is strict — if the Intent has a category not in the filter, the activity won't be considered a match, which can cause app crashes if not handled properly.
Services
Services run in the background and don't have any user interface components. They can perform the same actions as activities, but without any user interface. Services are useful for actions that we want to perform for a while, regardless of what is on the screen. For example, you might want your music player to play music even as you are flipping between other applications.
Services have a much simpler life cycle than activities. You either start a service or stop it. Also, the service life cycle is more or less controlled by the developer, and not so much by the system. Consequently, we as developers have to be mindful to run our services so that they don't consume shared resources unnecessarily, such as the CPU and battery.
🔑 Definition — Service: A component that runs in the background to perform long-running operations without a user interface.
A service class extends the Service base class:
public class MyService extends Service {
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}
Key methods in a Service:
- onBind(): Enables you to bind an activity to a service, allowing an activity to directly access members and methods inside a service. For now, simply return
nullfor this method. - onStartCommand(): Called when you start the service explicitly using the
startService()method. This method signifies the start of the service. ReturningSTART_STICKYensures the service will continue to run until it is explicitly stopped. - onDestroy(): Called when the service is stopped using the
stopService()method. This is where you clean up the resources used by your service.
📌 Example — Service declaration in AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.learn2develop.Services"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon"
android:label="@string/app_name">
<activity android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyService" />
</application>
<uses-sdk android:minSdkVersion="9" />
</manifest>
All services that you have created must be declared in the AndroidManifest.xml file, like this: <service android:name=".MyService" />. If you want your service to be available to other applications, you can always add an intent filter with an action name:
<service android:name=".MyService">
<intent-filter>
<action android:name="net.learn2develop.MyService" />
</intent-filter>
</service>
📌 Example — Starting and stopping a service from an Activity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnStart = (Button) findViewById(R.id.btnStartService);
btnStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startService(new Intent(getBaseContext(), MyService.class));
}
});
Button btnStop = (Button) findViewById(R.id.btnStopService);
btnStop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
stopService(new Intent(getBaseContext(), MyService.class));
}
});
}
- To start a service, use the
startService()method:startService(new Intent(getBaseContext(), MyService.class)); - If calling an external service, use:
startService(new Intent("net.learn2develop.MyService")); - To stop a service, use the
stopService()method:stopService(new Intent(getBaseContext(), MyService.class));
💡 Why this matters: Services are essential for background tasks like music playback, network operations, or data synchronization that must continue even when the user switches applications.
Intents and Broadcast Receivers
- Intents: An inter-application message-passing framework. Using Intents you can broadcast messages system-wide or to a target Activity or Service, stating your intention to have an action performed.
- Broadcast Receivers: Intent broadcast consumers. If you create and register a Broadcast Receiver, your application can listen for broadcast Intents that match specific filter criteria. Broadcast Receivers will automatically start your application to respond to an incoming Intent, making them perfect for creating event-driven applications.
🔑 Definition — Broadcast Receiver: A component that listens for broadcast Intents and allows your application to respond to events raised by other applications or the system.
SMS Application
AndroidManifest.xml: Because sending SMS messages incurs additional costs on the user's end, indicating the SMS permissions in the AndroidManifest.xml file enables users to decide whether to allow the application to install or not.
Sending SMS: To send an SMS message programmatically, you use the SmsManager class. Unlike other classes, you do not directly instantiate this class; instead, you call the getDefault() static method to obtain a SmsManager object. You then send the SMS message using the sendTextMessage() method:
private void sendSMS(String phoneNumber, String message) {
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
Five arguments to the sendTextMessage() method:
destinationAddress— Phone number of the recipientscAddress— Service center address; usenullfor default SMSCtext— Content of the SMS messagesentIntent— Pending intent to invoke when the message is sentdeliveryIntent— Pending intent to invoke when the message has been delivered
📌 Example — Sending SMS with PendingIntents:
private void sendSMS(String phoneNumber, String message) {
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), 0);
}
Using the SmsManager class, you can send SMS messages from within your application without the need to involve the built-in Messaging application. However, sometimes it would be easier if you could simply invoke the built-in Messaging application and let it do all the work of sending the message.
Receiving SMS: To listen for incoming SMS messages, you create a BroadcastReceiver class. The BroadcastReceiver class enables your application to receive intents sent by other applications using the sendBroadcast() method. Essentially, it enables your application to handle events raised by other applications.
When an intent is received, the onReceive() method is called; hence, you need to override this. When an incoming SMS message is received, the onReceive() method is fired.
The SMS message is contained in the Intent object via a Bundle object. The messages are stored in an Object array in the PDU format. To extract each message, you use the static createFromPdu() method from the SmsMessage class. The SMS message is then displayed using the Toast class. The phone number of the sender is obtained via the getOriginatingAddress() method.
🔑 Definition — PDU (Protocol Data Unit): The format in which SMS messages are stored and transmitted over the network.
One interesting characteristic of the BroadcastReceiver is that you can continue to listen for incoming SMS messages even if the application is not running; as long as the application is installed on the device, any incoming SMS messages will be received by the application.
💡 Why this matters: Broadcast Receivers make it possible to build event-driven applications that respond to system events (like receiving SMS) even when the app isn't actively running.
⭐ Key Takeaways
The most critical learning from this lecture is the Android Intent framework — Intents are the fundamental message-passing mechanism for inter-component communication, consisting of Action, Data, Type, and Category components that are matched against intent filters during intent resolution. Services run in the background without UI and must be declared in AndroidManifest.xml, with key lifecycle methods onStartCommand() returning START_STICKY for continuous operation and onDestroy() for cleanup. Broadcast Receivers enable applications to listen for system-wide intents and respond automatically, even when not running, making them ideal for event-driven applications like SMS handling. Programmatic SMS sending uses the SmsManager class's sendTextMessage() method with PendingIntents for status tracking, while receiving SMS requires a BroadcastReceiver that extracts messages from PDU format using SmsMessage.createFromPdu().
🧠 Quick Revision Questions
- What are the four components of an Intent object and what does each define?
- What happens when you specify a category in an Intent that does not match any category in the target activity's intent filter?
- Why should you return
START_STICKYfrom theonStartCommand()method in a Service? - How do you extract individual SMS messages from a received Intent in a BroadcastReceiver, and what format are they stored in?
- What is the purpose of the
sentIntentanddeliveryIntentparameters in thesendTextMessage()method of SmsManager?
📘 Lecture 44 — Notifications, Widgets, Databases, and Detecting User Activity
📖 Overview: This lecture covers four major areas of Android development: creating and managing status bar notifications for background services, building home screen widgets with periodic updates, implementing persistent data storage using SQLite databases, and detecting user activity through device sensors and touch events. Understanding these topics is crucial for creating responsive, interactive, and data-driven mobile applications.
🗂️ Topics Covered
The lecture begins with status bar notifications for background services, including how to create, configure, and display notifications with sound, vibration, and lights. It then covers home screen widgets, their lifecycle, and update mechanisms. Next, it explains SQLite database creation, table management, data insertion, threading, and versioning. Finally, it explores detecting user activity through device orientation, accelerometer sensors, available sensor listing, touch events, gestures, and keyboard control.
📝 Lecture Summary
Notifications
A status bar notification adds an icon to the system's status bar with an optional ticker-text message and an expanded message in the "Notifications" window. When the user selects the expanded message, Android fires an Intent that usually launches an Activity. You can also configure the notification to alert the user with a sound, a vibration, and flashing lights on the device.
A status bar notification should be used for any case in which a background Service needs to alert the user about an event that requires a response. A background Service should never launch an Activity on its own; instead, it should create a status bar notification that will launch the Activity when selected by the user.
🔑 Definition — Notification: defines the properties of your status bar notification, such as the status bar icon, the expanded message, and extra settings like sound to play.
🔑 Definition — NotificationManager: an Android system service that executes and manages all Notifications.
To create a notification, you must retrieve a reference to the NotificationManager using getSystemService(), then pass your Notification object with notify():
// Get Reference to Notification Manager
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
// Instantiate the Notification
int icon = R.drawable.notification_icon;
CharSequence tickerText = "Hello";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
// Define the Notification's expanded message and Intent
Context context = getApplicationContext();
CharSequence contentTitle = "My notification";
CharSequence contentText = "Hello World!";
Intent notificationIntent = new Intent(this, MyClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
// Pass the Notification to the NotificationManager
private static final int HELLO_ID = 1;
mNotificationManager.notify(HELLO_ID, notification);
Additional "fancy stuff" includes adding sound, vibration, and flashing lights to notifications.
💡 Why this matters: Notifications allow background services to communicate with users without interrupting their current activity, which is essential for maintaining a good user experience.
Widgets
Widgets are little applications that can be placed on the home screen of an Android device. A widget gets its data on a periodic timetable. There are two methods to update a widget: one based on an XML configuration file and the other based on AlarmManager.
🔑 Definition — AppWidgetProvider: a broadcast receiver that extends AppWidgetProvider and provides additional lifecycle hooks for widgets.
To create a widget, you must:
- Define a layout file for the widget
- Maintain an XML file (AppWidgetProviderInfo) describing widget properties
- Create a broadcast receiver extending AppWidgetProvider
- Maintain App Widget configuration in AndroidManifest.xml
- Optionally specify a configuration activity called once when a widget instance is added
To save power consumption, a widget does not have its own process but is part of the home screen process. The widget UI is created as a RemoteView, which can be executed by another process with the same permissions as the original application.
In the widget configuration file, you can specify a fixed update interval. The minimum update interval is 180000 milliseconds (30 minutes).
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:updatePeriodMillis="180000"
android:initialLayout="@layout/widget_layout"
android:minHeight="72dp"
android:minWidth="146dp">
</appwidget-provider>
The AppWidgetProvider class implements the onReceive() method, extracts required information, and calls widget lifecycle methods.
Creating Database / Persistence
Android incorporates SQLite (version 3), a server-less, transactional database engine. Inside the onCreate() method, you declare and assign an SQLiteDatabase:
SQLiteDatabase db;
db = openOrCreateDatabase("my_database.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
🔑 Definition — openOrCreateDatabase(): a SQLiteDatabase method that takes a string name, an SQL mode, and a CursorFactory object. SQL modes include: CREATE_IF_NECESSARY, OPEN_READWRITE, OPEN_READONLY, and NO_LOCALIZED_COLLATORS.
To create a table, construct an SQL statement and execute it:
final String CREATE_TABLE_CITIES = "CREATE TABLE tb_cities (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"city_name TEXT);";
db.execSQL(CREATE_TABLE_CITIES);
To insert entries, use a ContentValues object:
ContentValues cv = new ContentValues();
cv.put("city_name", "Aberdeen");
db.insert("tb_cities", null, cv);
cv.put("city_name", "Dundee");
db.insert("tb_cities", null, cv);
Finally, close the database with db.close();
To make a database thread safe, use:
db.setLockingEnabled(true);
To version a database, use:
db.setVersion(2);
💡 Why this matters: Persistent storage is essential for applications that need to save user data, preferences, or application state across sessions.
Detecting User Activity
Android handsets can detect speed, motion, gravitational pull, and the Earth's magnetic field. Combined with sensitive touch-screens capable of reading complex gestures, these input devices make smartphones versatile programming platforms.
Reading Device Orientation
To detect orientation changes, add a configChanges element to the <activity> node in AndroidManifest.xml, then override onConfigurationChanged():
@Override
public void onConfigurationChanged(Configuration config) {
super.onConfigurationChanged(config);
if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
mTextView.setText("landscape");
} else if (config.orientation == Configuration.ORIENTATION_PORTRAIT) {
mTextView.setText("portrait");
}
}
Measuring Speed with Accelerometer To gather information from sensors, implement the SensorEventListener interface:
public class MotionDetector extends Activity implements SensorEventListener {
private SensorManager mSensorManager;
// In onCreate():
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
}
🔑 Definition — SensorEventListener: an Android interface that provides callbacks for responding to changes in sensor values or accuracy.
Register the listener in onResume() and unregister in onPause():
@Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
}
@Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
The delay value controls how quickly the sensor operates and can dramatically affect power usage. The four settings are:
SENSOR_DELAY_FASTESTSENSOR_DELAY_GAMESENSOR_DELAY_NORMALSENSOR_DELAY_UI
The actual reading of accelerometer values occurs in onSensorChanged():
public void onSensorChanged(SensorEvent e) {
synchronized (this) {
if (e.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
mTextView.setText("x= " + e.values[0] + "\ny= " + e.values[1] + "\nz= " + e.values[2]);
}
}
}
The accelerometer returns three values describing acceleration along each axis in m/s².
The onAccuracyChanged() method must be included but can remain empty:
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
Possible accuracy constant values include: SENSOR_STATUS_ACCURACY_HIGH, SENSOR_STATUS_ACCURACY_MEDIUM, and SENSOR_STATUS_ACCURACY_LOW.
Other Types of Sensors
Available sensor types include: TYPE_ACCELEROMETER, TYPE_ALL, TYPE_GRAVITY, TYPE_GYROSCOPE, TYPE_LIGHT, TYPE_LINEAR_ACCELERATION, TYPE_MAGNETIC_FIELD, TYPE_ORIENTATION, TYPE_PRESSURE, TYPE_PROXIMITY, TYPE_ROTATION_VECTOR, and TYPE_TEMPERATURE.
Listing Available Sensors To detect which sensors are available on a device:
private SensorManager mSensorManager;
private TextView mTextView;
private List mList;
// In onCreate():
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mTextView = (TextView) findViewById(R.id.text_view);
mList = mSensorManager.getSensorList(Sensor.TYPE_ALL);
for (int i = 1; i < mList.size(); i++) {
mTextView.append("\n" + mList.get(i));
}
Other Functionalities The lecture also mentions recognizing touch events, detecting multi-touch events, recognizing gestures, and controlling the on-screen keyboard.
⭐ Key Takeaways
The most critical concepts from this lecture are: status bar notifications must be created from background Services (not Activities directly) using Notification and NotificationManager classes, with optional sound, vibration, and light alerts. Widgets are lightweight home screen components using RemoteViews with a minimum update interval of 30 minutes to conserve power. SQLite databases are created using openOrCreateDatabase(), tables are built with execSQL(), and data is inserted using ContentValues objects. Sensor detection requires implementing SensorEventListener, registering the listener in onResume() and unregistering in onPause() to manage battery consumption, with four delay settings controlling sensor update frequency.
🧠 Quick Revision Questions
- What two classes are required to create a status bar notification, and how do you pass the notification to the system?
- What is the minimum update interval for an Android widget, and why is this enforced?
- What SQL mode flag creates a database if it doesn't already exist, and what other flags are available?
- How do you make a SQLite database thread-safe, and how do you version it?
- What are the four sensor delay settings and which one is most battery-efficient?