π 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?