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