diff options
Diffstat (limited to 'docs/html/guide/topics')
38 files changed, 7914 insertions, 1606 deletions
diff --git a/docs/html/guide/topics/data/contentproviders.jd b/docs/html/guide/topics/data/contentproviders.jd deleted file mode 100644 index 343ed84..0000000 --- a/docs/html/guide/topics/data/contentproviders.jd +++ /dev/null @@ -1,608 +0,0 @@ -page.title=Accessing Content Providers -@jd:body - -<p>If you want to make your data public, you can create (or call) a content -provider. This is an object that can store and retrieve data accessible by all -applications. This is the only way to share data across packages; there is no -common storage area that all packages can share. Android ships with a number -of content providers for common data types (audio, video, images, personal -contact information, and so on). You can see some of -Android's native content providers in the {@link android.provider provider} package.</p> - -<p>How a content provider actually stores its data under the covers is up to -the implementation of the content provider, but all content providers must -implement a common convention to query for data, and a common convention to -return results. However, a content provider can implement custom helper -functions to make data storage/retrieval simpler for the specific data that it -exposes.</p> - -<p>This document covers two topics related to Content Providers:</p> -<ul> - <li><a href="#usingacp">Using a Content Provider</a></li> - <li><a href="#creatingacontentprovider">Creating a Content Provider</a></li> -</ul> - -<h2>Using a Content Provider to Store and Retrieve Data <a name="usingacp" -id="usingacp"></a></h2> - -<p>This section describes how to store and retrieve data using a content -provider implemented by you or anyone else. Android exposes a number of -content providers for a wide range of data types, from music and image files -to phone numbers. You can see a list of content providers exposed through the -convenience classes in the {@link android.provider android.provider} package.</p> - -<p>Android's content providers are loosely linked to their clients. Each -content provider exposes a unique string (a URI) identifying the type of data -that it will handle, and the client must use that string to store or retrieve -data of that type. We'll explain this more in <a href="#querying">Querying for -Data</a>.</p> - -<p>This section describes the following activities:</p> - -<ul> - <li> - <a href="#querying">Querying for Data</a> - - <ul> - <li>Making the query</li> - - <li>What the query returns</li> - - <li>Querying for files</li> - - <li>Reading retrieved data</li> - </ul> - </li> - - <li><a href="#modifyingdata">Modifying Data</a></li> - - <li><a href="#addingrecord">Adding a Record</a></li> - - <li><a href="#deletingrecord">Deleting a Record</a></li> -</ul> - -<a name="querying" id="querying"></a> -<h4>Querying for Data</h4> - -<p>Each contact provider exposes a unique public URI (wrapped by {@link android.net.Uri}) -that is used by a client to query/add/update/delete data on that content -provider. This URI has two forms: one to indicate all values of that type -(e.g., all personal contacts), and one form to indicate a specific record of -that type (e.g., Joe Smith's contact information).</p> - -<ul> - <li><strong>content://contacts/people/</strong> is the URI that would return a list of all contact names on the device.</li> - - <li><strong>content://contacts/people/23</strong> is the URI string that would return a single result row, the contact with ID = 23. .</li> -</ul> - -<p>An application sends a query to the device that specifies a general type of -item (all phone numbers), or a specific item (Bob's phone number), to -retrieve. Android then returns a Cursor over a recordset of results, with a -specific set of columns. Let's look at a hypothetical query string and a -result set (the results have been trimmed a bit for clarity):</p> - -<p>query = <code>content://contacts/people/</code></p> - -<p>Results:</p> - -<table border="1"> - <tbody> - <tr> - <th scope="col">_ID</th> - - <th scope="col">_COUNT</th> - - <th scope="col">NUMBER</th> - - <th scope="col">NUMBER_KEY</th> - - <th scope="col">LABEL</th> - - <th scope="col">NAME</th> - - <th scope="col">TYPE</th> - </tr> - - <tr> - <td>13</td> - - <td>4</td> - - <td>(425) 555 6677</td> - - <td>425 555 6677</td> - - <td>Kirkland office</td> - - <td>Bully Pulpit</td> - - <td>Work</td> - </tr> - - <tr> - <td>44</td> - - <td>4</td> - - <td>(212) 555-1234</td> - - <td>212 555 1234</td> - - <td>NY apartment</td> - - <td>Alan Vain</td> - - <td>Home</td> - </tr> - - <tr> - <td>45</td> - - <td>4</td> - - <td>(212) 555-6657</td> - - <td>212 555 6657</td> - - <td>Downtown office</td> - - <td>Alan Vain</td> - - <td>Work</td> - </tr> - - <tr> - <td>53</td> - - <td>4</td> - - <td>201.555.4433</td> - - <td>201 555 4433</td> - - <td>Love Nest</td> - - <td>Rex Cars</td> - - <td>Home</td> - </tr> - </tbody> -</table> - -<p>Note that the query string isn't a standard SQL query string, but instead a -URI string that describes the type of data to return. This URI consists of -three parts: the string "content://"; a segment that describes what kind of -data to retrieve; and finally an optional ID of a specific item of the -specified content type. Here are a few more example query strings:</p> - -<ul> - <li><strong>content://media/internal/images</strong> is the URI string that would return a list of all - the internal images on the device.</li> - - <li><strong>content://media/external/images</strong> is the URI string that would return a list of all - the images on the "primary" external storage (e.g., the SD card).</li> - - <li><strong>content://contacts/people/</strong> is the URI that would return a list of all contact names on the device.</li> - - <li><strong>content://contacts/people/23</strong> is the URI string that would return a single result row, the contact with ID = 23.</li> -</ul> - -<p>Although there is a general form, these query URIs are somewhat arbitrary and -confusing. Therefore, Android provides a list of helper classes in the {@link -android.provider} package that -define these query strings so you should not need to know the actual URI value -for different data types. These helper classes define a string (actually, -a {@link android.net.Uri Uri} object) -called CONTENT_URI for a specific data type.</p> - -<p>Typically you will use the defined CONTENT_URI object to make a query, -instead of writing the full URI yourself. -So, each of the example query strings listed above (except for the last one that specifies the record ID) - can be acquired with the following Uri references:</p> - -<ul> - <li>{@link android.provider.MediaStore.Images.Media#INTERNAL_CONTENT_URI - MediaStore.Images.Media.INTERNAL_CONTENT_URI}</li> - - <li>{@link android.provider.MediaStore.Images.Media#EXTERNAL_CONTENT_URI - MediaStore.Images.Media.EXTERNAL_CONTENT_URI}</li> - - <li>{@link android.provider.Contacts.People#CONTENT_URI - Contacts.People.CONTENT_URI}</li> -</ul> - -<p>To query a specific record ID (e.g., content://contacts/people/23), -you'll use the same CONTENT_URI, but must append the specific ID value that you want. -This is one of the few times you should need to examine or modify the URI string. -So, for example, if you were looking for record 23 in the people contacts, you might run a query -as shown here:</p> -<pre> -// Get the base URI for contact with _ID=23. -// This is same as Uri.parse("content://contacts/people/23"); -Uri myPerson = ContentUris.withAppendedId(People.CONTENT_URI, 23); -// Query for this record. -Cursor cur = managedQuery(myPerson, null, null, null); -</pre> -<p class="note"><strong>Tip:</strong> You can also append a string to a Uri, using -{@link android.net.Uri#withAppendedPath(Uri,String)}.</p> - -<p>This query returns a cursor over a database query result set. What columns -are returned, what they're called, and what they are named are discussed next. -For now, though, know that you can specify that only certain columns be -returned, the sort order, and a SQL WHERE clause.</p> - -<p>You should use the {@link -android.app.Activity#managedQuery(android.net.Uri,java.lang.String[],java.lang.String,java.lang.String[],java.lang.String) Activity.managedQuery()} -method to retrieve a managed cursor. A managed cursor handles all the niceties -such as unloading itself when the application pauses, and requerying itself -when the application restarts. You can ask Android to manage an unmanaged -cursor for you by calling {@link -android.app.Activity#startManagingCursor(android.database.Cursor) Activity.startManagingCursor()}.</p> - -<p>Let's look at an example query to retrieve a list of contact names and their primary phone -numbers.</p> -<pre> -// An array specifying which columns to return. -string[] projection = new string[] { - People._ID, - People.NAME, - People.NUMBER, -}; - -// Get the base URI for People table in Contacts content provider. -// ie. content://contacts/people/ -Uri mContacts = People.CONTENT_URI; - -// Best way to retrieve a query; returns a managed query. -Cursor managedCursor = managedQuery( mContacts, - projection, //Which columns to return. - null, // WHERE clause--we won't specify. - People.NAME + " ASC"); // Order-by clause. -</pre> - -<p>This query will retrieve data from the people table of -the Contacts content provider. It will retrieve the name, primary phone number, and unique record ID for -each contact. </p> - -<p><strong>What the query returns</strong></p> - -<p>A query returns a set of zero or more database records. The column names, -order, and type are specific to the content provider, but every query includes -a column called _id, which is the ID of the item in that row. If a query can -return binary data, such as a bitmap or audio file, it will have a column with -any name that holds a content:// URI that you can use to get this data (more -information on how to get the file will be given later). Here is a tiresome -example result set for the previous query:</p> - -<table border="1"> - <tbody> - <tr> - <th scope="col">_id</th> - - <th scope="col">name</th> - - <th scope="col">number</th> - - - </tr> - - <tr> - <td>44</td> - - <td>Alan Vain</td> - - <td>212 555 1234</td> - - - </tr> - - <tr> - <td>13</td> - - <td>Bully Pulpit</td> - - <td>425 555 6677</td> - - - </tr> - - <tr> - <td>53</td> - - <td>Rex Cars</td> - - <td>201 555 4433</td> - - - </tr> - </tbody> -</table> - -<p>This result set demonstrates what is returned when we specified a subset of -columns to return. The optional subset list is passed in the -<em>projection</em> parameter of the query. A content manager should list -which columns it supports either by implementing a set of interfaces -describing each column (see {@link -android.provider.Contacts.People.Phones Contacts.People.Phones}, -which extends {@link android.provider.BaseColumns BaseColumns}, {@link -android.provider.Contacts.PhonesColumns PhonesColumns}, and {@link -android.provider.Contacts.PeopleColumns PeopleColumns}), or by -listing the column names as constants. Note that you need to -know the data type of a column exposed by a content provider in order to be -able to read it; the field reading method is specific to the data type, and a -column's data type is not exposed programmatically.</p> - -<p>The retrieved data is exposed by a {@link -android.database.Cursor Cursor} object that can be used to -iterate backward or forward through the result set. You can use this cursor to -read, modify, or delete rows. Adding new rows requires a different object -described later.</p> - -<p>Note that by convention, every recordset includes a field named _id, which -is the ID of a specific record, and a _count field, which is a count of -records in the current result set. These field names are defined by {@link -android.provider.BaseColumns BaseColumns}.</p> - -<p><strong>Querying for Files</strong></p> - -<p>The previous query result demonstrates how a file is returned in a data -set. The file field is typically (but not required to be) a string path to the -file. However, the caller should never try to read and open the file directly -(permissions problems for one thing can make this fail). Instead, you should -call {@link -android.content.ContentResolver#openInputStream(android.net.Uri) ContentResolver.openInputStream()} -/ {@link -android.content.ContentResolver#openOutputStream(android.net.Uri) -ContentResolver.openOutputStream()}, -or one of the helper functions from a content provider.</p> - -<p><strong>Reading Retrieved Data</strong></p> - -<p>The Cursor object retrieved by the query provides access to a recordset of -results. If you have queried for a specific record by ID, this set will -contain only one value; otherwise, it can contain multiple values. You can -read data from specific fields in the record, but you must know the data type -of the field, because reading data requires a specialized method for each type -of data. (If you call the string reading method on most types of columns, -Android will give you the String representation of the data.) The Cursor lets -you request the column name from the index, or the index number from the -column name.</p> - -<p>If you are reading binary data, such as an image file, you should call -{@link -android.content.ContentResolver#openOutputStream(android.net.Uri) ContentResolver.openOutputStream()} -on the string content:// URI stored in a column name.</p> - -<p>The following snippet demonstrates reading the name and phone number from -our phone number query:</p> -<pre> -private void getColumnData(Cursor cur){ - if (cur.moveToFirst()) { - - String name; - String phoneNumber; - int nameColumn = cur.getColumnIndex(People.NAME); - int phoneColumn = cur.getColumnIndex(People.NUMBER); - String imagePath; - - do { - // Get the field values - name = cur.getString(nameColumn); - phoneNumber = cur.getString(phoneColumn); - - // Do something with the values. - ... - - } while (cur.moveToNext()); - - } -} -</pre> - -<h3>Modifying Data<a name="modifyingdata" id="modifyingdata"></a></h3> - -<p>To batch update a group of records (for example, to change "NY" to "New -York" in all contact fields), call the {@link -android.content.ContentResolver#update(android.net.Uri,android.content.ContentValues,java.lang.String,java.lang.String[]) ContentResolver.update()} -method with the columns and values to change.</p> - -<h3>Adding a New Record <a name="addingrecord" id="addingrecord"></a></h3> - -<p>To add a new record, call ContentResolver.insert() with the URI of the type -of item to add, and a Map of any values you want to set immediately on the new -record. This will return the full URI of the new record, including record -number, which you can then use to query and get a Cursor over the new -record.</p> - -<pre> -ContentValues values = new ContentValues(); -Uri phoneUri = null; -Uri emailUri = null; - -values.put(Contacts.People.NAME, "New Contact"); -//1 = the new contact is added to favorites -//0 = the new contact is not added to favorites -values.put(Contacts.People.STARRED,1); - -//Add Phone Numbers -Uri uri = getContentResolver().insert(Contacts.People.CONTENT_URI, values); - -//The best way to add Contacts data like Phone, email, IM is to -//get the CONTENT_URI of the contact just inserted from People's table, -//and use withAppendedPath to construct the new Uri to insert into. -phoneUri = Uri.withAppendedPath(uri, Contacts.People.Phones.CONTENT_DIRECTORY); - -values.clear(); -values.put(Contacts.Phones.TYPE, Phones.TYPE_MOBILE); -values.put(Contacts.Phones.NUMBER, "1233214567"); -getContentResolver().insert(phoneUri, values); - -//Add Email -emailUri = Uri.withAppendedPath(uri, ContactMethods.CONTENT_DIRECTORY); - -values.clear(); -//ContactMethods.KIND is used to distinguish different kinds of -//contact data like email, im, etc. -values.put(ContactMethods.KIND, Contacts.KIND_EMAIL); -values.put(ContactMethods.DATA, "test@example.com"); -values.put(ContactMethods.TYPE, ContactMethods.TYPE_HOME); -getContentResolver().insert(emailUri, values); - -</pre> - -<p>To save a file, you can call ContentResolver().openOutputStream() with the -URI as shown in the following snippet: -</p> -<pre> -// Save the name and description in a map. Key is the content provider's -// column name, value is the value to save in that record field. -ContentValues values = new ContentValues(3); -values.put(MediaStore.Images.Media.DISPLAY_NAME, "road_trip_1"); -values.put(MediaStore.Images.Media.DESCRIPTION, "Day 1, trip to Los Angeles"); -values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); - -// Add a new record without the bitmap, but with the values. -// It returns the URI of the new record. -Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); - -try { - // Now get a handle to the file for that record, and save the data into it. - // sourceBitmap is a Bitmap object representing the file to save to the database. - OutputStream outStream = getContentResolver().openOutputStream(uri); - sourceBitmap.compress(Bitmap.CompressFormat.JPEG, 50, outStream); - outStream.close(); -} catch (Exception e) { - Log.e(TAG, "exception while writing image", e); -} -</pre> - -<h3>Deleting a Record <a name="deletingrecord" id="deletingrecord"></a></h3> - -<p>To delete a single record, call {@link -android.content.ContentResolver#delete(android.net.Uri,java.lang.String,java.lang.String[]) ContentResolver.delete()} -with the URI of a specific row.</p> - -<p>To delete multiple rows, call ContentResolver.delete() with the URI of the -type of record to delete (for example, -android.provider.Contacts.People.CONTENT_URI) and a SQL WHERE clause defining -which rows to delete (<em>Warning</em>: be sure to include a valid WHERE -clause if deleting a general type using ContentResolver.delete(), or else you -risk deleting more records than you intended!).</p> - -<h2>Creating a Content Provider<a name="creatingacontentprovider" -id="creatingacontentprovider"></a> </h2> <p>Here is how to create your own -content provider to act as a public source for reading and writing a new data -type:</p> -<ol> - <li>Extend - {@link android.content.ContentProvider ContentProvider}.</li> - <li>Define a <code>public static final {@link android.net.Uri Uri} </code>named - CONTENT_URI. This is the string that represents the full "content://" URI - that your content provider handles. You must define a unique string for this - value; the best solution is to use the fully-qualified class name of your - content provider (lowercase). So, for example: <br> - - <code>public static final Uri CONTENT_URI = Uri.parse( - "content://com.google.codelab.rssprovider");</code></li> - <li>Create your system for storing data. Most content providers store their - data using Android's file storage methods or SQLite databases, but you can - store your data any way you want, so long as you follow the calling and return - value conventions.</li> - <li>Define the column names that you will return to your clients. If you are - using an underlying database, these column names are typically identical - to the SQL database column names they represent. In any case, you should include - an integer column named <code>_id</code> to - define a specific record number. If using the SQLite database, this should - be type <code>INTEGER - PRIMARY KEY AUTOINCREMENT</code>. - The <code>AUTOINCREMENT</code> descriptor - is optional, but by default, SQLite - autoincrements an ID counter field to the next number above the largest - existing number in the table. If you delete the last row, the next row added - will have the same ID as the deleted row. To avoid this by having SQLite - increment to the next largest value whether deleted or not, then assign your - ID column the following type: INTEGER PRIMARY KEY AUTOINCREMENT. (<strong>Note</strong> You - should have a unique _id field whether or not you have another field (such - as a URL) that is also unique among all records.) Android provides the - {@link android.database.sqlite.SQLiteOpenHelper SQLiteOpenHelper} - - class to help you create and manage versions of your database. </li> - <li>If you are exposing byte data, such as a bitmap file, the field that stores - this data should actually be a string field with a content:// URI for that - specific file. This is the field that clients will call to retrieve this - data. The content provider for that content type (it can be the same content - provider or another content provider — for example, if you're storing a photo - you would use the media content provider) should implement a field named - _data for that record. The _data field lists the exact file path on the device - for that file. This field is not intended to be read by the client, but by - the ContentResolver. The client will call {@link - android.content.ContentResolver#openOutputStream(android.net.Uri) ContentResolver.openOutputStream()} on the user-facing field holding the URI - for the item (for example, the column named photo might have a value content://media/images/4453). - The ContentResolver will request the _data field for that record, and because - it has higher permissions than a client, it should be able to access - that file directly and return a read wrapper for that file to the client. </li> - <li>Declare public static - Strings that clients can use to specify which columns to return, or to specify - field values from the cursor. Carefully document the data type of each - field. Remember that file fields, such as audio or bitmap fields, are typically - returned as string path values </li> - <li>Return a {@link android.database.Cursor Cursor} object over a recordset in - reply to a query. This means implementing the query(), update(), insert(), - and delete() methods. As a courtesy, you might want to call {@link android.content.ContentResolver#notifyChange(android.net.Uri,android.database.ContentObserver) ContentResolver.notifyChange()} to notify - listeners about updated information. </li> - - <li>Add a <code><provider></code> tag to AndroidManifest.xml, and use its - <em>authorities</em> attribute to define the authority part of the content type it should - handle. For example, if your content type is content://com.example.autos/auto - to request a list of all autos, then <em>authorities</em> would be <code>com.example.autos</code>. - Set the <em>multiprocess</em> attribute to true if data does not need to - be synchronized between multiple running versions of the content provider. </li> - - <li>If you are handling a new data type, you must define a new MIME type to return - for your implementation of {@link android.content.ContentProvider#getType(android.net.Uri) android.ContentProvider.getType(url)}. This type corresponds to the <code>content://</code> URI - submitted to getType(), which will be one of the content types handled by - the provider. The MIME type for each content type has two forms: one for - a specific record, and one for multiple records. Use the {@link android.net.Uri Uri} methods to help determine what is being requested. Here is - the general format for each: -<ul> -<li><code>vnd.android.cursor.item/vnd.<em>yourcompanyname.contenttype</em></code> -for a single row. For example, a request for train record 122 using -<pre>content://com.example.transportationprovider/trains/122</pre> -might return the MIME type -<code>vnd.android.cursor.item/vnd.example.rail</code> -</li> -<li><code>vnd.android.cursor.dir/vnd.<em>yourcompanyname.contenttype</em></code> -for multiple rows. For example, a request for all train records using -<pre>content://com.example.transportationprovider/trains</pre> -might return the MIME type -<code>vnd.android.cursor.dir/vnd.example.rail</code> -</li> -</ul> - - </li> -</ol> -<p>For an example of a private content provider implementation, see the NodePadProvider - class in the notepad sample application that ships with the SDK. </p> -<p>Here is a recap of the important parts of a content URI:</p> -<p><img src="../../images/content_uri.png" alt="Elements of a content URI" height="80" width="528"> </p> -<ol type="A"> - <li>Standard required prefix. Never modified. </li> - <li>Authority part. For third-party applications, this should be a fully-qualified - class to ensure uniqueness. This corresponds to the value in - the <code><provider></code> element's <em>authorities</em> attribute: - <code><provider class="TransportationProvider" - authorities="com.example.transportationprovider" - /></code> </li> - - <li>The path that the content provider uses to determine what kind of data is - being requested. This can be zero or more segments: if the content provider - exposes only one type of data (only trains, for example), this can be absent. - If it provides several types, including subtypes, this can be several elements - long: e.g., "<code>land/bus</code>, <code>land/train</code>, <code>sea/ship</code>, - and <code>sea/submarine</code>" to give four possibilities.</li> - <li>A specific record being requested, if any. This is the _id value of a specific - record being requested. If all records of a specific type are being requested, - omit this and the trailing slash: <code>content://com.example.transportationprovider/trains</code> </li> -</ol> - diff --git a/docs/html/guide/topics/data/data-storage.jd b/docs/html/guide/topics/data/data-storage.jd index 2b3491c..0a1ee02 100644 --- a/docs/html/guide/topics/data/data-storage.jd +++ b/docs/html/guide/topics/data/data-storage.jd @@ -1,16 +1,45 @@ page.title=Data Storage @jd:body + +<div id="qv-wrapper"> +<div id="qv"> + + <h2>Storage quickview</h2> + <ul> + <li>Fast, lightweight storage through system preferences</li> + <li>File storage to device internal or removable flash</li> + <li>Arbitrary and structured storage in databases</li> + <li>Support for network-based storage</li> + </ul> + + <h2>In this document</h2> + <ol> + <li><a href="#pref">Preferences</a></li> + <li><a href="#files">Files</a></li> + <li><a href="#db">Databases</a></li> + <li><a href="#netw">Network</a></li> + </ol> + + <h2>See also</h2> + <ol> + <li><a href="#pref">Content Providers and Content Resolvers</a></li> + </ol> + +</div> +</div> + <p> A typical desktop operating system provides a common file system that any application can use to store files that can be read by other applications (perhaps with some access control settings). Android uses a different system: On Android, all application data (including files) are private to that application. +</p> <p> However, Android also provides a standard way for an application to expose -its private data to other applications — through a content providers. +its private data to other applications — through content providers. A content provider is an optional component of an application that exposes read/write access to the application's data, subject to whatever restrictions it might impose. @@ -19,23 +48,19 @@ data, and a standard mechanism for reading the returned data. Android supplies a number of content providers for standard data types, such as image, audio, and video files and personal contact information. For more information on using content providers, see a separate document, -<a href="{@docRoot}devel/data/contentproviders.html">Content Providers</a>. +<a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>. +</p> <p> Whether or not you want to export your application's data to others, you need a way to store it. Android provides the following four mechanisms -for storing and retrieving data: - -<dl> -<dd><a href="#pref">Preferences</a> -<dd><a href="#files">Files</a> -<dd><a href="#db">Databases</a> -<dd><a href="#netw">Network</a> -</dl> - -<dl> -<dt><a name="pref"></a><b>Preferences</b></dt> -<dd>A lightweight mechanism to store and retrieve key-value pairs of primitive +for storing and retrieving data: <a href="#pref">Preferences</a>, +<a href="#files">Files</a>, <a href="#db">Databases</a>, and <a href="#netw">Network</a>. +</p> + + +<h2 id="pref">Preferences</h2> +<p>Preferences is a lightweight mechanism to store and retrieve key-value pairs of primitive data types. It is typically used to store application preferences, such as a default greeting or a text font to be loaded whenever the application is started. Call <code>{@link android.content.Context#getSharedPreferences(java.lang.String,int) @@ -44,11 +69,13 @@ your set of preferences if you want to share them with other components in the s application, or use <code>{@link android.app.Activity#getPreferences(int) Activity.getPreferences()}</code> with no name to keep them private to the calling activity. You cannot share preferences across applications (except by using a -content provider). +content provider). +</p> <p> Here is an example of setting user preferences for silent keypress mode for a calculator: +</p> <pre> import android.app.Activity; @@ -84,12 +111,13 @@ public static final String PREFS_NAME = "MyPrefsFile"; editor.commit(); } } -</pre></dd> +</pre> -<p> -<dt><a name="files"></a><b>Files</b></dt> -<dd>You can store files directly on the mobile device or on a removable + +<h2 id="files">Files</h2> +<p>You can store files directly on the mobile device or on a removable storage medium. By default, other applications cannot access these files. +</p> <p> To read data from a file, call {@link android.content.Context#openFileInput @@ -100,6 +128,7 @@ Context.openFileOutput()} with the name and path. It returns a {@link java.io.FileOutputStream} object. Calling these methods with name and path strings from another application will not work; you can only access local files. +</p> <p> If you have a static file to package with your application at compile time, @@ -108,11 +137,12 @@ and then open it with {@link android.content.res.Resources#openRawResource(int) Resources.openRawResource (R.raw.<em>myDataFile</em>)}. It returns an {@link java.io.InputStream} object that you can use to read from the file. -</dd> +</p> -<dt><a name="db"></a><b>Databases</b></dt> -<dd>The Android API contains support for creating and using SQLite databases. +<h2 id="db">Databases</h2> +<p>The Android API contains support for creating and using SQLite databases. Each database is private to the application that creates it. +</p> <p> The {@link android.database.sqlite.SQLiteDatabase} object represents a database @@ -120,6 +150,7 @@ and has methods for interacting with it — making queries and managing the data. To create the database, call <code>{@link android.database.sqlite.SQLiteDatabase#create SQLiteDatabase.create()}</code> and also subclass {@link android.database.sqlite.SQLiteOpenHelper}. +</p> <p> As part of its support for the SQLite database system, Android exposes @@ -128,16 +159,19 @@ wrapped into useful objects. For example, Android defines a data type for contact information; it consists of many fields including a first and last name (strings), an address and phone numbers (also strings), a photo (bitmap image), and much other information describing a person. +</p> <p> Android ships with the sqlite3 database tool, which enables you to browse table contents, run SQL commands, and perform other useful functions on SQLite -databases. See <a href="{@docRoot}reference/adb.html#sqlite">Examine databases +databases. See <a href="{@docRoot}guide/developing/tools/adb.html#sqlite">Examine databases (sqlite3)</a> to learn how to run this program. +</p> <p> All databases, SQLite and others, are stored on the device in <code>/data/data/<em>package_name</em>/databases</code>. +</p> <p> Discussion of how many tables to create, what fields they contain, and how @@ -146,21 +180,20 @@ impose any limitations beyond the standard SQLite concepts. We do recommend including an autoincrement value key field that can be used as a unique ID to quickly find a record. This is not required for private data, but if you implement a content provider, you must include such a unique ID field. See the -<a href="{@docRoot}devel/data/contentproviders.html">Content Providers</a> +<a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a> document for more information on this field and the NotePadProvider class in the NotePad sample code for an example of creating and populating a new database. Any databases you create will be accessible by name to any other -class in the application, but not outside the application.</p> -</dd> - -<dt><a name="netw"></a><b>Network</b></dt> -<dd>You can also use the network to store and retrieve data (when it's available). -To do network operations, use the classes in the following packages: -<dl> - <dd><code>{@link java.net java.net.*}</code></dd> - <dd><code>{@link android.net android.net.*}</code></dd> -</dl> -</dd> - -</dl> +class in the application, but not outside the application. +</p> + + +<h2 id="netw">Network</h2> +<p>You can also use the network to store and retrieve data (when it's available). +To do network operations, use the classes in the following packages:</p> + +<ul class="no-style"> + <li><code>{@link java.net java.net.*}</code></li> + <li><code>{@link android.net android.net.*}</code></li> +</ul> diff --git a/docs/html/guide/topics/data/index.html b/docs/html/guide/topics/data/index.html new file mode 100644 index 0000000..a94f8c0 --- /dev/null +++ b/docs/html/guide/topics/data/index.html @@ -0,0 +1,9 @@ +<html> +<head> +<meta http-equiv="refresh" content="0;url=data-storage.html"> +<title>Redirecting...</title> +</head> +<body> +<a href="data-storage.html">click here</a> if you are not redirected. +</body> +</html>
\ No newline at end of file diff --git a/docs/html/guide/topics/drawing/index.html b/docs/html/guide/topics/drawing/index.html new file mode 100644 index 0000000..43c1499 --- /dev/null +++ b/docs/html/guide/topics/drawing/index.html @@ -0,0 +1,9 @@ +<html> +<head> +<meta http-equiv="refresh" content="0;url=opengl.html"> +<title>Redirecting...</title> +</head> +<body> +<a href="opengl.html">click here</a> if you are not redirected. +</body> +</html>
\ No newline at end of file diff --git a/docs/html/guide/topics/fundamentals.jd b/docs/html/guide/topics/fundamentals.jd new file mode 100644 index 0000000..7118ceb --- /dev/null +++ b/docs/html/guide/topics/fundamentals.jd @@ -0,0 +1,1411 @@ +page.title=Application Fundamentals +@jd:body + +<div id="qv-wrapper"> +<div id="qv"> +<h2>Key classes</h2> +<ol> +<li>{@link android.app.Activity}</li> +<li>{@link android.app.Service}</li> +<li>{@link android.content.BroadcastReceiver}</li> +<li>{@link android.content.ContentProvider}</li> +<li>{@link android.content.Intent}</li> +</ol> + +<h2>In this document</h2> +<ol> +<li><a href="#appcomp">Application Components</a> + <ol> + <li><a href="#actcomp">Activating components: intents</a></li> + <li><a href="#manfile">The manifest file</a></li> + <li><a href="#ifilters">Intent filters</a></li> + </ol></li> +<li><a href="#acttask">Activities and Tasks</a> + <ol> + <li><a href="#afftask">Affinities and new tasks</a></li> + <li><a href="#lmodes">Launch modes</a></li> + <li><a href="#clearstack">Clearing the stack</a></li> + <li><a href="#starttask">Starting tasks</a></li> + </ol></li> +<li><a href="#procthread">Processes and Threads</a></li> +<li><a href="#lcycles">Lifecycles</a> + <ol> + <li><a href="#actlife">Activity lifecycle</a></li> + <li><a href="#servlife">Service lifecycle</a></li> + <li><a href="#broadlife">Broadcast receiver lifecycle</a></li> + <li><a href="#proclife">Processes and lifecycles</a></li> + </ol></li> +</div> +</div> + +<p> +Android applications are written in the Java programming language. +The compiled Java code — along with data and +resource files required by the application and a manifest describing the +application — is bundled by the aapt tool into an <i>Android package</i>, +an archive file marked by an {@code .apk} suffix. This file is the vehicle +for distributing the application and installing it on mobile devices; it's +the file users download to their devices. All the code in a single +{@code .apk} file is considered to be one <i>application</i>. +</p> + +<p> +In many ways, each Android application lives in its own world: +</p> + +<ul> +<li>By default, every application runs in its own Linux process. +Android starts the process when any of the application's code needs to be +executed, and shuts down the process when it's no longer needed and system +resources are required by other applications.</li> + +<li>Each process has its own Java virtual machine (VM), so application code +runs in isolation from the code of all other applications.</li> + +<li>By default, each application is assigned a unique Linux user ID. +Permissions are set so that the application's files are visible only +that user, only to the application itself — although there are ways +to export them to other applications as well.</li> +</ul> + +<p> +It's possible to arrange for two applications to share the same user ID, +in which case they will be able to see each other's files. To conserve +system resources, applications with the same ID can also arrange to run +in the same Linux process, sharing the same VM. +</p> + + +<h2><a name="appcomp"></a>Application Components</h2> + +<p> +A central feature of Android is that one application can make use of elements +of other applications (provided those applications permit it). For example, +if your application needs to display a scrolling list of images and another +application has developed a suitable scroller and made it available to others, +you can call upon that scroller to do the work, rather than develop your own. +Your application doesn't incorporate the code of the other application or +link to it. Rather, it simply starts up that piece of the other application +when the need arises. +</p> + +<p> +For this to work, the system must be able to start an application process +when any part of it is needed, and instantiate the Java objects for that part. +Therefore, unlike applications on most other systems, Android applications don't +have a single entry point for everything in the application (no {@code main()} +function, for example). Rather, they have essential <i>components</i> that +the system can instantiate and run as needed. There are four types of components: +</p> + +<dl> + +<dt><b>Activities</b></dt> +<dd>An <i>activity</i> presents a visual user interface for one focused endeavor +the user can undertake. For example, an activity might present a list of +menu items users can choose from or it might display photographs along +with their captions. A text messaging application might have one activity +that shows a list of contacts to send messages to, a second activity to write +the message to the chosen contact, and other activities to review old messages +or change settings. Though they work together to form a cohesive user interface, +each activity is independent of the others. +Each one is implemented as a subclass of the {@link android.app.Activity} base class. + +<p> +An application might consist of just one activity or, like the text messaging +application just mentioned, it may contain several. +What the activities are, and how many there are depends, of course, on the +application and its design. Typically, one of the activities is marked +as the first one that should be presented to the user when the application is +launched. Moving from one activity to another is accomplished by having the +current activity start the next one. +</p> + +<p> +Each activity is given a default window to draw in. Typically, the window +fills the screen, but it might be smaller than the screen and float on top +of other windows. An activity can also make use of additional windows — +for example, a window that presents users with vital information when they +select a particular item on-screen, or a pop-up dialog that calls for a user +response in the midst of the activity. +</p> + +<p> +The visual content of the window is provided by a hierarchy of views — +objects derived from the base {@link android.view.View} class. Each view +draws in a particular rectangular space within the window and responds to user +actions directed at that space. Android has a number of ready-made views that +you can use — including buttons, text fields, scroll bars, menu items, +check boxes, and more. A view hierarchy is placed within the activity's +window by the <code>{@link android.app.Activity#setContentView +Activity.setContentView()}</code> method. The <i>content view</i> +is the View object at the root of the hierarchy. +(See <a href="{@docRoot}guide/topics/views/index.html">Views and Layout</a> +for more information on views and the heirarchy.) +</p></dd> + +<p><dt><b>Services</b></dt> +<dd>A <i>service</i> doesn't have a visual user interface, but rather runs in +the background for an indefinite period of time. For example, a service might +play background music as the user attends to other matters, or it might fetch +data over the network or calculate something and provide the result to activities +that need it. Each service extends the {@link android.app.Service} base class. + +<p> +A good example is a media player playing songs from a play list. The player +application would probably have one or more activities that allow the user to +choose songs and start playing them. However, the music playback itself would +not be handled by an activity because users will expect the music to keep +playing even after they leave the player and begin something different. +To keep the music going, the media player activity could start a service to run +in the background. The system will then keep the music playback service running +even after the activity that started it leaves the screen. +</p> + +<p> +It's possible to connect to (bind to) an ongoing service (and start the service +if it's not already running). While connected, you can communicate with the +service through an interface that the service exposes. For the music service, +this interface might allow users to pause, rewind, stop, and restart the playback. +</p> + +<p> +Like activities and the other components, services run in the main thread of +the application process. So that they won't block other components or the +user interface, they often spawn another thread for time-consuming tasks +(like music playback). See <a href="#procthread">Processes and Threads</a>, later. +</p></dd> + +<dt><b>Broadcast receivers</b></dt> +<dd>A <i>broadcast receiver</i> is a component that does nothing but +receive and react to broadcast announcements. Many broadcasts originate in +system code — for example, announcements that the timezone has changed, +that the battery is low, that the keyboard has been exposed, or that the user +changed a language preference. + +<p> +An application can have any number of broadcast receivers to respond to any +announcements it considers important. All receivers extend the {@link +android.content.BroadcastReceiver} base class. +</p> + +<p> +Broadcast receivers do not display a user interface. However, they may start +an activity in response to the information they receive, or they may use +the {@link android.app.NotificationManager} to alert the user. Notifications +can get the user's attention in various ways — flashing +the backlight, vibrating the device, playing a sound, and so on. They +typically place a persistent icon in the status bar, which users can open to +get the message. +</p></dd> + +<dt><b>Content providers</b></dt> +<dd>A <i>content provider</i> makes a specific set of the application's data +available to other applications. The data can be stored in the file system, +in an SQLite database, or in any other manner that makes sense. +The content provider extends the {@link android.content.ContentProvider} base +class to implement a standard set of methods that enable other applications +to retrieve and store data of the type it controls. However, applications +do not call these methods directly. Rather they use a {@link +android.content.ContentResolver} object and call its methods instead. +A ContentResolver can talk to any content provider; it cooperates with the +provider to manage any interprocess communication that's involved. + +<p> +See the separate +<a href="{@docRoot}guide/topics/providers/content-providers.html">Content +Providers</a> document for more information on using content providers. +</p></dd> + +</dl> + +<p> +Whenever there's a request that should be handled by a particular component, +Android makes sure that the application process of the component is running, +starting it if necessary, and that an appropriate instance of the component +is available, creating the instance if necessary. +</p> + + +<h3><a name="actcomp"></a>Activating components: intents</h3> + +<p> +Content providers are activated when they're targeted by a request from a +ContentResolver. The other three components — activities, services, +and broadcast receivers — are activated by asynchronous messages +called <i>intents</i>. An intent is an {@link android.content.Intent} +object that holds the content of the message. Among other things, it names +the action an activity or service is being requested to take and specifies +the URI of the data to act on. For broadcast receivers, it names the +action being announced. For example, it might convey a request for +an activity to present an image to the user or let the user edit some +text. Or it might announce to interested broadcast receivers that the +camera button has been pressed. +</p> + +<p> +There are separate methods for activiating each type of component: +</p> + +<ul> + +<li>An activity is launched (or given something new to do) by passing an +Intent object to <code>{@link android.content.Context#startActivity +Context.startActivity()}</code> or <code>{@link +android.app.Activity#startActivityForResult +Activity.startActivityForResult()}</code>. The responding activity can +look at the initial intent that caused it to be launched by calling its +<code>{@link android.app.Activity#getIntent getIntent()}</code> method. +Android calls the activity's <code>{@link +android.app.Activity#onNewIntent onNewIntent()}</code> method to pass +it any subsequent intents. + +<p> +One activity often starts the next one. If it expects a result back from +the activity it's starting, it calls {@code startActivityForResult()} +instead of {@code startActivity()}. For example, if it starts an activity +that lets the user pick a photo, it might expect to be returned the chosen +photo. The result is returned in an Intent object that's passed to the +calling activity's <code>{@link android.app.Activity#onActivityResult +onActivityResult()}</code> method. +</p> +</li> + +<li><p>A service is started (or new instructions are given to an ongoing +service) by passing an Intent object to <code>{@link +android.content.Context#startService Context.startService()}</code>. +Android calls the service's <code>{@link android.app.Service#onStart +onStart()}</code> method and passes it the Intent object.</p> + +<p> +Similarly, an intent can be passed to <code>{@link +android.content.Context#bindService Context.bindService()}</code> to +establish an ongoing connection between the calling component and a +target service. It initiates the service if it's not already running. +The service receives the Intent object in +an <code>{@link android.app.Service#onBind onBind()}</code> call. +For example, an activity might establish a connection with the music +playback service mentioned earlier so that it could provide the user +with an interface for controlling the playback. The activity would +call {@code bindService()} to set up that connection. +</p> +</li> + +<li><p>An application can initiate a broadcast by passing an Intent object to +methods like <code>{@link +android.content.Context#sendBroadcast(Intent) Context.sendBroadcast()}</code>, +<code>{@link android.content.Context#sendOrderedBroadcast(Intent, String) +Context.sendOrderedBroadcast()}</code>, and <code>{@link +android.content.Context#sendStickyBroadcast Context.sendStickyBroadcast()}</code> +in any of their variations. Android delivers the intent to all interested +broadcast receivers by calling their <code>{@link +android.content.BroadcastReceiver#onReceive onReceive()}</code> methods.</p></li> + +</ul> + +<p> +For more on intent messages, see the separate article, <a +href="{@docRoot}guide/topics/intents/intents-filters.html">Intents +and Intent Filters</a>. + + +<h3><a name="manfile"></a>The manifest file</h3> + +<p> +Before Android can start an application component, it must learn that +the component exists. Therefore, applications declare their components +in a manifest file that's bundled into the Android package, the {@code .apk} +file that also holds the application's code, files, and resources. +</p> + +<p> +The manifest is a structured XML file and is always named AndroidManifest.xml +for all applications. It does a number of things in addition to declaring the +application's components, such as naming any libraries the application needs +to be linked against (besides the default Android library) and identifying +any permissions the application expects to be granted. +</p> + +<p> +But the principal task of the manifest is to inform Android about the application's +components. For example, an activity might be declared as follows: +</p> + +<pre><?xml version="1.0" encoding="utf-8"?> +<manifest . . . > + <application . . . > + <activity android:name="com.example.project.FreneticActivity" + android:icon="@drawable/small_pic.png" + android:label="@string/freneticLabel" + . . . > + </activity> + . . . + </application> +</manifest></pre> + +<p> +The {@code name} attribute of the {@code <activity>} element +names the {@link android.app.Activity} subclass that implements the +activity. The {@code icon} and {@code label} attributes point to +resource files containing an icon and label that can be displayed +to users to represent the activity. +</p> + +<p> +The other components are declared in a similar way — +{@code <service>} elements for services, {@code <receiver>} +elements for broadcast receivers, and {@code <provider>} elements +for content providers. Activities, services, and content providers that +are not declared in the manifest are not visible to the system and are +consequently never run. Broadcast receivers can be declared in the +manifest, or they can be created dynamically in code (as +{@link android.content.BroadcastReceiver} objects) +and registered with the system by calling <code>{@link +android.content.Context#registerReceiver Context.registerReceiver()}</code>. +</p> + +<p> +For more on how to structure a manifest file for your application, see +<a href="{@docRoot}guide/topics/manifest/manifest.html">The Manifest File</a>. +</p> + + +<h3><a name="ifilters"></a>Intent filters</h3> + +<p> +An Intent object can explicitly name a target component. If it does, +Android finds that component (based on the declarations in the manifest +file) and activates it. But if a target is not explicitly named, +Android must locate the best component to respond to the intent. +It does so by comparing the Intent object to the <i>intent filters</i> +of potential targets. A component's intent filters inform Android of +the kinds of intents the component is able to handle. Like other +essential information about the component, they're declared in the +manifest file. Here's an extension of the previous example that adds +two intent filters to the activity: +</p> + +<pre><?xml version="1.0" encoding="utf-8"?> +<manifest . . . > + <application . . . > + <activity android:name="com.example.project.FreneticActivity" + android:icon="@drawable/small_pic.png" + android:label="@string/freneticLabel" + . . . > + <intent-filter . . . > + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + <intent-filter . . . > + <action android:name="com.example.project.BOUNCE" /> + <data android:type="image/jpeg" /> + <category android:name="android.intent.category.DEFAULT" /> + </intent-filter> + </activity> + . . . + </application> +</manifest></pre> + +<p> +The first filter in the example — the combination of the action +"{@code android.intent.action.MAIN}" and the category +"{@code android.intent.category.LAUNCHER}" — is a common one. +It marks the activity as one that should be represented in the +application launcher, the screen listing applications users can launch +on the device. In other words, the activity is the entry point for +the application, the initial one users would see when they choose +the application in the launcher. +</p> + +<p> +The second filter declares an action that the activity can perform on +a particular type of data. +</p> + +<p> +A component can have any number of intent filters, each one declaring a +different set of capabilities. If it doesn't have any filters, it can +be activated only by intents that explicitly name the component as the +target. +</p> + +<p> +For a broadcast receiver that's created and registered in code, the +intent filter is instantiated directly as an {@link android.content.IntentFilter} +object. All other filters are set up in the manifest. +</p> + +<p> +For more on intent filters, see a separate document, +<a href="{@docRoot}guide/topics/intents/intents-filters.html">Intents +and Intent Filters</a>. +</p> + + +<h2><a name="acttask"></a>Activities and Tasks</h2> + +<p> +As noted earlier, one activity can start another, including one defined +in a different application. Suppose, for example, that you'd like +to let users display a street map of some location. There's already an +activity that can do that, so all your activity needs to do is put together +an Intent object with the required information and pass it to +{@code startActivity()}. The map viewer will display the map. When the user +hits the BACK key, your activity will reappear on screen. +</p> + +<p> +To the user, it will seem as if the map viewer is part of the same application +as your activity, even though it's defined in another application and runs in +that application's process. Android maintains this user experience by keeping +both activities in the same <i>task</i>. Simply put, a task is what the user +experiences as an "application." It's a group of related activities, arranged +in a stack. The root activity in the stack is the one that began the task +— typically, it's an activity the user selected in the application launcher. +The activity at the top of the stack is one that's currently running — +the one that is the focus for user actions. When one activity starts another, +the new activity is pushed on the stack; it becomes the running activity. +The previous activity remains in the stack. When the user presses the BACK key, +the current activity is popped from the stack, and the previous one resumes as +the running activity. Activities in the stack are never rearranged, only +pushed and popped. +</p> + +<p> +The stack contains objects, so if a task has more than one instance of the same +Activity subclass open — multiple map viewers, for example — the +stack has a separate entry for each instance. +</p> + +<p> +A task is a stack of activities, not a class or an element in the manifest file. +So there's no way to set values for a task independently of its activities. +Values for the task as a whole are set in the root activity. For example, the +next section will talk about the "affinity of a task"; that value is read from +the affinity set for the task's root activity. +</p> + +<p> +All the activities in a task move together as a unit. The entire task (the entire +activity stack) can be brought to the foreground or sent to the background. +Suppose, for instance, that the current task has four activities in its stack +— three under the current activity. The user presses the HOME key, goes +to the application launcher, and selects a new application (actually, a new <i>task</i>). +The current task goes into the background and the root activity for the new task is displayed. +Then, after a short period, the user goes back to the home screen and again selects +the previous application (the previous task). That task, with all four +activities in the stack, comes forward. When the user presses the BACK +key, the screen does not display the activity the user just left (the root +activity of the previous task). Rather, the activity on the top of the stack +is removed and the previous activity in the same task is displayed. +</p> + +<p> +The behavior just described is the default behavior for activities and tasks. +But there are ways to modify almost all aspects of it. The association of +activities with tasks, and the behavior of an activity within a task, is +controlled by the interaction between flags set in the Intent object that +started the activity and attributes set in the activity's {@code <activity>} +element in the manifest. Both requester and respondent have a say in what happens. +</p> + +<p> +In this regard, the principal Intent flags are: + +<p style="margin-left: 2em">{@code FLAG_ACTIVITY_NEW_TASK} +<br/>{@code FLAG_ACTIVITY_CLEAR_TOP} +<br/>{@code FLAG_ACTIVITY_RESET_TASK_IF_NEEDED} +<br/>{@code FLAG_ACTIVITY_SINGLE_TOP}</p> + +<p> +The principal {@code <activity>} attributes are: + +<p style="margin-left: 2em">{@code taskAffinity} +<br/>{@code launchMode} +<br/>{@code allowTaskReparenting} +<br/>{@code clearTaskOnLaunch} +<br/>{@code alwaysRetainTaskState} +<br/>{@code finishOnTaskLaunch}</p> + +<p> +The following sections describe what some of these flags and attributes do, +and how they interact. +</p> + + +<h3><a name="afftask"></a>Affinities and new tasks</h3> + +<p> +By default, all the activities in an application have an <i>affinity</i> for each +other — that is, there's a preference for them all to belong to the +same task. However, an individual affinity can be set for each activity +with the {@code taskAffinity} attribute. Activities defined in different +applications can share an affinity, or activities defined in the same +application can be assigned different affinities. +The affinity comes into play in two circumstances: When the Intent object +that launches an activity contains the {@code FLAG_ACTIVITY_NEW_TASK} flag, +and when an activity has its {@code allowTaskReparenting} attribute set +to "{@code true}". +</p> + +<dl> +<dt>The <code>{@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK}</code> flag</dt> +<dd>As mentioned earlier, a new activity is, by default, launched into +the task of the activity that called {@code startActivity()}. It's pushed + onto the same stack as the caller. However, if the Intent object passed +to {@code startActivity()} contains the {@code FLAG_ACTIVITY_NEW_TASK} +flag, the system looks for a different task to house the new activity. +Often, as the name of the flag implies, it's a new task. However, it +doesn't have to be. If there's an existing task with the same affinity +as the new activity, the activity is launched into that task. If not, +it begins a new task.</dd> + +<dt>The {@code allowTaskReparenting} attribute</dt> +<dd>If an activity has its {@code allowTaskReparenting} attribute is +set to "{@code true}", it can move from the task it starts in to the task +it has an affinity for when that task comes to the fore. For example, +suppose that an activity that reports weather conditions in selected +cities is defined as part of a travel application. It has the same +affinity as other activities in the same application (the default +affinity) and it allows reparenting. One of your activities +starts the weather reporter, so it initially belongs to the same task as +your activity. However, when the travel application, next comes forward, +the weather reporter will be reassigned to and displayed with that task.</dd> +</dl> + +<p> +If an {@code .apk} file contains more than one "application" +from the user's point of view, you will probably want to assign different +affinities to the activities associated with each of them. +</p> + + +<h3><a name="lmodes"></a>Launch modes</h3> + +<p> +There are four different launch modes that can be assigned to an {@code +<activity>} element's {@code launchMode} attribute: +</p> + +<p style="margin-left: 2em">"{@code standard}" (the default value) +<br>"{@code singleTop}" +<br>"{@code singleTask}" +<br>"{@code singleInstance}"</p> + +<p> +The launch mode determines three things: +</p> + +<ul> +<li>Whether the activity can belong to a task that includes other +activities. The answer is yes for all the modes except +"{@code singleInstance}". A "{@code singleInstance}" activity is always +the only activity in its task. If it tries to launch another activity, +that activity is assigned to a different task — as if {@code +FLAG_ACTIVITY_NEW_TASK} was in the intent.</li> + +<li><p>Whether the activity always begins a task. For "{@code singleTask}" +and "{@code singleInstance}" the answer is yes. They mark activities that +can only be the root activities of a task; they define a task. In contrast, +"{@code standard}" and "{@code singleTop}" activities can belong to any task. +</p></li> + +<li><p>Whether an existing instance of the activity can handle new +intents. The answer is yes for all the modes except "{@code standard}". +Existing "{@code singleTask}" and "{@code singleInstance}" activities +handle all new intents that come their way; a new instance is never +created. In the case of "{@code singleTask}", all other activities in +the task are popped from the stack, so that the root "{@code singleTask}" +activity is at the top and in position to respond to the intent. +</p> + +<p> +If a "{@code singleTop}" activity is at the +top of its stack, that object is expected to handle any new intents. +However, if it's farther down the stack, a new instance is created for +the intent and pushed on the stack. +</p> + +<p> +In contrast, a new instance of a "{@code standard}" activity is always +created for each new intent. +</p> +</li> +</ul> + +<p> +When an existing activity is asked to handle a new intent, the Intent +object is passed to the activity in an <code>{@link android.app.Activity#onNewIntent +onNewIntent()}</code> call. (The intent object that originally started the +activity can be retrieved by calling +<code>{@link android.app.Activity#getIntent getIntent()}</code>.) +</p> + +<p> +Note that when a new instance of an Activity is created to handle a new +intent, the user can always press the BACK key to return to the previous state +(to the previous activity). But when an existing instance of an +Activity handles a new intent, the user cannot press the BACK key to +return to what that instance was doing before the new intent arrived. +</p> + +<p> +For more on launch modes, see +<a href="{@docRoot}guide/topics/manifest/manifest.html">The +AndroidManifest.xml File</a> +</p> + + +<h3><a name="clearstack"></a>Clearing the stack</h3> + +<p> +If the user leaves a task for a long time, the system clears the task of all +activities except the root activity. When the user returns to the task again, +it's as the user left it, except that only the initial activity is present. +The idea is that, after +a time, users will likely have abandoned what they were doing before and are +returning to the task to begin something new. +</p> + +<p> +That's the default. There are some activity attributes that can be used to +control this behavior and modify it: +</p> + +<dl> +<dt>The {@code alwaysRetainTaskState} attribute</dt> +<dd>If this attribute is set to "{@code true}" in the root activity of a task, +the default behavior just described does not happen. +Activities are retained in the stack even after a long period.</dd> + +<dt>The {@code clearTaskOnLaunch} attribute</dt> +<dd>If this attribute is set to "{@code true}" in the root activity of a task, +the stack is cleared down to the root activity whenever the user leaves the task +and returns to it. In other words, it's the polar opposite of +{@code alwaysRetainTaskState}. The user always returns to the task in its +initial state, even after a momentary absence.</dd> + +<dt>The {@code finishOnTaskLaunch} attribute</dt> +<dd>This attribute is like {@code clearTaskOnLaunch}, but it operates on a +single activity, not an entire task. And it can cause any activity to go +away, including the root activity. When it's set to "{@code true}", the +activity remains part of the task only for the current session. If the user +leaves and then relaunches the task, it no longer is present.</dd> +</dl> + +<p> +There's another way to force activities to be removed from the stack. +If an Intent object includes the <code>{@link +android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP FLAG_ACTIVITY_CLEAR_TOP}</code> +flag, and the target task already has an instance of the type of activity that +should handle the intent in its stack, all activities above that instance +are cleared away so that it stands at the top of the stack and can respond +to the intent. +</p> + +<p> +{@code FLAG_ACTIVITY_CLEAR_TOP} is most often used in conjunction +with {@code FLAG_ACTIVITY_NEW_TASK}. When used together, these flags are +a way of locating an existing activity in another task and putting it in +a position where it can respond to the intent. +</p> + + +<h3><a name="starttask"></a>Starting tasks</h3> + +<p> +An activity is set up as the entry point for a task by giving it +an intent filter with "{@code android.intent.action.MAIN}" as the +specified action and "{@code android.intent.category.LAUNCHER}" as +the specified category. (There's an example of this type of filter +in the earlier <a href="#ifilters">Intent Filters</a> section.) +A filter of this kind causes an icon and label for the activity to be +displayed in the application launcher, giving users a way both to +launch the task and to return to it at any time after it has been +launched. +</p> + +<p> +This second ability is important: Users must be able to leave a task +and then come back to it later. For this reason, the two launch modes +that mark activities as always initiating a task, "{@code singleTask}" +and "{@code singleInstance}", should be used only when the activity has +a {@code MAIN} and {@code LAUNCHER} filter. +Imagine, for example, what could happen if the filter is missing. +An intent launches a "{@code singleTask}" activity, initiating a new task, +and the user spends some time working in that task. The user then presses +the HOME key. The task is now ordered behind and obscured by the home +screen. And, because it is not represented in the application launcher, +the user has no way to return to it. +</p> + +<p> +A similar difficulty attends the {@code FLAG_ACTIVITY_NEW_TASK} flag. +If this flag causes an activity to +begin a new task and the user presses the HOME key to leave it, there +must be some way for the user to navigate back to it again. Some +entities (such as the notification manager) always start activities +in an external task, never as part of their own, so they always put +{@code FLAG_ACTIVITY_NEW_TASK} in the intents they pass to +{@code startActivity()}. If you have an activity that can be invoked +by an external entity that might use this flag, take care that the user +has a independent way to get back to the task that's started. +</p> + +<p> +For those cases where you don't want the user to be able to return +to an activity, set the {@code <activity>} element's {@code +finishOnTaskLaunch} to "{@code true}". +See <a href="#clearstack">Clearing the stack</a>, earlier. +</p> + + +<h2><a name="procthread"></a>Processes and Threads</h2> + +<p> +When the first of an application's components needs to be run, Android +starts a Linux process for it with a single thread of execution. By default, +all components of the application run in that process and thread. +</p> + +<p> +However, you can arrange for components to run in other processes as well as +spawn additional threads: +</p> + +<ul> +<li>The process where a component runs is controlled by the manifest file. +The component elements — {@code <activity>}, +{@code <service>}, {@code <receiver>}, and {@code <provider>} +— each have a {@code process} attribute that can specify a process +where that component should run. These attributes can be set so that each +component runs in its own process, or so that some components share a process +while others do not. They can also be set so that components of +different applications run in the same process — provided that the +applications share the same Linux user ID and are signed by the same authorities. +The {@code <application>} element also has a {@code process} attribute, +for setting a default value that applies to all components.</li> + +<li><p>Threads are created in code using standard Java {@link java.lang.Thread} +objects. Android provides a number of convenience classes for managing threads +— {@link android.os.Looper} for running a message loop within a thread, +{@link android.os.Handler} for processing messages, and +{@link android.os.HandlerThread} for setting up a thread with a message loop.</p> + +<p> +Even though you may confine your application to a single process, there may be +times when you will need to spawn a thread to do some background work. Since the +user interface must always be quick to respond to user actions, the +thread that hosts an activity should not also host time-consuming operations like +network downloads, or anything else that may not be completed quickly. +</p></li> +</ul> + +<p> +Android may decide to shut down a process at some point, when memory is +low and required by other applications that are more immediately serving +the user. Application components running in the process are consequently +destroyed. A process is restarted for those components when there's again +work for them to do. +</p> + +<p> +When deciding which processes to terminate, Android weighs their relative +importance to the user. For example, it more readily shuts down a process +with activities that are no longer visible on screen than a process with +visible activities. +The decision whether to terminate a process, therefore, depends on the state +of the components running in that process. Those states are the subject of +the next section, <a href="#lcycles">Lifecycles</a>. +</p> + + +<h2><a name="lcycles"></a>Lifecycles</h2> + +<p> +Application components have a lifecycle — a beginning when +Android instantiates them to respond to intents through to an end when +the instances are destroyed. In between, they may sometimes be active +or inactive, or, in the case of activities, visible to the user or +invisible. This section discusses the lifecycles of activities, +services, and broadcast receivers — including the states that they +can be in during their lifetimes, the methods that notify you of transitions +between states, and the effect of those states on the possibility that +the process hosting them might be terminated and the instances destroyed. +</p> + + +<h3><a name="actlife"></a>Activity lifecycle</h3> + +<p>An activity has essentially three states:</p> + +<ul> +<li> It is <em>active</em> or <em>running</em> when it is in the foreground of the +screen (at the top of the activity stack for the current task). This is the +activity that is the focus for the user's actions.</li> + +<li><p>It is <em>paused</em> if it has lost focus but is still visible to the user. +That is, another activity lies on top of it and that activity either is transparent +or doesn't cover the full screen, so some of the paused activity can show through. +A paused activity is completely alive (it maintains all state and member information +and remains attached to the window manager), but can be killed by the system in +extreme low memory situations.</p></li> + +<li><p>It is <em>stopped</em> if it is completely obscured by another activity. +It still retains all state and member information. However, it is no longer +visible to the user so its window is hidden and it will often be killed by the +system when memory is needed elsewhere.</p></li> +</ul> + +<p> +If an activity is paused or stopped, the system can drop it from memory either +by asking it to finish (calling its {@link android.app.Activity#finish finish()} +method), or simply killing its process. When it is displayed again +to the user, it must be completely restarted and restored to its previous state. +</p> + + +<h4>Lifecycle methods</h4> + +<p> +As an activity transitions from state to state, it is notified of the change +by calls to the following protected methods: + +<p style="margin-left: 2em">{@code void onCreate(Bundle <i>savedInstanceState</i>)} +<br/>{@code void onStart()} +<br/>{@code void onRestart()} +<br/>{@code void onResume()} +<br/>{@code void onPause()} +<br/>{@code void onStop()} +<br/>{@code void onDestroy()}</p> + +<p> +All of these methods are hooks that you can override to do appropriate work +when the state changes. +All activities must implement <code>{@link android.app.Activity#onCreate +onCreate()}</code> to do initial setup when the activity is first instantiated. +Many will also implement <code>{@link android.app.Activity#onPause onPause()}</code> +to commit data changes and otherwise prepare to stop interacting with the user. +</p> + +<div class="sidebox-wrapper"> +<div class="sidebox"> +<h2>Calling into the superclass</h2> +<p> +An implementation of any activity lifecycle method should always first +call the superclass version. For example: +</p> + +<pre>protected void onPause() { + super.onPause(); + . . . +}</pre> +</div> +</div> + + +<p> +Taken together, these seven methods define the entire lifecycle of an +activity. There are three nested loops that you can monitor by +implementing them: +</p> + +<ul> +<li>The <b>entire lifetime</b> of an activity happens between the first call +to <code>{@link android.app.Activity#onCreate onCreate()}</code> through to a +single final call to <code>{@link android.app.Activity#onDestroy}</code>. +An activity does all its initial setup of "global" state in {@code onCreate()}, +and releases all remaining resources in {@code onDestroy()}. For example, +if it has a thread running in the background to download data from the network, +it may create that thread in {@code onCreate()} and then stop the thread in +{@code onDestroy()}.</li> + +<li><p>The <b>visible lifetime</b> of an activity happens between a call to +<code>{@link android.app.Activity#onStart onStart()}</code> until a +corresponding call to <code>{@link android.app.Activity#onStop onStop()}</code>. +During this time, the user can see the activity on-screen, though it may not +be in the foreground and interacting with the user. Between these two methods, +you can maintain resources that are needed to show the activity to the user. +For example, you can register a {@link android.content.BroadcastReceiver} in +{@code onStart()} to monitor for changes that impact your UI, and unregister +it in {@code onStop()} when the user can no longer see what you are displaying. +The {@code onStart()} and {@code onStop()} methods can be called multiple times, +as the activity alternates between being visible and hidden to the user.</p></li> + +<li><p>The <b>foreground lifetime</b> of an activity happens between a call +to <code>{@link android.app.Activity#onResume onResume()}</code> until a +corresponding call to <code>{@link android.app.Activity#onPause onPause()}</code>. +During this time, the activity is in front of all other activities on screen and +is interacting with the user. An activity can frequently transition between the +resumed and paused states — for example, {@code onPause()} is called when +the device goes to sleep or when a new activity is started, {@code onResume()} +is called when an activity result or a new intent is delivered. Therefore, the +code in these two methods should be fairly lightweight.</p></li> +</ul> + +<p> +The following diagram illustrates these loops and the paths an activity +may take between states. The colored ovals are major states the activity +can be in. The square rectangles represent the callback methods you can implement +to perform operations when the activity transitions between states. +<p> + +<p><img src="{@docRoot}images/activity_lifecycle.png" +alt="State diagram for an Android activity lifecycle." border="0" /></p> + +<p> +The following table describes each of these methods in more detail and +locates it within the activity's overall lifecycle: +</p> + +<table border="2" width="85%" align="center" frame="hsides" rules="rows"> +<colgroup align="left" span="3" /> +<colgroup align="left" /> +<colgroup align="center" /> +<colgroup align="center" /> + +<thead> +<tr><th colspan="3">Method</th> <th>Description</th> <th>Killable?</th> <th>Next</th></tr> +</thead> + +<tbody> +<tr> + <td colspan="3" align="left" border="0"><code>{@link android.app.Activity#onCreate onCreate()}</code></td> + <td>Called when the activity is first created. + This is where you should do all of your normal static set up — + create views, bind data to lists, and so on. This method is passed + a Bundle object containing the activity's previous state, if that + state was captured (see <a href="#actstate">Saving Activity State</a>, + later). + <p>Always followed by {@code onStart()}.</p></td> + <td align="center">No</td> + <td align="center">{@code onStart()}</td> +</tr> + +<tr> + <td rowspan="5" style="border-left: none; border-right: none;"> </td> + <td colspan="2" align="left" border="0"><code>{@link android.app.Activity#onRestart +onRestart()}</code></td> + <td>Called after the activity has been stopped, just prior to it being + started again. + <p>Always followed by {@code onStart()}</p></td> + <td align="center">No</td> + <td align="center">{@code onStart()}</td> +</tr> + +<tr> + <td colspan="2" align="left" border="0"><code>{@link android.app.Activity#onStart onStart()}</code></td> + <td>Called just before the activity becomes visible to the user. + <p>Followed by {@code onResume()} if the activity comes + to the foreground, or {@code onStop()} if it becomes hidden.</p></td> + <td align="center">No</td> + <td align="center">{@code onResume()} <br/>or<br/> {@code onStop()}</td> +</tr> + +<tr> + <td rowspan="2" style="border-left: none;"> </td> + <td align="left" border="0"><code>{@link android.app.Activity#onResume onResume()}</code></td> + <td>Called just before the activity starts + interacting with the user. At this point the activity is at + the top of the activity stack, with user input going to it. + <p>Always followed by {@code onPause()}.</p></td> + <td align="center">No</td> + <td align="center">{@code onPause()}</td> +</tr> + +<tr> + <td align="left" border="0"><code>{@link android.app.Activity#onPause onPause()}</code></td> + <td>Called when the system is about to start resuming another + activity. This method is typically used to commit unsaved changes to + persistent data, stop animations and other things that may be consuming + CPU, and so on. It should do whatever it does very quickly, because + the next activity will not be resumed until it returns. + <p>Followed either by {@code onResume()} if the activity + returns back to the front, or by {@code onStop()} if it becomes + invisible to the user.</td> + <td align="center"><font color="#800000"><strong>Yes</strong></font></td> + <td align="center">{@code onResume()} <br/>or<br/> {@code onStop()}</td> +</tr> + +<tr> + <td colspan="2" align="left" border="0"><code>{@link android.app.Activity#onStop onStop()}</code></td> + <td>Called when the activity is no longer visible to the user. This + may happen because it is being destroyed, or because another activity + (either an existing one or a new one) has been resumed and is covering it. + <p>Followed either by {@code onRestart()} if + the activity is coming back to interact with the user, or by + {@code onDestroy()} if this activity is going away.</p></td> + <td align="center"><font color="#800000"><strong>Yes</strong></font></td> + <td align="center">{@code onRestart()} <br/>or<br/> {@code onDestroy()}</td> +</tr> + +<tr> + <td colspan="3" align="left" border="0"><code>{@link android.app.Activity#onDestroy +onDestroy()}</code></td> + <td>Called before the activity is destroyed. This is the final call + that the activity will receive. It could be called either because the + activity is finishing (someone called <code>{@link android.app.Activity#finish + finish()}</code> on it), or because the system is temporarily destroying this + instance of the activity to save space. You can distinguish + between these two scenarios with the <code>{@link + android.app.Activity#isFinishing isFinishing()}</code> method.</td> + <td align="center"><font color="#800000"><strong>Yes</strong></font></td> + <td align="center"><em>nothing</em></td> +</tr> +</tbody> +</table> + +<p> +Note the <b>Killable</b> column in the table above. It indicates +whether or not the system can kill the process hosting the activity +<em>at any time after the method returns, without executing another +line of the activity's code</em>. Three methods ({@code onPause()}, +{@code onStop()}, and {@code onDestroy()}) are marked "Yes." Because +{@code onPause()} is the first of the three, it's the only one that's +guaranteed to be called before the process is killed &mdash +{@code onStop()} and {@code onDestroy()} may not be. Therefore, you +should use {@code onPause()} to write any persistent data (such as user +edits) to storage. +</p> + +<p> +Methods that are marked "No" in the <b>Killable</b> column protect the +process hosting the activity from being killed from the moment they are +called. Thus an activity is in a killable state, for example, from the +time {@code onPause()} returns to the time {@code onResume()} is called. +It will not again be killable until {@code onPause()} again returns. +</p> + +<p> +As noted in a later section, <a href="#proclife">Processes and lifecycle</a>, +an activity that's not technically "killable" by this definition might +still be killed by the system — but that would happen only in +extreme and dire circumstances when there is no other recourse. +</p> + + +<h4><a name="actstate"></a>Saving activity state</h4> + +<p> +When the system, rather than the user, shuts down an activity to conserve +memory, the user may expect to return to the activity and find it in its +previous state. +</p> + +<p> +To capture that state before the activity is killed, you can implement +an <code>{@link android.app.Activity#onSaveInstanceState +onSaveInstanceState()}</code> method for the activity. Android calls this +method before making the activity vulnerable to being destroyed &mdash +that is, before {@code onPause()} is called. It +passes the method a {@link android.os.Bundle} object where you can record +the dynamic state of the activity as name-value pairs. When the activity is +again started, the Bundle is passed both to {@code onCreate()} and to a +method that's called after {@code onStart()}, <code>{@link +android.app.Activity#onRestoreInstanceState onRestoreInstanceState()}</code>, +so that either or both of them can recreate the captured state. +</p> + +<p> +Unlike {@code onPause()} and the other methods discussed earlier, +{@code onSaveInstanceState()} and {@code onRestoreInstanceState()} are +not lifecycle methods. They are not always called. For example, Android +calls {@code onSaveInstanceState()} before the activity becomes +vulnerable to being destroyed by the system, but does not bother +calling it when the instance is actually being destroyed by a user action +(such as pressing the BACK key). In that case, the user won't expect to +return to the activity, so there's no reason to save its state. +</p> + +<p> +Because {@code onSaveInstanceState()} is not always called, you +should use it only to record the transient state of the activity, +not to store persistent data. Use {@code onPause()} for that purpose +instead. +</p> + + +<h3><a name="servlife"></a>Service lifecycle</h3> + +<p> +A service can be used in two ways: +</p> + +<ul> +<li>It can be started and allowed to run until someone stops it or +it stops itself. In this mode, it's started by calling +<code>{@link android.content.Context#startService Context.startService()}</code> +and stopped by calling +<code>{@link android.content.Context#stopService Context.stopService()}</code>. +It can stop itself by calling +<code>{@link android.app.Service#stopSelf() Service.stopSelf()}</code> or +<code>{@link android.app.Service#stopSelfResult Service.stopSelfResult()}</code>. +Only one {@code stopService()} call is needed to stop the service, no matter how +many times {@code startService()} was called.</li> + +<li><p>It can be operated programmatically using an interface that +it defines and exports. Clients establish a connection to the Service +object and use that connection to call into the service. The connection is +established by calling +<code>{@link android.content.Context#bindService Context.bindService()}</code>, +and is closed by calling +<code>{@link android.content.Context#unbindService Context.unbindService()}</code>. +Multiple clients can bind to the same service. +If the service has not already been launched, {@code bindService()} can optionally +launch it. +</p></li> +</ul> + +<p> +The two modes are not entirely separate. You can bind to a service that +was started with {@code startService()}. For example, a background music +service could be started by calling {@code startService()} with an Intent +object that identifies the music to play. Only later, possibly when the +user wants to exercise some control over the player or get information +about the current song, would an activity +establish a connection to the service by calling {@code bindService()}. +In cases like this, {@code stopService()} +will not actually stop the service until the last binding is closed. +</p> + +<p> +Like an activity, a service has lifecycle methods that you can implement +to monitor changes in its state. But they are fewer than the activity +methods — only three — and they are public, not protected: +</p> + +<p style="margin-left: 2em">{@code void onCreate()} +<br/>{@code void onStart(Intent <i>intent</i>)} +<br/>{@code void onDestroy()}</p> + +<p> +By implementing these methods, you can monitor two nested loops of the +service's lifecycle: +</p> + +<ul> +<li>The <b>entire lifetime</b> of a service happens between the time +<code>{@link android.app.Service#onCreate onCreate()}</code> is called and +the time <code>{@link android.app.Service#onDestroy}</code> returns. +Like an activity, a service does its initial setup in {@code onCreate()}, +and releases all remaining resources in {@code onDestroy()}. For example, +a music playback service could create the thread where the music will be played +in {@code onCreate()}, and then stop the thread in {@code onDestroy()}.</li> + +<li><p>The <b>active lifetime</b> of a service begins with a call to +<code>{@link android.app.Service#onStart onStart()}</code>. This method +is handed the Intent object that was passed to {@code startService()}. +The music service would open the Intent to discover which music to +play, and begin the playback.</p> + +<p> +There's no equivalent callback for when the service stops — no +{@code onStop()} method. +</p></li> +</ul> + +<p> +The {@code onCreate()} and {@code onDestroy()} methods are called for all +services, whether they're started by +<code>{@link android.content.Context#startService Context.startService()}</code> +or +<code>{@link android.content.Context#bindService Context.bindService()}</code>. +However, {@code onStart()} is called only for services started by {@code +startService()}. +</p> + +<p> +If a service permits others to +bind to it, there are additional callback methods for it to implement: +</p> + +<p style="margin-left: 2em">{@code IBinder onBind(Intent <i>intent</i>)} +<br/>{@code boolean onUnbind(Intent <i>intent</i>)} +<br/>{@code void onRebind(Intent <i>intent</i>)}</p> + +<p> +The <code>{@link android.app.Service#onBind onBind()}</code> callback is passed +the Intent object that was passed to {@code bindService} and +<code>{@link android.app.Service#onUnbind onUnbind()}</code> is handed +the intent that was passed to {@code unbindService()}. +If the service permits the binding, {@code onBind()} +returns the communications channel that clients use to interact with the service. +The {@code onUnbind()} method can ask for +<code>{@link android.app.Service#onRebind onRebind()}</code> +to be called if a new client connects to the service. +</p> + +<p> +The following diagram illustrates the callback methods for a service. +Although, it separates services that are created via {@code startService} +from those created by {@code bindService()}, keep in mind that any service, +no matter how it's started, can potentially allow clients to bind to it, +so any service may receive {@code onBind()} and {@code onUnbind()} calls. +</p> + +<p><img src="{@docRoot}images/service_lifecycle.png" +alt="State diagram for Service callbacks." border="0" /></p> + + +<h3><a name="broadlife"></a>Broadcast receiver lifecycle</h3> + +<p> +A broadcast receiver has single callback method: +</p> + +<p style="margin-left: 2em">{@code void onReceive(Context <i>curContext</i>, Intent <i>broadcastMsg</i>)}</p> + +<p> +When a broadcast message arrives for the receiver, Android calls its +<code>{@link android.content.BroadcastReceiver#onReceive onReceive()}</code> +method and passes it the Intent object containing the message. The broadcast +receiver is considered to be active only while it is executing this method. +When {@code onReceive()} returns, it is inactive. +</p> + +<p> +A process with an active broadcast receiver is protected from being killed. +But a process with only inactive components can be killed by the system at +any time, when the memory it consumes is needed by other processes. +</p> + +<p> +This presents a problem when the response to a broadcast message is time +consuming and, therefore, something that should be done in a separate thread, +away from the main thread where other components of the user interface run. +If {@code onReceive()} spawns the thread and then returns, the entire process, +including the new thread, is judged to be inactive (unless other application +components are active in the process), putting it in jeopardy of being killed. +The solution to this problem is for {@code onReceive()} to start a service +and let the service do the job, so the +system knows that there is still active work being done in the process. +</p> + +<p> +The next section has more on the vulnerability of processes to being killed. +</p> + + +<h3><a name="proclife"></a>Processes and lifecycles</h3> + +<p>The Android system tries to maintain an application process for as +long as possible, but eventually it will need to remove old processes when +memory runs low. To determine which processes to keep and which to kill, +Android places each process into an "importance hierarchy" based on the +components running in it and the state of those components. There are +five levels in the hierarchy. The following list presents them in order +of importance: +</p> + +<ol> + +<li>A <b>foreground process</b> is one that is required for +what the user is currently doing. A process is considered to be +in the foreground if any of the following conditions hold: + +<ul> +<li>It is running an activity that the user is interacting with +(the Activity object's <code>{@link android.app.Activity#onResume +onResume()}</code> method has been called).</p></li> + +<li><p>It hosts a service that's bound +to the activity that the user is interacting with.</p></li> + +<li><p>It has a {@link android.app.Service} object that's executing +one of its lifecycle callbacks (<code>{@link android.app.Service#onCreate +onCreate()}</code>, <code>{@link android.app.Service#onStart onStart()}</code>, +or <code>{@link android.app.Service#onDestroy onDestroy()}</code>).</p></li> + +<li><p>It has a {@link android.content.BroadcastReceiver} object that's +executing its <code>{@link android.content.BroadcastReceiver#onReceive +onReceive()}</code> method.</p></li> +</ul> + +<p> +Only a few foreground processes will exist at any given time. They +are killed only as a last resort — if memory is so low that +they cannot all continue to run. Generally, at that point, the device has +reached a memory paging state, so killing some foreground processes is +required to keep the user interface responsive. +</p></li> + +<li><p>A <b>visible process</b> is one that doesn't have any foreground +components, but still can affect what the user sees on screen. +A process is considered to be visible if either of the following conditions +holds:</p> + +<ul> +<li>It hosts an activity that is not in the foreground, but is still visible +to the user (its <code>{@link android.app.Activity#onPause onPause()}</code> +method has been called). This may occur, for example, if the foreground +activity is a dialog that allows the previous activity to be seen behind it.</li> + +<li><p>It hosts a service that's bound to a visible activity.</p></li> +</ul> + +<p> +A visible process is considered extremely important and will not be killed +unless doing so is required to keep all foreground processes running. +</p></li> + +<li><p>A <b>service process</b> is one that is running a service that has +been started with the +<code>{@link android.content.Context#startService startService()}</code> +method. Although service processes are not directly tied to anything the +user sees, they are generally doing things that the user cares about (such +as playing an mp3 in the background or downloading data on the network), +so the system keeps them running unless there's not enough +memory to retain them along with all foreground and visible processes. +(Note that a service can be ranked higher than this by virtue of being +bound to a visible or foreground activity). +</p></li> + +<li><p>A <b>background process</b> is one holding an activity +that's not currently visible to the user (the Activity object's +<code>{@link android.app.Activity#onStop onStop()}</code> method has been called). +These processes have no direct impact on the user experience, and can be killed +at any time to reclaim memory for a foreground, visible, or service process. +Usually there are many background processes running, +so they are kept in an LRU list to ensure that the process with the activity that +was most recently seen by the user is the last to be killed. +If an activity implements its lifecycle methods correctly, and captures its current +state, killing its process will not have a deleterious effect on the user experience. +</p></li> + +<li><p>An <b>empty process</b> is one that doesn't hold any active application +components. The only reason to keep such a process around is as a cache to +improve startup time the next time a component needs to run in it. The system +often kills these processes in order to balance overall system resources between +process caches and the underlying kernel caches.</p></li> + +</ol> + +<p> +Android ranks a process at the highest level it can, based upon the +importance of the components currently active in the process. For example, +if a process hosts a service and a visible activity, the process will be +ranked as a visible process, not a service process. +</p> + +<p> +In addition, a process's ranking may be increased because other processes are +dependent on it. A process that is serving another process can never be +ranked lower than the process it is serving. For example, if a content +provider in process A is serving a client in process B, or if a service in +process A is bound to a component in process B, process A will always be +considered at least as important as process B. +</p> + +<p> +Because a process running a service is ranked higher than one with background +activities, an activity that initiates a long-running operation might do +well to start a service for that operation, rather than simply spawn a thread +— particularly if the operation will likely outlast the activity. +Examples of this are playing music in the background +and uploading a picture taken by the camera to a web site. Using a service +guarantees that the operation will have at least "service process" priority, +regardless of what happens to the activity. As noted in the +<a href="#broadlife">Broadcast receiver lifecycle</a> section earlier, this +is the same reason that broadcast receivers should employ services rather +than simply put time-consuming operations in a thread. +</p> diff --git a/docs/html/guide/topics/graphics/2d-graphics.jd b/docs/html/guide/topics/graphics/2d-graphics.jd new file mode 100644 index 0000000..822c66f --- /dev/null +++ b/docs/html/guide/topics/graphics/2d-graphics.jd @@ -0,0 +1,459 @@ +page.title=2D Graphics +parent.title=2D and 3D Graphics +parent.link=index.html +@jd:body + + +<div id="qv-wrapper"> + <div id="qv"> + <h2>In this document</h2> + <ol> + <li><a href="#drawables">Drawables</a> + <ol> + <li><a href="#drawable-images">Creating from resource images</a></li> + <li><a href="#drawable-xml">Creating from resource XML</a></li> + </ol> + </li> + <li><a href="#shape-drawable">ShapeDrawable</a></li> + <!-- <li><a href="#state-list">StateListDrawable</a></li> --> + <li><a href="#nine-patch">NinePatchDrawable</a></li> + <li><a href="#tween-animation">Tween Animation</a></li> + <li><a href="#frame-animation">Frame Animation</a></li> + </ol> + </div> +</div> + +<p>Android offers a custom 2D graphics library for drawing and animating shapes and images. +The {@link android.graphics.drawable} and {@link android.view.animation} +packages are where you'll find the common classes used for drawing and animating in two-dimensions. +</p> + +<p>This document offers an introduction to drawing graphics in your Android application. +We'll discuss the basics of using Drawable objects to draw +graphics, how to use a couple subclasses of the Drawable class, and how to +create animations that either tween (move, stretch, rotate) a single graphic +or animate a series of graphics (like a roll of film).</p> + + +<h2 id="drawables">Drawables</h2> + +<p>A {@link android.graphics.drawable.Drawable} is a general abstraction for "something that can be drawn." +You'll discover that the Drawable class extends to define a variety of specific kinds of drawable graphics, +including {@link android.graphics.drawable.BitmapDrawable}, {@link android.graphics.drawable.ShapeDrawable}, +{@link android.graphics.drawable.PictureDrawable}, {@link android.graphics.drawable.LayerDrawable}, and several more. +Of course, you can also extend these to define your own custom Drawable objects that behave in unique ways.</p> + +<p>There are three ways to define and instantiate a Drawable: using an image saved in your project resouces; +using an XML file that defines the Drawable properties; or using the normal class constructors. Below, we'll discuss +each the first two techniques (using constructors is nothing new for an experienced developer).</p> + + +<h3 id="drawables-from-images">Creating from resource images</h3> + +<p>A simple way to add graphics to your application is by referencing an image file from your project resources. +Supported file types are PNG (preferred), JPG (acceptable) and GIF (discouraged). This technique would +obviously be preferred for application icons, logos, or other graphics such as those used in a game.</p> + +<p>To use an image resource, just add your file to the <code>res/drawable/</code> directory of your project. +From there, you can reference it from your code or your XML layout. +Either way, it is referred using a resource ID, which is the file name without the file type +extension (E.g., <code>my_image.png</code> is referenced as <var>my_image</var>).</p> + +<h4>Example code</h4> +<p>The following code snippet demonstrates how to build an {@link android.widget.ImageView} that uses an image +from drawable resources and add it to the layout.</p> +<pre> +LinearLayout mLinearLayout; + +protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + // Create a LinearLayout in which to add the ImageView + mLinearLayout = new LinearLayout(this); + + // Instantiate an ImageView and define its properties + ImageView i = new ImageView(this); + i.setImageResource(R.drawable.my_image); + i.setAdjustViewBounds(true); // set the ImageView bounds to match the Drawable's dimensions + i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); + + // Add the ImageView to the layout and set the layout as the content view + mLinearLayout.addView(i); + setContentView(mLinearLayout); +} +</pre> +<p>In other cases, you may want to handle your image resource as a +{@link android.graphics.drawable.Drawable} object. +To do so, create a Drawable from the resource like so: +<pre>Drawable myImage = Resources.getDrawable(R.drawable.my_image);</pre> + +<h4>Example XML</h4> +<p>The XML snippet below shows how to add a resource Drawable to an +{@link android.widget.ImageView} in the XML layout (with some red tint just for fun). +<pre> +<ImageView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:tint="#55ff0000" + android:src="@drawable/my_image"/> +</pre> +<p>For more information on using project resources, read about + <a href="{@docRoot}guide/topics/resources/index.html">Resources and Assets</a>.</p> + + +<h3 id="drawables-from-xml">Creating from resource XML</h3> + +<p>By now, you should be familiar with Android's principles of +<a href="{@docRoot}guide/topics/views/index.html">Views and Layout</a>. Hence, you understand the power +and flexibility inherent in defining objects in XML. This philosophy caries over from Views to Drawables. +If there is a Drawable object that you'd like to create, which is not initially dependent on variables defined by +your applicaton code or user interaction, then defining the Drawable in XML is a good option. +Even if you expect your Drawable to change its properties during the user's experience with your application, +you should consider defining the object in XML, as you can always modify properties once it is instantiated.</p> + +<p>Once you've defined your Drawable in XML, save the file in the <code>res/drawable/</code> directory of +your project. Then, retrieve and instantiate the object by calling +{@link android.content.res.Resources#getDrawable(int) Resources.getDrawable()}, passing it the resource ID +of your XML file. (See the <a href="#drawable-xml-example">example below</a>.)</p> + +<p>Any Drawable subclass that supports the <code>inflate()</code> method can be defined in +XML and instantiated by your application. +Each Drawable that supports XML inflation utilizes specific XML attributes that help define the object +properties (see the class reference to see what these are). See the class documentation for each +Drawable subclass for information on how to define it in XML. + +<h4 id="drawable-xml-example">Example</h4> +<p>Here's some XML that defines a TransitionDrawable:</p> +<pre> +<transition xmlns:android="http://schemas.android.com/apk/res/android"> + <item android:drawable="@drawable/image_expand"> + <item android:drawable="@drawable/image_collapse"> +</transition> +</pre> + +<p>With this XML saved in the file <code>res/drawable/expand_collapse.xml</code>, +the following code will instantiate the TransitionDrawable and set it as the content of an ImageView:</p> +<pre> +Resources res = mContext.getResources(); +TransitionDrawable transition = (TransitionDrawable) res.getDrawable(R.drawable.expand_collapse); +ImageView image = (ImageView) findViewById(R.id.toggle_image); +image.setImageDrawable(transition); +</pre> +<p>Then this transition can be run forward (for 1 second) with:</p> +<pre>transition.startTransition(1000);</pre> + +<p>Refer to the Drawable classes listed above for more information on the XML attributes supported by each.</p> + + + +<h2 id="shape-drawable">ShapeDrawable</h2> + +<p>When you want to dynamically draw some two-dimensional graphics, a {@link android.graphics.drawable.ShapeDrawable} +object will probably suit your needs. With a ShapeDrawable, you can programmatically draw +primitive shapes and style them in any way imaginable.</p> + +<p>A ShapeDrawable is an extension of {@link android.graphics.drawable.Drawable}, so you can use one where ever +a Drawable is expected — perhaps for the background of a View, set with +{@link android.view.View#setBackgroundDrawable(android.graphics.drawable.Drawable) setBackgroundDrawable()}. +Of course, you can also draw your shape as its own custom {@link android.view.View}, +to be added to your layout however you please. +Because the ShapeDrawable has its own <code>draw()</code> method, you can create a subclass of View that +draws the ShapeDrawable during the <code>View.onDraw()</code> method. +Here's a basic extension of the View class that does just this, to draw a ShapeDrawable as a View:</p> +<pre> +public class CustomDrawableView extends View { + private ShapeDrawable mDrawable; + + public CustomDrawableView(Context context) { + super(context); + + int x = 10; + int y = 10; + int width = 300; + int height = 50; + + mDrawable = new ShapeDrawable(new OvalShape()); + mDrawable.getPaint().setColor(0xff74AC23); + mDrawable.setBounds(x, y, x + width, y + height); + } + + protected void onDraw(Canvas canvas) { + mDrawable.draw(canvas); + } +} +</pre> + +<p>In the constructor, a ShapeDrawable is defines as an {@link android.graphics.drawable.shapes.OvalShape}. +It's then given a color and the bounds of the shape are set. If you do not set the bounds, then the +shape will not be drawn, whereas if you don't set the color, it will default to black.</p> +<p>With the custom View defined, it can be drawn any way you like. With the sample above, we can +draw the shape progammatically in an Activity:</p> +<pre> +CustomDrawableView mCustomDrawableView; + +protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + mCustomDrawableView = new CustomDrawableView(this); + + setContentView(mCustomDrawableView); +} +</pre> + +<p>If you'd like to draw this custom drawable from the XML layout instead of from the Activity, +then the CustomDrawable class must override the {@link android.view.View#View(android.content.Context, android.util.AttributeSet) View(Context, AttributeSet)} constructor, which is called when +instantiating a View via inflation from XML. Then add a CustomDrawable element to the XML, +like so:</p> +<pre> +<com.example.shapedrawable.CustomDrawableView + android:layout_width="fill_parent" + android:layout_height="wrap_content" + /> +</pre> + +<p>The ShapeDrawable class (like many other Drawable types in the {@link android.graphics.drawable} package) +allows you to define various properties of the drawable with public methods. +Some properties you might want to adjust include +alpha transparency, color filter, dither, opacity and color.</p> + +<!-- TODO +<h2 id="state-list">StateListDrawable</h2> + +<p>A StateListDrawable is an extension of the DrawableContainer class, making it little different. +The primary distinction is that the +StateListDrawable manages a collection of images for the Drawable, instead of just one. +This means that it can switch the image when you want, without switching objects. However, the +intention of the StateListDrawable is to automatically change the image used based on the state +of the object it's attached to. +--> + +<h2 id="nine-patch">NinePatchDrawable</h2> + +<p>A {@link android.graphics.drawable.NinePatchDrawable} graphic is a stretchable bitmap image, which Android +will automatically resize to accomodate the contents of the View in which you have placed it as the background. +An example use of a NinePatch is the backgrounds used by standard Android buttons — +buttons must stretch to accommodate strings of various lengths. A NinePatch drawable is a standard PNG +image that includes an extra 1-pixel-wide border. It must be saved with the extension <code>.9.png</code>, +and saved into the <code>res/drawable/</code> directory of your project. +</p> +<p> + The border is used to define the stretchable and static areas of + the image. You indicate a stretchable section by drawing one (or more) 1-pixel-wide + black line(s) in the left and top part of the border. (You can have as + many stretchable sections as you want.) The relative size of the stretchable + sections stays the same, so the largest sections always remain the largest. +</p> +<p> + You can also define an optional drawable section of the image (effectively, + the padding lines) by drawing a line on the right and bottom lines. + If a View object sets the NinePatch as its background and then specifies the + View's text, it will stretch itself so that all the text fits inside only + the area designated by the right and bottom lines (if included). If the + padding lines are not included, Android uses the left and top lines to + define this drawable area. +</p> +<p>To clarify the difference between the different lines, the left and top lines define +which pixels of the image are allowed to be replicated in order to strech the image. +The bottom and right lines define the relative area within the image that the contents +of the View are allowed to lie within.</p> +<p> + Here is a sample NinePatch file used to define a button: +</p> + <img src="{@docRoot}images/ninepatch_raw.png" alt="" /> + +<p>This NinePatch defines one stretchable area with the left and top lines +and the drawable area with the bottom and right lines. In the top image, the dotted grey +lines identify the regions of the image that will be replicated in order to strech the image. The pink +rectangle in the bottom image identifies the region in which the contents of the View are allowed. +If the contents don't fit in this region, then the image will be stretched so that they do. +</p> + +<p>The <a href="{@docRoot}guide/developing/tools/draw9patch.html">Draw 9-patch</a> tool offers + an extremely handy way to create your NinePatch images, using a WYSIWYG graphics editor. It +even raises warnings if the region you've defined for the stretchable area is at risk of +producing drawing artifacts as a result of the pixel replication. +</p> + +<h3>Example XML</h3> + +<p>Here's some sample layout XML that demonstrates how to add a NinePatch image to a +couple of buttons. (The NinePatch image is saved as <code>res/drawable/my_button_background.9.png</code> +<pre> +<Button id="@+id/tiny" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_alignParentTop="true" + android:layout_centerInParent="true" + android:text="Tiny" + android:textSize="8sp" + android:background="@drawable/my_button_background"/> + +<Button id="@+id/big" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_alignParentBottom="true" + android:layout_centerInParent="true" + android:text="Biiiiiiig text!" + android:textSize="30sp" + android:background="@drawable/my_button_background"/> +</pre> +<p>Note that the width and height are set to "wrap_content" to make the button fit neatly around the text. +</p> + +<p>Below are the two buttons rendered from the XML and NinePatch image shown above. +Notice how the width and height of the button varies with the text, and the background image +stretches to accommodate it. +</p> + +<img src="{@docRoot}images/ninepatch_examples.png" alt=""/> + + +<h2 id="tween-animation">Tween Animation</h2> + +<p>A tweened animation can perform a series of simple transformations (position, size, rotation, and transparency) on +the contents of a View object. So, if you have a TextView object, you can move, rotate, grow, or shrink the text. +If it has a background image, the background image will be transformed along with the text.</p> + +<p>The animation is achieved with a sequence of animation instructions, defined in either XML or code. +Like defining a layout, an XML file is recommended because it's more readable, reusable, and swappable +than hard-coding it. In the example below, we use XML. (To define an animation in code, refer to the +{@link android.view.animation.AnimationSet} class and other {@link android.view.animation.Animation} subclasses.)</p> + +<p>The animation XML file belongs in the <code>res/anim/</code> directory of your Android project. +The file must have a single root element: this will be either a single <code><alpha></code>, +<code><scale></code>, <code><translate></code>, <code><rotate></code>, interpolator element, +or <code><set></code> element that holds groups of these elements (which may include another +<code><set></code>). By default, all animation instructions are applied simultaneously. +To make them occur sequentially, you must specify the <code>startOffset</code> attribute, as shown in the example below. +</p> + +<p>The following XML from one of the ApiDemos is used to stretch, +then simultaneously spin and rotate a View object. +</p> +<pre> +<set android:shareInterpolator="false"> + <scale + android:interpolator="@android:anim/accelerate_decelerate_interpolator" + android:fromXScale="1.0" + android:toXScale="1.4" + android:fromYScale="1.0" + android:toYScale="0.6" + android:pivotX="50%" + android:pivotY="50%" + android:fillAfter="false" + android:duration="700" /> + <set android:interpolator="@android:anim/decelerate_interpolator"> + <scale + android:fromXScale="1.4" + android:toXScale="0.0" + android:fromYScale="0.6" + android:toYScale="0.0" + android:pivotX="50%" + android:pivotY="50%" + android:startOffset="700" + android:duration="400" + android:fillBefore="false" /> + <rotate + android:fromDegrees="0" + android:toDegrees="-45" + android:toYScale="0.0" + android:pivotX="50%" + android:pivotY="50%" + android:startOffset="700" + android:duration="400" /> + </set> +</set> +</pre> +<p>Screen coordinates (not used in this example) are (0,0) at the upper left hand corner, +and increase as you go down and to the right.</p> + +<p>Some values, such as pivotX, can be specified relative to the object itself or relative to the parent. +Be sure to use the proper format for what you want ("50" for 50% relative to the parent, or "50%" for 50% +relative to itself).</p> + +<p>You can determine how a transformation is applied over time by assigning an +{@link android.view.animation.Interpolator}. Android includes +several Interpolator subclasses that specify various speed curves: for instance, +{@link android.view.animation.AccelerateInterpolator} tells +a transformation to start slow and speed up. Each one has an attribute value that can be applied in the XML.</p> + +<p>With this XML saved as <code>hyperspace_jump.xml</code> in the <code>res/anim/</code> directory of the +project, the following Java code will reference it and apply it to an {@link android.widget.ImageView} object +from the layout. +</p> +<pre> +ImageView spaceshipImage = (ImageView) findViewById(R.id.spaceshipImage); +Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(this, R.anim.hyperspace_jump); +spaceshipImage.startAnimation(hyperspaceJumpAnimation); +</pre> + +<p>As an alternative to <code>startAnimation()</code>, you can define a starting time for the animation with +<code>{@link android.view.animation.Animation#setStartTime(long) Animation.setStartTime()}</code>, +then assign the animation to the View with +<code>{@link android.view.View#setAnimation(android.view.animation.Animation) View.setAnimation()}</code>.</p> + +<p>For more information on the XML syntax, available tags and attributes, see the discussion on animation +in the <a href="{@docRoot}guide/topics/resources/available-resources.html#animation">Available Resources</a>.</p> + +<p class="note"><strong>Note:</strong> Animations are drawn in the area designated for the View at the start of +the animation; this area does not change to accommodate size or movement, so if your animation moves or expands +outside the original boundaries of your object, it will be clipped to the size of the original View, even if +the object's LayoutParams are set to WRAP_CONTENT (the object will not resize to accommodate moving or +expanding/shrinking animations).</p> + + +<h2 id="frame-animation">Frame Animation</h2> + +<p>This is a traditional animation in the sense that it is created with a sequence of different +images, played in order, like a roll of film.</p> + +<p>While you can define the frames of an animation in your code, using the +{@link android.graphics.drawable.AnimationDrawable} class API, it's more simply accomplished with a single XML +file that lists the frames that compose the animation. Like the tween animation above, the XML file for this kind +of animation belongs in the <code>res/anim/</code> directory of your Android project. In this case, +the instructions are the order and duration for each frame of the animation.</p> + +<p>The XML file consists of an <code><animation-list></code> element as the root node and a series +of child <code><item></code> nodes that each define a frame: a drawable resource for the frame and the frame duration. +Here's an example XML file for a frame-by-frame animation:</p> +<pre> +<animation-list xmlns:android="http://schemas.android.com/apk/res/android" + android:oneshot="true"> + <item android:drawable="@drawable/rocket_thrust1" android:duration="200" /> + <item android:drawable="@drawable/rocket_thrust2" android:duration="200" /> + <item android:drawable="@drawable/rocket_thrust3" android:duration="200" /> +</animation-list> +</pre> + +<p>This animation runs for just three frames. By setting the <code>android:oneshot</code> attribute of the +list to <var>true</var>, it will cycle just once then stop and hold on the last frame. If it is set <var>false</var> then +the animation will loop. With this XML saved as <code>rocket_thrust.xml</p> in the <code>res/anim/</code> directory +of the project, it can be added as the background image to a View and then called to play. Here's an example Activity, +in which the animation is added to an {@link android.widget.ImageView} and then animated when the screen is touched:</p> +<pre> +AnimationDrawable rocketAnimation; + +public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.main); + + ImageView rocketImage = (ImageView) findViewById(R.id.rocket_image); + rocketImage.setBackgroundResource(R.anim.rocket_thrust); + rocketAnimation = (AnimationDrawable) rocketImage.getBackground(); +} + +public boolean onTouchEvent(MotionEvent event) { + if (event.getAction() == MotionEvent.ACTION_DOWN) { + rocketAnimation.start(); + return true; + } + return super.onTouchEvent(event); +} +</pre> +<p>It's important to note that the <code>start()</code> method called on the AnimationDrawable cannot be +called during the <code>onCreate()</code> method of your Activity, because the AnimationDrawable is not yet fully attached +to the window. If you want to play the animation immediately, without +requiring interaction, then you might want to call it from the +<code>{@link android.app.Activity#onWindowFocusChanged(boolean) onWindowFocusChanged()}</code> method in +your Activity, which will get called when Android brings your window into focus.</p> + + diff --git a/docs/html/guide/topics/graphics/index.jd b/docs/html/guide/topics/graphics/index.jd new file mode 100644 index 0000000..388acc9 --- /dev/null +++ b/docs/html/guide/topics/graphics/index.jd @@ -0,0 +1,21 @@ +page.title=2D and 3D Graphics +@jd:body + + +<p>Android graphics are powered by a custom 2D graphics library and OpenGL ES 1.0 +for 3D graphics.</p> + +<h2>2D Graphics</h2> +<p>Android offers a custom 2D graphics library for drawing shapes and images.</p> +<p>The {@link android.graphics} and {@link android.graphics.drawable} +packages are where you'll find the classes used for drawing in two-dimensions. +For common drawing tasks, though, the {@link android.graphics.drawable} package +is where you'll find what you need.</p> +<p>For an introduction to drawing shapes and images, read the +<a href="2d-graphics.html">2D Graphics</a> document.</p> + + +<h2>3D with OpenGL</h2> +<p>High performance 3D graphic utilities are provided on Android with the OpenGL ES API. +You'll find the OpenGL APIs in the {@link android.opengl} package. +Read more about <a href="opengl.html">3D with OpenGL</a>.</p>
\ No newline at end of file diff --git a/docs/html/guide/topics/graphics/opengl.jd b/docs/html/guide/topics/graphics/opengl.jd new file mode 100644 index 0000000..eb2932d --- /dev/null +++ b/docs/html/guide/topics/graphics/opengl.jd @@ -0,0 +1,56 @@ +page.title=3D with OpenGL +parent.title=2D and 3D Graphics +parent.link=index.html +@jd:body + + +<p>Android includes support for high performance 3D graphics +via the OpenGL API — specifically, the OpenGL ES API.</p> + +<p>OpenGL ES is a flavor of the OpenGL specification intended for embedded +devices. Versions of <a href="http://www.khronos.org/opengles/">OpenGL ES</a> are loosely peered to versions of the primary +OpenGL standard. Android currently supports OpenGL ES 1.0, which corresponds +to OpenGL 1.3. So, if the application you have in mind is possible with OpenGL +1.3 on a desktop system, it should be possible on Android.</p> + +<p>The specific API provided by Android is similar to the J2ME JSR239 OpenGL +ES API. However, it may not be identical, so watch out for deviations.</p> + +<h2>Using the API</h2> + +<p>Here's how to use the API at an extremely high level:</p> + +<ol> +<li>Write a custom View subclass.</li> +<li>Obtain a handle to an OpenGLContext, which provides access to the OpenGL functionality.</li> +<li>In your View's onDraw() method, get a handle to a GL object, and use its methods to perform GL operations.</li> +</ol> + +<p>For an example of this usage model (based on the classic GL ColorCube), +see +<a href="{@docRoot}guide/samples/ApiDemos/src/com/example/android/apis/graphics/GLSurfaceView.html">com.android.samples.graphics.GLSurfaceView.java</a> +in the ApiDemos sample code project. A slightly more sophisticated version showing how to use +it with threads can be found in +<a href="{@docRoot}guide/samples/ApiDemos/src/com/example/android/apis/graphics/GLSurfaceViewActivity.html">com.android.samples.graphics.GLSurfaceViewActivity.java</a>. +</p> + +<p>Writing a summary of how to actually write 3D applications using OpenGL is +beyond the scope of this text and is left as an exercise for the reader.</p> + +<h2>Links to Additional Information</h2> + +<p>Information about OpenGL ES can be +found at <a title="http://www.khronos.org/opengles/" +href="http://www.khronos.org/opengles/">http://www.khronos.org/opengles/</a>.</p> + +<p>Information specifically +about OpenGL ES 1.0 (including a detailed specification) can be found +at <a title="http://www.khronos.org/opengles/1_X/" +href="http://www.khronos.org/opengles/1_X/">http://www.khronos.org/opengles/1_X/</a>.</p> + +<p>The documentation for the Android {@link javax.microedition.khronos.opengles +OpenGL ES implementations} are also available.</p> + +<p>Finally, note that though Android does include some basic support for +OpenGL ES 1.1, the support is <strong>not complete</strong>, and should not be relied +upon at this time.</p> diff --git a/docs/html/guide/topics/intents/index.html b/docs/html/guide/topics/intents/index.html new file mode 100644 index 0000000..b831246 --- /dev/null +++ b/docs/html/guide/topics/intents/index.html @@ -0,0 +1,9 @@ +<html> +<head> +<meta http-equiv="refresh" content="0;url=intents-filters.html"> +<title>Redirecting...</title> +</head> +<body> +<a href="intents-filters.html">click here</a> if you are not redirected. +</body> +</html>
\ No newline at end of file diff --git a/docs/html/guide/topics/intents/intents-filters.jd b/docs/html/guide/topics/intents/intents-filters.jd index 39ca589..d49d27e 100644 --- a/docs/html/guide/topics/intents/intents-filters.jd +++ b/docs/html/guide/topics/intents/intents-filters.jd @@ -1,6 +1,30 @@ page.title=Intents and Intent Filters @jd:body +<div id="qv-wrapper"> +<div id="qv"> +<h2>Key classes</h2> +<ol> +<li>{@link android.content.Intent}</li> +<li>{@link android.content.IntentFilter}</li> +<li>{@link android.app.Activity}</li> +<li>{@link android.app.Service}</li> +<li>{@link android.content.BroadcastReceiver}</li> +<li>{@link android.content.pm.PackageManager}</li> +</ol> + +<h2>In this document</h2> +<ol> +<li><a href="#iobjs">Intent Objects</a></li> +<li><a href="#ires">Intent Resolution</a>, including:</li> +<li style="margin-left: 2em"><a href="#ifs">Intent filters</a></li> +<li style="margin-left: 2em"><a href="#ccases">Common cases</a></li> +<li style="margin-left: 2em"><a href="#imatch">Using intent matching</a></li> +</ol> +</div> +</div> + + <p> Three of the core components of an application — activities, services, and broadcast receivers — are activated through messages, called <i>intents</i>. @@ -10,29 +34,28 @@ object, is a passive data structure holding an abstract description of an operat to be performed — or, in the case of broadcasts, a description of something that has happened and is being announced. There are separate mechanisms for delivering intents to each type of component: +</p> <ul> - -<p><li>An Intent object is passed to <code>{@link android.content.Context#startActivity +<li>An Intent object is passed to <code>{@link android.content.Context#startActivity Context.startActivity()}</code> or <code>{@link android.app.Activity#startActivityForResult Activity.startActivityForResult()}</code> to launch an activity or get an existing -activity to do something new. +activity to do something new.</li> -<p><li>An Intent object is passed to <code>{@link android.content.Context#startService +<li><p>An Intent object is passed to <code>{@link android.content.Context#startService Context.startService()}</code> to initiate a service or deliver new instructions to an ongoing service. Similarly, an intent can be passed to <code>{@link android.content.Context#bindService Context.bindService()}</code> to establish a -connection between the calling component and a target service. It initiates the -service if it's not already running. +connection between the calling component and a target service. It can optionally +initiate the service if it's not already running.</p></li> -<p><li>Intent objects passed to any of the broadcast methods (such as <code>{@link +<li><p>Intent objects passed to any of the broadcast methods (such as <code>{@link android.content.Context#sendBroadcast(Intent) Context.sendBroadcast()}</code>, <code>{@link android.content.Context#sendOrderedBroadcast(Intent, String) Context.sendOrderedBroadcast()}</code>, or <code>{@link android.content.Context#sendStickyBroadcast Context.sendStickyBroadcast()}</code>) are delivered to all interested broadcast receivers. Many kinds of broadcasts -originate in system code. - +originate in system code.</p></li> </ul> <p> @@ -42,71 +65,63 @@ There is no overlap within these messaging systems: Broadcast intents are deliv only to broadcast receivers, never to activities or services. An intent passed to {@code startActivity()} is delivered only to an activity, never to a service or broadcast receiver, and so on. +</p> <p> -Intents can be divided into two groups: - -<ul> - -<p><li><i>Explicit intents</i> designate the target component by its class name. -They're typically used for application-internal messages — such as -an activity starting a subordinate service or launching a sister activity -— since component names would generally not be known to developers -of other applications. - -<p><li><i>Implicit intents</i> do not name the target. Instead, the -Android system determines the best component (or components) to respond -to the message. It compares the contents of the Intent object with -<i>intent filters</i>, structures associated with components that can -potentially receive intents. Filters advertise the capabilities of a -component and delimit the intents it can handle. - - -</ul> - -<p> -This document describes the rules Android uses to map intents to components — -how it determines which component should receive an intent message. -It begins with a description of Intent objects, and then describes intent filters -and how intents are tested against the filters. +This document begins with a description of Intent objects. It then describes the +rules Android uses to map intents to components — how it resolves which +component should receive an intent message. For intents that don't explicitly +name a target component, this process involves testing the Intent object against +<i>intent filters</i> associated with potential targets. +</p> -<h2>Intent Objects</h2> +<h2><a name="iobjs"></a>Intent Objects</h2> <p> -An {@link android.content.Intent} object is a bundle of information. It contains -information of interest to the component that receives the intent (such as the action -to be taken and the data to act on) plus information -of interest to the Android system (such as the category of component that should handle -the intent and instructions on how to launch a target activity). Principally, it can contain -the following: +An {@link android.content.Intent} object is a bundle of information. It +contains information of interest to the component that receives the intent +(such as the action to be taken and the data to act on) plus information +of interest to the Android system (such as the category of component that +should handle the intent and instructions on how to launch a target activity). +Principally, it can contain the following: +</p> <dl> -<p><dt><b>Component class name</b></dt> -<dd>The fully qualified class name of the component that should handle the intent -— for example "{@code com.example.project.FreneticActivity}". -This field is optional (and it would not normally be set for broadcast intents, since -broadcasts are intended for more than a single receiver). However, if a class name -is specified, nothing else in the Intent -object matters for determining which component should get the intent; it will be -delivered to the named component. (Of course, the other contents of the intent will -matter to the component that receives it.) - -<p> -The component class is set by <code>{@link android.content.Intent#setComponent +<dt><b>Component name</b><a name="cname"></a></dt> +<dd>The name of the component that should handle the intent. This field is +a {@link android.content.ComponentName} object — a combination of the +fully qualified class name of the target component (for example "{@code +com.example.project.app.FreneticActivity}") and the package name set +in the manifest file of the application where the component resides (for +example, "{@code com.example.project}"). The package part of the component +name and the package name set in the manifest do not necessarily have to match. + +<p> +The component name is optional. If it is set, the Intent object is +delivered to an instance of the designated class. If it is not set, +Android uses other information in the Intent object to locate a suitable +target — see <a href="#ires">Intent Resolution</a>, later in this +document. +</p> + +<p> +The component name is set by <code>{@link android.content.Intent#setComponent setComponent()}</code>, <code>{@link android.content.Intent#setClass setClass()}</code>, or <code>{@link android.content.Intent#setClassName(String, String) setClassName()}</code> and read by <code>{@link android.content.Intent#getComponent getComponent()}</code>. +</p> +</dd> <p><dt><b>Action</b></dt> <dd>A string naming the action to be performed — or, in the case of broadcast -intents, the action that took place and is being reported. This is the only field -in the object that must be set. The Intent class defines a number of action constants, -including these: +intents, the action that took place and is being reported. The Intent class defines +a number of action constants, including these: +</p> -<p><table> +<table> <tr> <th>Constant</th> <th>Target component</th> @@ -122,7 +137,7 @@ including these: </tr><tr> <td>{@code ACTION_MAIN} <td>activity - <td>Start up as the initial activity of a task. + <td>Start up as the initial activity of a task, with no data input and no returned output. </tr><tr> <td>{@code ACTION_SYNC} <td>activity @@ -147,45 +162,75 @@ including these: </table> <p> -See the {@link android.content.Intent} class description for a full list of pre-defined action constants. - -<p> -You can define action strings of your own. Those you define should include the -application package as a prefix — for example: -"<code>com.example.project.DEBIT_ACCT</code>". The action in an Intent object -is set by the <code>{@link android.content.Intent#setAction setAction()}</code> -method and read by <code>{@link android.content.Intent#getAction getAction()}</code>. - -<p><dt><b>Data</b></dt> -<dd>The data to be acted on. Different actions are paired with different kinds -of data specifications. For example, if the action field is {@code ACTION_EDIT}, +See the {@link android.content.Intent} class description for a list of +pre-defined constants for generic actions. Other actions are defined +elsewhere in the Android API. +You can also define your own action strings for activating the components +in your application. Those you invent should include the application +package as a prefix — for example: +"<code>com.example.project.SHOW_COLOR</code>". +</p> + +<p> +The action largely determines how the rest of the intent is structured +— particularly the <a href="#data">data</a> and +<a href="#extras">extras</a> fields — +much as a method name determines a set of arguments and a return value. +For this reason, it's a good idea to use action names that are +as specific as possible, and to couple them tightly to the other fields of +the intent. In other words, instead of defining an action in isolation, +define an entire protocol for the Intent objects your components can handle. +</p> + +<p> +The action in an Intent object is set by the +<code>{@link android.content.Intent#setAction setAction()}</code> +method and read by +<code>{@link android.content.Intent#getAction getAction()}</code>. +</p> +</dd> + +<p><dt><b>Data</b><a name="data"></a></dt> +<dd>The URI of the data to be acted on and the MIME type of that data. Different +actions are paired with different kinds of data specifications. For example, if +the action field is {@code ACTION_EDIT}, the data field would contain the URI of the document to be displayed for editing. If the action is {@code ACTION_CALL}, the data field would be a {@code tel:} URI with the number to call. Similarly, if the action is {@code ACTION_VIEW} and the -data field is a {@code mailto:} URI, the receiving activity would be called upon -to display a screen for composing an e-mail message, with the address filled in -from the URI. +data field is an {@code http:} URI, the receiving activity would be called upon +to download and display whatever data the URI refers to. <p> -It's often important to know the type of data (its MIME type) in addition to its URI. -Typically, the type is inferred from the URI. But it can also be explicitly set. +When matching an intent to a component that is capable of handling the data, +it's often important to know the type of data (its MIME type) in addition to its URI. +For example, a component able to display image data should not be called +upon to play an audio file. +</p> + +<p> +In many cases, the data type can be inferred from the URI — particularly +{@code content:} URIs, which indicate that the data is located on the device and +controlled by a content provider (see the +<a href="{@docRoot}guide/topics/providers/content-providers.html">separate +discussion on content providers</a>). But the type can also be explicitly set +in the Intent object. The <code>{@link android.content.Intent#setData setData()}</code> method specifies data only as a URI, <code>{@link android.content.Intent#setType setType()}</code> specifies it only as a MIME type, and <code>{@link android.content.Intent#setDataAndType setDataAndType()}</code> specifies it as both -a URI and a MIME type. The data and type are read by <code>{@link -android.content.Intent#getData getData()}</code> and <code>{@link +a URI and a MIME type. The URI is read by <code>{@link +android.content.Intent#getData getData()}</code> and the type by <code>{@link android.content.Intent#getType getType()}</code>. - +</p> +</dd> <p><dt><b>Category</b></dt> <dd>A string containing additional information about the kind of component -that should handle the intent. Categories generally apply only to activities. +that should handle the intent. Any number of category descriptions can be +placed in an Intent object. As it does for actions, the Intent class defines +several category constants, including these: -<p> -Any number of category descriptions can be placed in an Intent object. As it does for actions, the Intent class defines a number of category constants, including these: - -<p><table> +<table> <tr> <th>Constant</th> <th>Meaning</th> @@ -211,29 +256,28 @@ Any number of category descriptions can be placed in an Intent object. As it do </table> <p> -In addition to the role categories play in Intent objects, they have an -independent function in intent filters. As the examples above suggest, they -instruct the Android system how to treat the activity that owns the filter. For -example, {@code CATEGORY_HOME} defines the home activity. - -<p> See the {@link android.content.Intent} class description for the full list of categories. +</p> <p> The <code>{@link android.content.Intent#addCategory addCategory()}</code> method places a category in an Intent object, <code>{@link android.content.Intent#removeCategory removeCategory()}</code> deletes a category previously added, and <code>{@link android.content.Intent#getCategories getCategories()}</code> gets the set of all categories currently in the object. +</p> +</dd> -<p><dt><b>Extras</b></dt> +<p><dt><b>Extras</b><a name="extras"></a></dt> <dd>Key-value pairs for additional information that should be delivered to the component handling the intent. Just as some actions are paired with particular kinds of data URIs, some are paired with particular extras. For example, an {@code ACTION_TIMEZONE_CHANGED} intent has a "{@code time-zone}" extra that identifies the new time zone, and {@code ACTION_HEADSET_PLUG} has a "{@code state}" extra indicating whether the headset is now plugged in or -unplugged, as well as a "{@code name}" extra for the type of headset. +unplugged, as well as a "{@code name}" extra for the type of headset. +If you were to invent a {@code SHOW_COLOR} action, the color value would +be set in an extra key-value pair. <p> The Intent object has a series of {@code put...()} methods for inserting various @@ -242,12 +286,15 @@ the data. These methods parallel those for {@link android.os.Bundle} objects. In fact, the extras can be installed and read as a Bundle using the <code>{@link android.content.Intent#putExtras putExtras()}</code> and <code>{@link android.content.Intent#getExtras getExtras()}</code> methods. +</p> +</dd> -<p><dt><b>Launch instructions</b></dt> -<dd>Flags that instruct the Android system how to launch an activity (for -example, which task the activity should belong to) and how to treat it after -it's launched (for example, whether it belongs in the list of recent activities). -All these flags are defined in the Intent class. +<p><dt><b>Flags</b></dt> +<dd>Flags of various sorts. Many instruct the Android system how to launch an +activity (for example, which task the activity should belong to) and how to treat +it after it's launched (for example, whether it belongs in the list of recent +activities). All these flags are defined in the Intent class. +</dd> </dl> @@ -256,38 +303,89 @@ The Android system and the applications that come with the platform employ Intent objects both to send out system-originated broadcasts and to activate system-defined components. To see how to structure an intent to activate a system component, consult the -<a href="{@docRoot}../reference/available-intents.html">list of intents</a> +<a href="{@docRoot}guide/appendix/g-app-intents.html">list of intents</a> in the reference. -For example, the component that initiates phone calls can be activated by an -{@code ACTION_CALL} intent with a {@code tel:} URI specifying the phone number. +</p> + +<h2><a name="ires"></a>Intent Resolution</h2> -<h2>Intent Filters</h2> +<p> +Intents can be divided into two groups: +</p> + +<ul> +<li><i>Explicit intents</i> designate the target component by its +name (the <a href="#cname">component name field</a>, mentioned earlier, +has a value set). Since component names would generally not be known to +developers of other applications, explicit intents are typically used +for application-internal messages — such as an activity starting +a subordinate service or launching a sister activity.</li> + +<li><p><i>Implicit intents</i> do not name a target (the field for +the component name is blank). Implicit intents are often used to +activate components in other applications.</p></li> +</ul> <p> -If an intent explicitly names a component class, Android delivers the intent to -an instance of that class, creating the instance if necessary. However, if the -intent does not designate a target by name, Android must find the appropriate -component to handle the request — a single activity or service to perform -the requested action or the set of broadcast receivers to respond to the -broadcast announcement. It does so by comparing the Intent object against -components' intent filters. +Android delivers an explicit intent to an instance of the designated +target class. Nothing in the Intent object other than the component +name matters for determining which component should get the intent. +</p> + +<p> +A different strategy is needed for implicit intents. In the absence of a +designated target, the Android system must find the best component (or +components) to handle the intent — a single activity or service to +perform the requested action or the set of broadcast receivers to respond +to the broadcast announcement. It does so by comparing the contents of +the Intent object to <i>intent filters</i>, structures associated with +components that can potentially receive intents. Filters advertise the +capabilities of a component and delimit the intents it can handle. They +open the component to the possibility of receiving implicit intents of +the advertised type. If a component does not have any intent filters, +it can receive only explicit intents. A component with filters can +receive both explicit and implicit intents. +</p> + +<p> +Only three aspects of an Intent object are consulted when the object +is tested against an intent filter: +</p> + +<p style="margin-left: 2em">action +<br/>data (both URI and data type) +<br/>category</p> + +<p> +The extras and flags play no part in resolving which component receives +an intent. +</p> + + +<h3><a name="ifs"></a>Intent filters</h3> <p> -To inform the system which intents they can handle, activities, services, and -broadcast receivers can have one or more intent filters. +To inform the system which implicit intents they can handle, activities, +services, and broadcast receivers can have one or more intent filters. Each filter describes a capability of the component, a set of intents that -the component is willing to receive. It, in effect, filters out unwanted -intents. An implicit intent (one that doesn't name a target class) is delivered -to a component only if it can pass through one of the component's filters. -If a component lacks any intent filters, it can be activated only by explicit -intents (those that specifically name its class). +the component is willing to receive. It, in effect, filters in +intents of a desired type, while filtering out unwanted +intents — but only unwanted implicit intents (those that don't name +a target class). An explicit intent is always delivered to its target, +no matter what it contains; the filter is not consulted. But an implicit +intent is delivered to a component only if it can pass through one of the +component's filters. +</p> <p> A component has separate filters for each job it can do, each face it can -present to the user. For example, if an activity can either display -a list of items that the user can select or display the full details of one of -the items, it would have a separate filter for each of these possibilities. +present to the user. For example, the principal activity of the sample +NotePad application has three filters — one for starting up with a +blank slate, another for starting with an assigned directory of notes +that the user can view, edit, or select from, and a third for finding a +particular note without an initial specification of its directory. +</p> <p> An intent filter is an instance of the {@link android.content.IntentFilter} class. @@ -298,22 +396,38 @@ Java code, but in the application's manifest file (AndroidManifest.xml) as broadcast receivers that are registered dynamically by calling <code>{@link android.content.Context#registerReceiver(BroadcastReceiver, IntentFilter, String, Handler) Context.registerReceiver()}</code>; they are directly created as IntentFilter objects.) +</p> + +<div class="sidebox-wrapper"> +<div class="sidebox"> +<h2>Filters and security</h2> +<p>An intent filter cannot be relied on for security. While it opens a +component to receiving only certain kinds of implicit intents, it does +nothing to prevent explicit intents from targeting the component. Even +though a filter restricts the intents a component will be asked to handle +to certain actions and data sources, someone could always put +together an explicit intent with a different action and data source, and +name the component as the target. +</p> +</div> +</div> <p> A filter has fields that parallel the action, data, and category fields of an -Intent object. A new intent is tested against the filter in all three areas. +Intent object. An implicit intent is tested against the filter in all three areas. To be delivered to the component that owns the filter, it must pass all three tests. If it fails even one of them, the Android system won't deliver it to the component — at least not on the basis of that filter. However, since a -component can have multiple intent filters, an arriving intent that does not pass +component can have multiple intent filters, an intent that does not pass through one of a component's filters might make it through on another. +</p> <p> Each of the three tests is described in detail below: +</p> <dl> -<p> <dt><b>Action test</b></dt> <dd>An {@code <intent-filter>} element in the manifest file lists actions as {@code <action>} subelements. For example: @@ -327,15 +441,28 @@ as {@code <action>} subelements. For example: <p> As the example shows, while an Intent object names just a single action, -a filter may list more than one — or it may not list any at all. +a filter may list more than one. The list cannot be empty; a filter must +contain at least one {@code <action>} element, or it +will block all intents. +</p> <p> -To pass this test, the action specified in the {@link android.content.Intent} -object must match one of the actions listed in the filter. However, if the -filter doesn't list any actions, all actions are accepted, so all intents pass -the test. +To pass this test, the action specified in the Intent object must match +one of the actions listed in the filter. If the object or the filter +does not specify an action, the results are as follows: +</p> + +<ul> +<li>If the filter fails to list any actions, there is nothing for an +intent to match, so all intents fail the test. No intents can get +through the filter.</li> + +<li><p>On the other hand, an Intent object that doesn't specify an +action automatically passes the test — as long as the filter +contains at least one action.</p></li> +</ul +</dd> -<p> <dt><b>Category test</b></dt> <dd>An {@code <intent-filter>} element also lists categories as subelements. For example: @@ -346,110 +473,217 @@ For example: . . . </intent-filter></pre> -<p>Note that the constants described earlier for actions and categories are not +<p> +Note that the constants described earlier for actions and categories are not used in the manifest file. The full string values are used instead. For instance, the "{@code android.intent.category.BROWSABLE}" string in the example above corresponds to the {@code CATEGORY_BROWSABLE} constant mentioned earlier in this document. Similarly, the string "{@code android.intent.action.EDIT}" corresponds to the {@code ACTION_EDIT} constant. - -<p> -Many categories tell the Android system how to treat the component. For example, -"{@code android.intent.category.LAUNCHER}" (the {@code CATEGORY_LAUNCHER} constant -in code) instructs the system to include the activity in the screen showing -applications the user can launch. Some categories — like "{@code -android.intent.category.DEFAULT}" in the example above &mdash typically appear -only in filters, not in Intent objects. +</p> <p> For an intent to pass the category test, every category in the Intent object must match a category in the filter. The filter can list additional categories, -but it cannot omit any in the intent. An intent with no -categories always passes this test, regardless of what's in the filter. +but it cannot omit any that are in the intent. +</p> + +<p> +In principle, therefore, an Intent object with no categories should always pass +this test, regardless of what's in the filter. That's mostly true. However, +with one exception, Android treats all implicit intents passed to {@link +android.content.Context#startActivity startActivity()} as if they contained +at least one category: "{@code android.intent.category.DEFAULT}" (the +{@code CATEGORY_DEFAULT} constant). +Therefore, activities that are willing to receive implicit intents must +include "{@code android.intent.category.DEFAULT}" in their intent filters. +(Filters with "{@code android.intent.action.MAIN}" and +"{@code android.intent.category.LAUNCHER}" settings are the exception. +They mark activities that begin new tasks and that are represented on the +launcher screen. They can include "{@code android.intent.category.DEFAULT}" +in the list of categories, but don't need to.) See <a href="#imatch">Using +intent matching</a>, later, for more on these filters.) +</p> +<dd> -<p> <dt><b>Data test</b></dt> <dd>Like the action and categories, the data specification for an intent filter is contained in a subelement. And, as in those cases, the subelement can appear multiple times, or not at all. For example: <pre><intent-filter . . . > - <data android:scheme="content" - android:host="com.example" - android:path="folder/*" . . . /> - <data android:scheme="content" - android:type="image/jpeg" . . . /> + <data android:type="video/mpeg" android:scheme="http" . . . /> + <data android:type="audio/mpeg" android:scheme="http" . . . /> . . . </intent-filter></pre> <p> -Each {@code <data>} element can specify a URI and a data type (MIME type). +Each {@code <data>} element can specify a URI and a data type (MIME media type). There are separate attributes — {@code scheme}, {@code host}, {@code port}, and {@code path} — for each part of the URI: +</p> -<dl><dd>{@code scheme://host:port/path}</dd></dl> +<p style="margin-left: 2em">{@code scheme://host:port/path}</p> <p> For example, in the following URI, +</p> -<dl><dd>{@code content://com.example.project:200/folder/subfolder/etc}</dd></dl> +<p style="margin-left: 2em">{@code content://com.example.project:200/folder/subfolder/etc}</p> <p> the scheme is "{@code content}", the host is "{@code com.example.project}", the port is "{@code 200}", and the path is "{@code folder/subfolder/etc}". The host and port together constitute the URI <i>authority</i>; if a host is not specified, the port is ignored. +</p> <p> Each of these attributes is optional, but they are not independent of each other: For an authority to be meaningful, a scheme must also be specified. For a path to be meaningful, both a scheme and an authority must be specified. +</p> <p> When the URI in an Intent object is compared to a URI specification in a filter, -it's compared only to the parts of the URI actually specified in the filter. +it's compared only to the parts of the URI actually mentioned in the filter. For example, if a filter specifies only a scheme, all URIs with that scheme match the filter. If a filter specifies a scheme and an authority but no path, all URIs with the same scheme and authority match, regardless of their paths. If a filter specifies a scheme, an authority, and a path, only URIs with the same scheme, authority, and path match. However, a path specification in the filter can contain wildcards to require only a partial match of the path. +</p> <p> -A {@code <data>} element specifies a MIME type with the {@code type} attribute. -Both the Intent object and the filter can use the '*" wildcard for the subtype field -— for example, "{@code text/*}" or "{@code image/*}" — indicating any -subtype matches. +The {@code type} attribute of a {@code <data>} element specifies the MIME type +of the data. It's more common in filters than a URI. Both the Intent object and +the filter can use a "*" wildcard for the subtype field — for example, +"{@code text/*}" or "{@code audio/*}" — indicating any subtype matches. +</p> <p> The data test compares both the URI and the data type in the Intent object to a URI and data type specified in the filter. The rules are as follows: +</p> -<ul> +<ol type="a"> +<li>An Intent object that contains neither a URI nor a data type passes the +test only if the filter likewise does not specify any URIs or data types.</li> -<p><li>An Intent object that contains neither a URI nor a data type passes the -test only if the filter likewise does not specify any URIs or data types. - -<p><li>An Intent object that contains a URI but no data type (and a type cannot +<li><p>An Intent object that contains a URI but no data type (and a type cannot be inferred from the URI) passes the test only if its URI matches a URI in the filter and the filter likewise does not specify a type. This will be the case -only for URIs like {@code mailto:} and {@code tel:} that do not refer to actual data. +only for URIs like {@code mailto:} and {@code tel:} that do not refer to actual data.</p></li> -<p><li>An Intent object that contains a data type but not a URI passes the test -only if the filter lists the same data type and similarly does not specify a URI. +<li><p>An Intent object that contains a data type but not a URI passes the test +only if the filter lists the same data type and similarly does not specify a URI.</p></li> -<p><li>An Intent object that contains both a URI and a data type (or a data type +<li><p>An Intent object that contains both a URI and a data type (or a data type can be inferred from the URI) passes the data type part of the test only if its type matches a type listed in the filter. It passes the URI part of the test either if its URI matches a URI in the filter or if it has a {@code content:} or {@code file:} URI and the filter does not specify a URI. In other words, a component is presumed to support {@code content:} and {@code file:} data if -its filter list only a data type. +its filter lists only a data type.</p></li> +</ol> +</dl> + +<p> +If an intent can pass through the filters of more than one activity or service, +the user may be asked which component to activate. An exception is raised if +no target can be found. +</p> + + +<h3><a name="ccases"></a>Common cases</h3> + +<p> +The last rule shown above for the data test, rule (d), reflects the expectation +that components are able to get local data from a file or content provider. +Therefore, their filters can list just a data type and do not need to explicitly +name the {@code content:} and {@code file:} schemes. +This is a typical case. A {@code <data>} element like the following, +for example, tells Android that the component can get image data from a content +provider and display it: +</p> + +<pre><data android:type="image/*" /></pre> -</ul> +<p> +Since most available data is dispensed by content providers, filters that +specify a data type but not a URI are perhaps the most common. +</p> + +<p> +Another common configuration is filters with a scheme and a data type. For +example, a {@code <data>} element like the following tells Android that +the component can get video data from the network and display it: +</p> + +<pre><data android:scheme="http" android:type="video/*" /></pre> + +<p> +Consider, for example, 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. +</p> <p> -If an intent can pass through the filters of more than one component, the user -may be asked which component to activate. +Most applications also have a way to start fresh, without a reference +to any particular data. Activities that can initiate applications +have filters with "{@code android.intent.action.MAIN}" specified as +the action. If they are to be represented in the application launcher, +they also specify the "{@code android.intent.category.LAUNCHER}" +category: +</p> + +<pre><intent-filter . . . > + <action android:name="code android.intent.action.MAIN" /> + <category android:name="code android.intent.category.LAUNCHER" /> +</intent-filter></pre> + + +<h3><a name="imatch"></a>Using intent matching</h3> + +<p> +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 "{@code android.intent.action.MAIN}" +action and "{@code android.intent.category.LAUNCHER}" category +(as illustrated in the previous section). 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 +"{@code android.intent.category.HOME}" in its filter. +</p> + +<p> +Your application can use intent matching is a similar way. +The {@link android.content.pm.PackageManager} has a set of {@code query...()} +methods that return all components that can accept a particular intent, and +a similar series of {@code resolve...()} methods that determine the best +component to respond to an intent. For example, +{@link android.content.pm.PackageManager#queryIntentActivities +queryIntentActivities()} returns a list of all activities that can perform +the intent passed as an argument, and {@link +android.content.pm.PackageManager#queryIntentServices +queryIntentServices()} returns a similar list of services. +Neither method activates the components; they just list the ones that +can respond. There's a similar method, +{@link android.content.pm.PackageManager#queryBroadcastReceivers +queryBroadcastReceivers()}, for broadcast receivers. +</p> + + + + diff --git a/docs/html/guide/topics/location/geo/mapkey.jd b/docs/html/guide/topics/location/geo/mapkey.jd new file mode 100644 index 0000000..110876f --- /dev/null +++ b/docs/html/guide/topics/location/geo/mapkey.jd @@ -0,0 +1,28 @@ +page.title=Obtaining a MapView API Key +@jd:body + +<p>{@link-fixme com.google.android.maps.MapView} is a very useful class that lets you easily integrate Google Maps into your application. It provides built-in map downloading, rendering, and caching, as well as a variety of display options and controls. It provides a wrapper around the Google Maps API that lets your application request and manipulate Google Maps data through class methods, and it lets you work with Maps data as you would other types of Views. </p> + +<p>Because MapView gives you access to Google Maps data, you need to register your application with the Google Maps service and agree to the applicable Terms of Service, before your MapView will be able to obtain data from Google Maps. This will apply whether you are developing your application on the emulator or preparing your application for deployment to mobile devices. </p> + +<p>Registering your application is simple, and has two parts: </p> + +<ol> +<li>Registering a public key fingerprint from the certificate that you will use to sign the .apk. The registration service then provides you a Maps API Key that is associated with your application's signer certificate. </li> +<li>Adding the Maps API Key to a special attribute of the MapView element — <code>android:apiKey</code>. You can use the same Maps API Key for any MapView in any application, provided that the application's .apk is signed with the certificate whose fingerprint you registered with the service. </li> +</ol> + +<p>Once you have registered your application as described above, your MapView will be able to retrieve data from the Google Maps servers. </p> + +<div class="special"> +<p>The MapView registration service is not yet active and Google Maps is not yet enforcing the Maps API Key requirement. The registration service will be activated soon, so that MapViews in any application deployed to a mobile device will require registration and a valid Maps API Key.</p> + +<p>As soon as the registration service becomes available, this page (<a href="http://code.google.com/android/toolbox/apis/mapkey.html">http://code.google.com/android/toolbox/apis/mapkey.html</a>) will be updated with details about how and where to register and how to add your Maps API Key to your application. </p> + +<p>In the meantime, you can continue developing your MapView without registration, provided that you:</p> +<ol type="a"> +<li>Add the attribute "android:apiKey" to the MapView element in your layout XML, with any value. Or</li> +<li>Include an arbitrary string in the <code>apikey</code> parameter of the MapView constructor, if creating the MapView programmatically. </li> +</ol> + +<p>When the Maps API Key checking is activated in the service, any MapViews that do not have a properly registered apiKey will stop working. The map data (tile images) of the MapView will never load (even if the device is on the network). In this case, go to the page linked above and read about how to register your certificate fingerprint and obtain a Maps API Key. </p> diff --git a/docs/html/guide/topics/location/index.jd b/docs/html/guide/topics/location/index.jd new file mode 100644 index 0000000..eeaab39 --- /dev/null +++ b/docs/html/guide/topics/location/index.jd @@ -0,0 +1,109 @@ +page.title=Location +@jd:body + +<div id="qv-wrapper"> +<div id="qv"> + + <h2>In this document</h2> + <ol> + <li><a href="#location">android.location</a></li> + <li><a href="#maps">com.google.android.maps</a></li> + </ol> +</div> +</div> + +<p>The Android SDK includes two packages that provide Android's primary support +for building location-based services: +{@link android.location} and {@link-fixme com.google.android.maps}. +Please read on below for a brief introduction to each package.</p> + +<h2 id="location">android.location</h2> + +<p>This package contains several classes related to +location services in the Android platform. Most importantly, it introduces the +{@link android.location.LocationManager} +service, which provides an API to determine location and bearing if the +underlying device (if it supports the service). The LocationManager +should <strong>not</strong> be +instantiated directly; rather, a handle to it should be retrieved via +{@link android.content.Context#getSystemService(String) +getSystemService(Context.LOCATION_SERVICE)}.</p> + +<p>Once your application has a handle to the LocationManager, your application +will be able to do three things:</p> + +<ul> + <li>Query for the list of all LocationProviders known to the + LocationManager for its last known location.</li> + <li>Register/unregister for periodic updates of current location from a + LocationProvider (specified either by Criteria or name).</li> + <li>Register/unregister for a given Intent to be fired if the device comes + within a given proximity (specified by radius in meters) of a given + lat/long.</li> +</ul> + +<p>However, during initial development, you may not have access to real +data from a real location provider (Network or GPS). So it may be necessary to +spoof some data for your application, with some mock location data.</p> + +<p class="note"><strong>Note:</strong> If you've used mock LocationProviders in +previous versions of the SDK (m3/m5), you can no longer provide canned LocationProviders +in the /system/etc/location directory. These directories will be wiped during boot-up. +Please follow the new procedures below.</p> + + +<h3>Providing Mock Location Data</h3> + +<p>When testing your application on the Android emulator, there are a couple different +ways to send it some spoof location data: with the DDMS tool or the "geo" command.</p> + +<h4 id="ddms">Using DDMS</h4> +<p>With the DDMS tool, you can simulate location data a few different ways:</p> +<ul> + <li>Manually send individual longitude/latitude coordinates to the device.</li> + <li>Use a GPX file describing a route for playback to the device.</li> + <li>Use a KML file describing individual placemarks for sequenced playback to the device.</li> +</ul> +<p>For more information on using DDMS to spoof location data, see the +<a href="{@docRoot}guide/developing/tools/ddms.html#emulator-control">Using DDMS guide</a>. + +<h4 id="geo">Using the "geo" command</h4> +<p>Launch your application in the Android emulator and open a terminal/console in +your SDK's <code>/tools</code> directory. Now you can use:</p> +<ul><li><code>geo fix</code> to send a fixed geo-location. + <p>This command accepts a longitude and latitude in decimal degrees, and + an optional altitude in meters. For example:</p> + <pre>geo fix -121.45356 46.51119 4392</pre> + </li> + <li><code>geo nmea</code> to send an NMEA 0183 sentence. + <p>This command accepts a single NMEA sentence of type '$GPGGA' (fix data) or '$GPRMC' (transit data). + For example:</p> + <pre>geo nmea $GPRMC,081836,A,3751.65,S,14507.36,E,000.0,360.0,130998,011.3,E*62</pre> + </li> +</ul> + + +<h2 id="maps">com.google.android.maps</h2> + +<p>This package introduces a number of classes related to +rendering, controlling, and overlaying customized information on your own +Google Mapified Activity. The most important of which is the +{@link-fixme com.google.android.maps.MapView} class, which automagically draws you a +basic Google Map when you add a MapView to your layout. Note that, if you +want to do so, then your Activity that handles the +MapView must extend {@link-fixme com.google.android.maps.MapActivity}. </p> + +<p>Also note that you must obtain a MapView API Key from the Google Maps +service, before your MapView can load maps data. For more information, see +<a href="{@docRoot}guide/developing/mapkey.html">Obtaining a MapView API Key</a>.</p> + +<p>Once you've created a MapView, you'll probably want to use +{@link-fixme com.google.android.maps.MapView#getController()} to +retrieve a {@link-fixme com.google.android.maps.MapController}, for controlling and +animating the map, and {@link-fixme com.google.android.maps.ItemizedOverlay} to +draw {@link-fixme com.google.android.maps.Overlay}s and other information on the Map.</p> + +<p>This is not a standard package in the Android library. In order to use it, you must add the following node to your Android Manifest file, as a child of the +<code><application></code> element:</p> +<pre><uses-library android:name="com.google.android.maps" /></pre> + diff --git a/docs/html/guide/topics/manifest/manifest.jd b/docs/html/guide/topics/manifest/manifest.jd index 2cf1976..bf9194c 100644 --- a/docs/html/guide/topics/manifest/manifest.jd +++ b/docs/html/guide/topics/manifest/manifest.jd @@ -1,183 +1,3063 @@ -page.title=The Manifest File (AndroidManifest.xml) +page.title=The AndroidManifest.xml File @jd:body -<p>Every Android application has a <em>manifest file</em> that declares global values for the application. -For example, the manifest file declares the appliication's fully qualified package name, as well as the application components (activities, services, etc) it exposes, the implementation classes for each, the kinds of data each can handle, -and where they can be launched. </p> - -<p>The manifest is an XML file that is always stored under the name <code>AndroidManifest.xml</code> in the root folder of the application. Only one manifest file is allowed per application package. As part of developing your android application, you will be creating the application's manifest file using the XML vocabulary described in this document. </p> - -<p>An important aspect of this file is the <em>intent filters</em> that it includes. - These filters describe where and when that activity can be started. When an activity - (or the operating system) wants to perform an action such as open a Web page - or open a contact picker screen, it creates an {@link android.content.Intent - Intent} object. This object can hold several descriptors describing what you - want to do, what data you want to do it to, the type of data, and other bits - of information. Android compares the information in an Intent object with the - intent filter exposed by every application and finds the activity most appropriate - to handle the data or action specified by the caller. More details - on intents is given in the {@link android.content.Intent - Intent} reference page.</p> - -<p>Besides declaring your application's activities, content providers, services, -and intent receivers, you can also specify permissions and instrumentation -(security control and testing) in AndroidManifest.xml. For a reference of the tags and -their attributes, please see {@link android.R.styleable#AndroidManifest}.</p> - -<p>A simple AndroidManifest.xml looks like this:</p> +<div id="qv-wrapper"> +<div id="qv"> + +<h2>In this document</h2> +<ol> +<li><a href="#filestruct">Structure of the Manifest File</a></li> +<li><a href="#filef">File Features</a> + <ol> + <li><a href="#ifs">Intent Filter</a></li> + <li><a href="#iconlabel">Icons and Labels</a></li> + <li><a href="#perms">Using Permissions</a></li> + <li><a href="#libs">Libraries</a></li> + </ol></li> +<li><a href="#elems">Elements of the Manifest File</a></li> +</ol> +</div> +</div> + +<p> +Every application must have an AndroidManifest.xml file (with precisely that +name) in its root directory. The manifest presents essential information about +the application to the Android system, information the system must have before +it can run any of the application's code. Among other things, the manifest +does the following: +</p> + +<ul> +<li>It names the Java package for the application. +The package name serves as a unique identifier for the application.</li> + +<li>It describes the components of the application — the activities, +services, broadcast receivers, and content providers that the application is +composed of. It names the classes that implement each of the components and +publishes their capabilities (for example, which {@link android.content.Intent +Intent} messages they can handle). These declarations let the Android system +know what the components are and under what conditions they can be launched.</li> + +<li>It determines which processes will host application components.</li> + +<li>It declares which permissions the application must have in order to +access protected parts of the API and interact with other applications.</li> + +<li>It also declares the permissions that others are required to have in +order to interact with the application's components.</li> + +<li>It lists the {@link android.app.Instrumentation} classes that provide +profiling and other information as the application is running. These declarations +are present in the manifest only while the application is being developed and +tested; they're removed before the application is published.</li> + +<li>It declares the minimum version of the Android API that the application +requires.</li> + +<li>It lists the libraries that the application must be linked against.</li> +</ul> + + +<h2 id="filestruct">Structure of the Manifest File</h2> + +<p> +A later section of this document, <a href="#elems">"Elements of the Manifest +File"</a>, describes all of the elements that can appear in the manifest file +and each of their attributes. The diagram below shows the general structure of +the file and every element it can contain. +</p> <pre> <?xml version="1.0" encoding="utf-8"?> -<manifest xmlns:android="http://schemas.android.com/apk/res/android" - package="com.my_domain.app.helloactivity"> - - <application android:label="@string/app_name"> - - <activity android:name=".HelloActivity"> - <intent-filter> - <action android:name="android.intent.action.MAIN"/> - <category android:name="android.intent.category.LAUNCHER"/> - </intent-filter> +<a href="#manf"><manifest></a> + + <a href="#usesp"><uses-permission /></a> + <a href="#prmsn"><permission /></a> + <a href="#ptree"><permission-tree /></a> + <a href="#pgroup"><permission-group /></a> + + <a href="#instru"><instrumentation /></a> + + <a href="#usess"><uses-sdk /></a> + + <a href="#app"><application></a> + + <a href="#actv"><activity></a> + <a href="#ifilt"><intent-filter></a> + <a href="#actn"><action /></a> + <a href="#catg"><category /></a> + <a href="#data"><data /></a> + <a href="#ifilt"></intent-filter></a> + <a href="#meta"><meta-data /></a> + <a href="#actv"></activity></a> + + <a href="#alias"><activity-alias></a> + <a href="#ifilt"><intent-filter></a> . . . <a href="#ifilt"></intent-filter></a> + <a href="#meta"><meta-data /></a> + <a href="#alias"></activity-alias></a> + + <a href="#srvc"><service></a> + <a href="#ifilt"><intent-filter></a> . . . <a href="#ifilt"></intent-filter></a> + <a href="#meta"><meta-data/></a> + <a href="#srvc"></service></a> + + <a href="#rcvr"><receiver></a> + <a href="#ifilt"><intent-filter></a> . . . <a href="#ifilt"></intent-filter></a> + <a href="#meta"><meta-data /></a> + <a href="#rcvr"></receiver></a> + + <a href="#pvdr"><provider></a> + <a href="#grantp"><grant-uri-permission /></a> + <a href="#meta"><meta-data /></a> + <a href="#pvdr"></provider></a> + + <a href="#usesl"><uses-library /></a> + + <a href="#app"></application></a> + +<a href="#manf"></manifest></a> +</pre> + +<p> +Some conventions and rules apply generally to all elements and attributes +in the manifest: +</p> + +<dl> +<dt><b>Elements</b></dt> +<dd>Only the {@code <a href="#manf"><manifest></a>} and +{@code <a href="#app"><application></a>} elements are required, they each +must be present and can occur only once. Most of the others can occur many times +or not at all — although at least some of them must be present for the +manifest to accomplish anything meaningful. + +<p> +If an element contains anything at all, it contains other elements. +All values are set through attributes, not as character data within an element. +</p> + +<p> +Elements at the same level are generally not ordered. For example, +{@code <a href="#actv"><activity></a>}, +{@code <a href{@code <a href="#pvdr"><provider></a>}, and +{@code <a href="#srvc"><service></a>} elements can be intermixed in +any sequence. (An {@code <a href="#alias"><activity-alias></a>} is the +exception to this rule: It must follow the {@code <a href="#actv"><activity></a>} +it is an alias for.)</p></dd> + +<dt><b>Attributes</b></dt> +<dd>In a formal sense, all attributes are optional. However, there are some +that must be specified for an element to accomplish its purpose. Use the +documentation as a guide. For truly optional attributes, it mentions a default +value or states what happens in the absence of a specification. + +<p>Except for some attributes of +the root {@code <a href="#manf"><manifest></a>} element, +all attribute names begin with an {@code android:} prefix — +for example, {@code android:alwaysRetainTaskState}. Because the prefix is +universal, this documentation generally omits it when referring to attributes +by name.</p></dd> + +<dt><b>Declaring class names</b></dt> +<dd>Many elements correspond to Java objects, including elements for the +application itself (the {@code <a href="#app"><application></a>} element) +and its principal components — +activities ({@code <a href="#actv"><activity></a>}), +services ({@code <a href="#srvc"><service></a>}), +broadcast receivers ({@code <a href="#rcvr"><receiver></a>}), +and content providers ({@code <a href="#pvdr"><provider></a>}). + +<p> +If you define a subclass, as you almost always would for the component classes +({@link android.app.Activity}, {@link android.app.Service}, +{@link android.content.BroadcastReceiver}, +and {@link android.content.ContentProvider}), the subclass is declared through +a {@code name} attribute. The name must include the full package designation. +For example, an {@link android.app.Service} subclass might be declared as follows: +</p> + +<pre><manifest . . . > + <application . . . > + <service android:name="com.example.project.SecretService" . . . > + . . . + </service> + . . . + </application> +</manifest></pre> + +<p> +However, as a shorthand, if the first character of the string is a period, the +string is appended to the application's package name (as specified by the +{@code <a href="#manf"><manifest></a>} element's +{@code <a href="#manf_package">package</a>} attribute). The following assignment +is the same as the one above: +</p> + +<pre><manifest package="com.example.project" . . . > + <application . . . > + <service android:name=".SecretService" . . . > + . . . + </service> + . . . + </application> +</manifest></pre> + +<p> +When starting a component, Android creates an instance of the named subclass. +If a subclass isn't specified, it creates an instance of the base class. +</p></dd> + +<dt><b>Multiple values</b></dt> +<dd>If more than one value can be specified, the element is almost always repeated, +rather than listing multiple values within a single element. +For example, an intent filter can list several actions: + +<pre><intent-filter . . . > + <action android:name="android.intent.action.EDIT" /> + <action android:name="android.intent.action.INSERT" /> + <action android:name="android.intent.action.DELETE" /> + . . . +</intent-filter></pre></dd> + +<dt><b>Resource values</b></dt> +<dd>Some attributes have values that can be displayed to users — for +example, a label and an icon for an activity. The values of these attributes +should be localized and therefore set from a resource or theme. Resource values +are expressed in the following format,</p> + +<p style="margin-left: 2em">{@code @[<i>package</i>:]<i>type</i>:<i>name</i>}</p> + +<p> +where the <i>package</i> name can be omitted if the resource is in the same package +as the application, <i>type</i> is a type of resource — such as "string" or +"drawable" — and <i>name</i> is the name that identifies the specific resource. +For example: +</p> + +<pre><activity android:icon="@drawable/smallPic" . . . ></pre> + +<p> +Values from a theme are expressed in a similar manner, but with an initial '?' +rather than '@': +</p> + +<p style="margin-left: 2em">{@code ?[<i>package</i>:]<i>type</i>:<i>name</i>} +</p></dd> + +<dt><b>String values</b></dt> +<dd>Where an attribute value is a string, double backslashes ('{@code \\}') +must be used to escape characters — for example, '{@code \\n}' for +a newline or '{@code \\uxxxx}' for a Unicode character.</dd> +</dl> + + +<h2 id="filef">File Features</h2> + +<p> +The following sections describe how some Android features are reflected +in the manifest file. +</p> + + +<h3 id="ifs">Intent Filters</h3> + +<p> +The core components of an application (its activities, services, and broadcast +receivers) are activated by <i>intents</i>. An intent is a +bundle of information (an {@link android.content.Intent} object) describing a +desired action — including the data to be acted upon, the category of +component that should perform the action, and other pertinent instructions. +Android locates an appropriate component to respond to the intent, launches +a new instance of the component if one is needed, and passes it the +Intent object. +</p> + +<p> +Components advertise their capabilities — the kinds of intents they can +respond to — through <i>intent filters</i>. Since the Android system +must learn which intents a component can handle before it launches the component, +intent filters are specified in the manifest as +{@code <a href="#ifilt"><intent-filter></a>} elements. A component may +have any number of filters, each one describing a different capability. +</p> + +<p> +An intent that explicitly names a target component will activate that component; +the filter doesn't play a role. But an intent that doesn't specify a target by +name can activate a component only if it can pass through one of the component's +filters. +</p> + +<p> +For information on how Intent objects are tested against intent filters, +a separate document, +<a href="{@docRoot}guide/topics/intents/intents-filters.html">Intents +and Intent Filters</a>. +</p> + + +<h3 id="iconlabel">Icons and Labels</h3> + +<p> +A number of elements have {@code icon} and {@code label} attributes for an +icon and a text label that can displayed to users. Some also have a +{@code description} attribute for longer explanatory text that can also be +shown on-screen. For example, the {@code <a href="#prmsn"><permission></a>} +element has all three of these attributes, so that when the user is asked whether +to grant the permission to an application that has requested it, an icon representing +the permission, the name of the permission, and a description of what it +entails can all be presented to the user. +</p> + +<p> +In every case, the icon and label set in a containing element become the default +{@code icon} and {@code label} settings for all of the container's subelements. +Thus, the icon and label set in the {@code <a href="#app"><application></a>} +element are the default icon and label for each of the application's components. +Similarly, the icon and label set for a component — for example, an +{@code <a href="#actv"><activity></a>} element — are the default +settings for each of the component's +{@code <a href="#ifilt"><intent-filter></a>} elements. If an +{@code <a href="#app"><application></a>} element sets a label, but +an activity and its intent filter do not, the application label is treated +as the label for both the activity and the intent filter. +</p> + +<p> +The icon and label set for an intent filter are used to represent a component +whenever the component is presented to the user as fulfilling the function +advertised by the filter. For example, a filter with +"{@code android.intent.action.MAIN}" and +"{@code android.intent.category.LAUNCHER}" settings advertises an activity +as one that initiates an application — that is, as +one that should be displayed in the application launcher. The icon and label +set in the filter are therefore the ones displayed in the launcher. +</p> + + +<h3 id="perms">Permissions</h3> + +<p> +A <i>permission</i> is a restriction limiting access to a part of the code +or to data on the device. The limitation is imposed to protect critical +data and code that could be misused to distort or damage the user experience. +</p> + +<p> +Each permission is identified +by a unique label. Often the label indicates the action that's restricted. +For example, here are some permissions defined by Android: +</p> + +<p style="margin-left: 2em">{@code android.permission.CALL_EMERGENCY_NUMBERS} +<br/>{@code android.permission.READ_OWNER_DATA} +<br/>{@code android.permission.SET_WALLPAPER} +<br/>{@code android.permission.DEVICE_POWER}</p> + +<p> +A feature can be protected by at most one permission. +</p> + +<p> +If an application needs access to a feature protected by a permission, it must +declare that it requires that permission with a +{@code <a href="#usesp"><uses-permission></a>} element in the manifest. +Then, when the application is installed on the device, the installer determines +whether or not to grant the requested permission by checking the authorities that +signed the application's certificates and, in some cases, asking the user. +If the permission is granted, the application is able to use the protected +features. If not, its attempts to access those features will simply fail +without any notification to the user. +</p> + +<p> +An application can also protect its own components (activities, services, +broadcast receivers, and content providers) with permissions. It can employ +any of the permissions defined by Android (listed in +{@link android.Manifest.permission android.Manifest.permission}) or declared +by other applications. Or it can define its own. A new permission is declared +with the {@code <a href="#prmsn"><permission></a>} element. +For example, an activity could be protected as follows: +</p> + +<pre> +<manifest . . . > + <permission android:name="com.example.project.DEBIT_ACCT" . . . /> + . . . + <application . . .> + <activity android:name="com.example.project.FreneticActivity" . . . > + android:permission="com.example.project.DEBIT_ACCT" + . . . > + . . . </activity> - </application> - + . . . + <uses-permission android:name="com.example.project.DEBIT_ACCT" /> + . . . </manifest> </pre> -<p>Some general items to note:</p> +<p> +Note that, in this example, the {@code DEBIT_ACCT} permission is not only +declared with the {@code <a href="#prmsn"><permission></a>} +element, its use is also requested with +the {@code <a href="#usesp"><uses-permission></a>} element. Its use +must be requested in order for other components of the application to launch +the protected activity, even though the protection is imposed by the +application itself. +</p> + +<p> +If, in the same example, the {@code permission} attribute was set to a +permission declared elsewhere +(such as {@code android.permission.CALL_EMERGENCY_NUMBERS}, it would not +have been necessary to declare it again with the +{@code <a href="#prmsn"><permission></a>} element. +However, it would still have been necessary to request its use with +{@code <a href="#usesp"><uses-permission></a>}. +</p> + +<p> +The {@code <a href="#ptree"><permission-tree></a>} element declares +a namespace for a group of permissions that will be defined in code. +And {@code <a href="#pgroup"><permission-group></a>} +defines a label for a set of permissions (both those declared in the +manifest with {@code <a href="#prmsn"><permission></a>} elements and +those declared elsewhere). It affects only how the permissions are grouped +when presented to the user. +</p> + + +<h3 id="libs">Libraries</h3> + +<p> +Every application is linked against the default Android library, which +includes the basic packages for building applications (with common classes +such as Activity, Service, Intent, View, Button, Application, ContentProvider, +and so on). +</p> + +<p> +However, some packages reside in their own libraries. If your application +uses code from any of these packages, it must explicitly asked to be linked +against them. The manifest must contain a separate +{@code <a href="#usesl"><uses-library></a>} element to name each +of the libraries. (The library name can be found in the documentation +for the package.) +</p> + + +<h2 id="elems">Elements of the Manifest File</h2> + +<p> +This section describes all the elements that can appear in the manifest and each +of their attributes in more detail. Only the elements listed here are legal. +The list is alphabetical. +</p> + + +<h3 id="actn"><action></h3> + +<dl class="xml"> +<dt>syntax:</dt> +<dd><pre class="stx"><action android:name="<i>string</i>" /></pre></dd> + +<dt>contained in:</dt> +<dd>{@code <a href="#ifilt"><intent-filter></a>}</dd> + +<p> +<dt>description:</dt> +<dd>Adds an action to an intent filter. +An {@code <a href="#ifilt"><intent-filter></a>} element must contain +one or more {@code <action>} elements. If it doesn't contain any, no +Intent objects will get through the filter. See +<a href="{@docRoot}guide/topics/intents/intents-filters.html">Intents and +Intent Filters</a> for details on intent filters and the role of action +specifications within a filter. +</dd> + +<dt>attributes:</dt> +<dd><dl class="attr"> +<dt>{@code android:name}</dt> +<dd>The name of the action. Some standard actions are defined in the +{@link android.content.Intent#ACTION_CHOOSER Intent} class as +{@code ACTION_<i>string</i>} constants. To assign one of these actions to +this attribute, prepend "{@code android.intent.action.}" to the +{@code <i>string</i>} that follows {@code ACTION_}. +For example, for {@code ACTION_MAIN}, use "{@code android.intent.action.MAIN}" +and for {@code ACTION_WEB_SEARCH}, use "{@code android.intent.action.WEB_SEARCH}". + +<p> +For actions you define, it's best to use the package name as a prefix to +ensure uniqueness. For example, a {@code TRANSMOGRIFY} action might be specified +as follows: +</p> + +<pre><action android:name="com.example.project.TRANSMOGRIFY" /></pre> +</dd> +</dl></dd> + +<dt>see also:</dt> +<dd>{@code <a href="#ifilt"><intent-filter></a>}</dd> + +</dl> +<hr> + +<h3 id="actv"><activity></h3> + +<dl class="xml"> +<dt>syntax:</dt> +<dd><pre class="stx"><activity android:allowTaskReparenting=["true" | "false"] + android:alwaysRetainTaskState=["true" | "false"] + android:clearTaskOnLaunch=["true"" | "false"] + android:configChanges=["mcc" | "mnc" | "locale" | + "touchscreen" | "keyboard" | + "keyboardHidden" | "navigation" | + "orientation" | "fontScale"] + android:enabled=["true" | "false"] + android:excludeFromRecents=["true" | "false"] + android:exported=["true" | "false"] + android:finishOnTaskLaunch=["true" | "false"] + android:icon="<i>drawable resource</i>" + android:label="<i>string resource</i>" + android:launchMode=["multiple" | "singleTop" | + "singleTask" | "singleInstance"] + android:multiprocess=["true" | "false"] + android:name="<i>string</i>" + android:permission="<i>string</i>" + android:process="<i>string</i>" + android:screenOrientation=["unspecified" | "user" | "behind" | + "landscape" | "portrait" | + "sensor" | "nonsensor"] + android:stateNotNeeded=["true" | "false"] + android:taskAffinity="<i>string</i>" + android:theme="<i>resource or theme</i>" > + . . . +</activity></pre></dd> + +<dt>contained in:</dt> +<dd>{@code <a href="#app"><application></a>}</dd> + +<dt>can contain:</dt> +<dd>{@code <a href="#ifilt"><intent-filter></a>} +<br/>{@code <a href="#meta"><meta-data></a>}</dd> + +<dt>description:</dt> +<dd>Declares an activity (an {@link android.app.Activity} subclass) that +implements part of the application's visual user interface. All activities +must be represented by {@code <activity>} +elements in the manifest file. Any that are not declared there will not be seen +by the system and will never be run. + +<dt>attributes:</dt> +<dd><dl class="attr"> +<dt><a href name="actv_reparent"></a>{@code android:allowTaskReparenting}</dt> +<dd>Whether or not the activity can move from the task that started it to +the task it has an affinity for when that task is next brought to the +front — "{@code true}" if it can move, and "{@code false}" if it +must remain with the task where it started. + +<p> +If this attribute is not set, the value set by the corresponding +{@code <a href="#app_reparent">allowTaskReparenting</a>} +attribute of the {@code <a href="#app"><application></a>} element +applies to the activity. The default value is "{@code false}". +</p> + +<p> +Normally when an activity is started, it's associated with the task of +the activity that started it and it stays there for its entire lifetime. +You can use this attribute to force it to be re-parented to the task it +has an affinity for when its current task is no longer displayed. +Typically, it's used to cause the activities of an application to move +to the main task associated with that application. +</p> + +<p> +For example, if an e-mail message contains a link to a web page, clicking +the link brings up an activity that can display the page. That activity +is defined by the browser application, but is launched as part of the e-mail +task. If it's reparented to the browser task, it will be shown when the +browser next comes to the front, and will be absent when the e-mail task +again comes forward. +</p> + +<p> +The affinity of an activity is defined by the +{@code <a href="#actv_aff">taskAffinity</a>} attribute. The affinity +of a task is determined by reading the affinity of its root activity. +Therefore, by definition, a root activity is always in a task with the +same affinity. Since activities with "{@code singleTask}" or +"{@code singleInstance}" launch modes can only be at the root of a task, +re-parenting is limited to the "{@code standard}" and "{@code singleTop}" +modes. (See also the {@code <a href="#actv_lmode">launchMode</a>} +attribute.) +</p></dd> + +<dt>{@code android:alwaysRetainTaskState}</dt> +<dd>Whether or not the state of the task that the activity is in will always +be maintained by the system — "{@code true}" if it will be, and +"{@code false}" if the system is allowed to reset the task to its initial +state in certain situations. The default value is "{@code false}". This +attribute is meaningful only for the root activity of a task; it's ignored +for all other activities. + +<p> +Normally, the system clears a task (removes all activities from the stack +above the root activity) in certain situations when the user re-selects that +task from the home screen. Typically, this is done if the user hasn't visited +the task for a certain amount of time, such as 30 minutes. +</p> + +<p> +However, when this attribute is "{@code true}", users will always return +to the task in its last state, regardless of how they get there. This is +useful, for example, in an application like the web browser where there is +a lot of state (such as multiple open tabs) that users would not like to lose. +</p></dd> + +<dt>{@code android:clearTaskOnLaunch}</dt> +<dd>Whether or not all activities will be removed from the task, except for +the root activity, whenever it is re-launched from the home screen — +"{@code true}" if the task is always stripped down to its root activity, and +"{@code false}" if not. The default value is "{@code false}". This attribute +is meaningful only for activities that start a new task (the root activity); +it's ignored for all other activities in the task. + +<p> +When the value is "{@code true}", every time users start the task again, they +are brought to its root activity, regardless of what they were last doing in +the task and regardless of whether they used BACK or HOME to last leave it. +When the value is "{@code false}", the task may be cleared of activities in +some situations (see the {@code alwaysRetainTaskState} attribute), but not always. +</p> + +<p> +Suppose, for example, that someone launches activity P from the home screen, +and from there goes to activity Q. The user next presses HOME, and then returns +to activity P. Normally, the user would see activity Q, since that is what they +were last doing in P's task. However, if P set this flag to "{@code true}", all +of the activities on top of it (Q in this case) were removed when the user pressed +HOME and the task went to the background. So the user sees only P when returning +to the task. +</p> + +<p> +If this attribute and {@code allowTaskReparenting} are both "{@code true}", +any activities that can be re-parented are moved to the task they share an +affinity with; the remaining activities are then dropped, as described above. +</p></dd> + +<dt>{@code android:configChanges}</dt> +<dd>Lists configuration changes that the activity will handle itself. When +changes that are not listed occur, the activity is shut down and restarted. +When a listed change occurs, the activity remains running and its <code>{@link android.app.Activity#onConfigurationChanged onConfigurationChanged()}</code> +method is called. + +<p> +Any or all of the following strings can be used to set this attribute. Values are +separated by '{@code |}' — for example, "{@code locale|navigation|orientation}". +</p> + +<table> +<tr> + <td><b>Value</b></td> + <td><b>Description</b></td> +</tr><tr> + <td>"{@code mcc}"</td> + <td>The IMSI mobile country code (MCC) has changed — + that is, a SIM has been detected and updated the MCC.</td> +</tr><tr> + <td>"{@code mnc}"</td> + <td>The IMSI mobile network code (MNC) has changed — + that is, a SIM has been detected and updated the MNC.</td> +</tr><tr> + <td>"{@code locale}"</td> + <td>The locale has changed — for example, the user has selected a new + language that text should be displayed in.</td> +</tr><tr> + <td>"{@code touchscreen}"</td> + <td>The touchscreen has changed. (This should never normally happen.)</td> +</tr><tr> + <td>"{@code keyboard}"</td> + <td>The keyboard type has changed — for example, the user has + plugged in an external keyboard.</td> +</tr><tr> + <td>"{@code keyboardHidden}"</td> + <td>The keyboard accessibility has changed — for example, the + user has slid the keyboard out to expose it.</td> +</tr><tr> + <td>"{@code navigation}"</td> + <td>The navigation type has changed. (This should never normally happen.)</td> +</tr><tr> + <td>"{@code orientation}"</td> + <td>The screen orientation has changed — that is, the user has rotated + the device.</td> + </tr><tr> + <td>"{@code fontScale}"</td> + <td>The font scaling factor has changed — that is, the user has selected + a new global font size.</td> +</tr> +</table> + +<p> +All of these configuration changes can impact the resource values seen by the +application. Therefore, when <code>{@link android.app.Activity#onConfigurationChanged +onConfigurationChanged()}</code> is called, it will generally be necessary to again +retrieve all resources (including view layouts, drawables, and so on) to correctly +handle the change. +</p></dd> + +<dt>{@code android:enabled}</dt> +<dd>Whether or not the activity can be instantiated by the system — +"{@code true}" if it can be, and "{@code false}" if not. The default value +is "{@code true}". + +<p> +The {@code <a href="#app"><application></a>} element has its own +{@code <a href="#app_enabled">enabled</a>} attribute that applies to all +application components, including activities. The +{@code <a href="#app"><application></a>} and {@code <activity>} +attributes must both be "{@code true}" (as they both are by default) for +the system to be able to instantiate the activity. If either is +"{@code false}", it cannot be instantiated. +</p></dd> + +<dt>{@code android:excludeFromRecents}</dt> +<dd>Whether or not the activity should be excluded from the list of recently +launched activities that can be displayed to users — "{@code true}" if +it should be excluded, and "{@code false}" if it should be included. +The default value is "{@code false}". +</p></dd> + +<dt>{@code android:exported}</dt> +<dd>Whether or not the activity can be launched by components of other +applications — "{@code true}" if it can be, and "{@code false}" if not. +If "{@code false}", the activity can be launched only by components of the +same application or applications with the same user ID. + +<p> +The default value depends on whether the activity contains intent filters. The +absence of any filters means that the activity can be invoked only by specifying +its exact class name. This implies that the activity is intended only for +application-internal use (since others would not know the class name). So in +this case, the default value is "{@code false}". +On the other hand, the presence of at least one filter implies that the activity +is intended for external use, so the default value is "{@code true}". +</p> + +<p> +This attribute is not the only way to limit an activity's exposure to other +applications. You can also use a permission to limit the external entities that +can invoke the activity (see the {@code <a href="#actv_prmsn">permission</a>} +attribute). +</p></dd> + +<dt>{@code android:finishOnTaskLaunch}</dt> +<dd>Whether or not an existing instance of the activity should be shut down +(finished) whenever the user again launches its task (chooses the task on the +home screen) — "{@code true}" if it should be shut down, and "{@code false}" +if not. The default value is "{@code false}". + +<p> +If this attribute and {@code <a href="#actv_reparent">allowTaskReparenting</a>} +are both "{@code true}", this attribute trumps the other. The affinity of the +activity is ignored. The activity is not re-parented, but destroyed. +</p> + +<dt><a name="actv_icon"></a>{@code android:icon}</dt> +<dd>An icon representing the activity. The icon is displayed to users when +a representation of the activity is required on-screen. For example, icons +for activities that initiate tasks are displayed in the launcher window. +The icon is often accompanied by a label (see the {@code label} attribute). +</p> + +<p> +This attribute must be set as a reference to a drawable resource containing +the image definition. If it is not set, the icon specified for the application +as a whole is used instead (see the {@code <a href="#app"><application></a>} +element's {@code <a href="#app_icon">icon</a>} attribute). +</p> + +<p> +The activity's icon — whether set here or by the +{@code <a href="#app"><application></a>} element — is also the +default icon for all the activity's intent filters (see the +{@code <a href="#ifilt"><intent-filter></a>} element's +{@code <a href="#ifilt_icon">icon</a>} attribute). +</p></dd> + +<dt>{@code android:label}</dt> +<dd>A user-readable label for the activity. The label is displayed on-screen +when the activity must be represented to the user. It's often displayed along +with the activity icon. + +<p> +If this attribute is not set, the label set for the application as a whole is +used instead (see the {@code <a href="#app"><application></a>} element's +{@code <a href="#app_label">label</a>} attribute). +</p> + +<p> +The activity's label — whether set here or by the +{@code <a href="#app"><application></a>} element — is also the +default label for all the activity's intent filters (see the +{@code <a href="#ifilt"><intent-filter></a>} element's +{@code <a href="#ifilt_label">label</a>} attribute). +</p> + +<p> +The label should be set as a reference to a string resource, so that +it can be localized like other strings in the user interface. +However, as a convenience while you're developing the application, +it can also be set as a raw string. +</p></dd> + +<dt><a name="actv_lmode"></a>{@code android:launchMode}</dt> +<dd>An instruction on how the activity should be launched. There are four modes +that work in conjunction with activity flags ({@code FLAG_ACTIVITY_*} constants) +in {@link android.content.Intent} objects to determine what should happen when +the activity is called upon to handle an intent: + +<p style="margin-left: 2em">"{@code standard}" +<br>"{@code singleTop}" +<br>"{@code singleTask}" +<br>"{@code singleInstance}"</p> + +<p> +The default mode is "{@code standard}". +The modes differ from each other on three points: +</p> + +<ol> + +<li><p><b>Whether or not a new instance of the class will be launched</b>. For +the default "{@code standard}" mode, every time a new intent is received, a new +instance of the class is created to handle that intent. For all the other modes, +an existing instance is re-used if it resides at the top of the activity stack. +As we'll see below, if there's an existing instance of a "{@code singleTask}" or +"{@code singleInstance}" activity, it will always be (or come to be) at the top +of the stack, so this condition will always be met for those two modes. However, +an existing "{@code singleTop}" instance may or may not be at the top of the stack. +If it is, it will be re-used. If not, a new instance is created.</p> + +<p> +For example, suppose a task's activity stack consists of root activity A with +activities B, C, and D on top in that order, so the stack is A-B-C-D. An intent +arrives for an activity of type D. If D has the default "{@code standard}" launch +mode, a new instance of the class is launched and the stack becomes A-B-C-D-D. +However, if D's launch mode is "{@code singleTop}", the existing instance is +expected to handle the new intent (since it's at the top of the stack) and the +stack remains A-B-C-D. +</p> + +<p> +If, on the other hand, the arriving intent is for an activity of type B, a new +instance of B would be launched no matter whether B's mode is "{@code standard}" +or "{@code singleTop}" (since B is not at the top of the stack), so the resulting +stack would be A-B-C-D-B. +</p> + +<p> +Now, suppose again that the stack is A-B-C-D and that the intent that arrives for +B has the <code>{@link android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP}</code> flag set. Since +the intent is destined for an activity of type B and the stack already has an object +of that type, the flag causes activities C and D to be shut down and removed from +the stack. If B's launch mode is "{@code standard}", it too will be removed, and +a new instance of B launched to handle the incoming intent. That's because a new +instance is always created for a new intent when the launch mode is "{@code standard}". +However, if B's launch mode is "{@code singleTop}", the current instance would remain +in the stack and receive the intent. +</p> + +<p> +Whenever an existing "{@code singleTop}", "{@code singleTask}", or +"{@code singleInstance}" object is expected to handle an incoming intent, its +<code>{@link android.app.Activity#onNewIntent onNewIntent()}</code> method is called with the +{@link android.content.Intent} object passed as an argument. +</p> +</li> + +<li><p><b>Which task will hold the activity that responds to the intent</b>. +For the "{@code standard}" and "{@code singleTop}" modes, it's the task that +originated the intent (and called <code>{@link android.content.Context#startActivity +startActivity()}</code>) — unless the Intent object contains the +<code>{@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK}</code> flag. In that case, +a different task is chosen as follows:</p> <ul> -<li> <p>Almost every AndroidManifest.xml (as well as many other Android -XML files) will include the namespace declaration -<code>xmlns:android="http://schemas.android.com/apk/res/android"</code> in -its first element. This makes a variety of standard Android attributes -available in the file, which will be used to supply most of the data for -elements in that file.</code> -<li> <p>Most manifests include a single <code><application></code> -element, which defines all of the application-level components and -properties that are available in the package.</p> -<li> <p>Any package that will be presented to the user as a top-level -application available from the program launcher will need to include at -least one {@link android.app.Activity} component that supports the -{@link android.content.Intent#ACTION_MAIN MAIN} action and -{@link android.content.Intent#CATEGORY_LAUNCHER LAUNCHER} category as -shown here.</p> +<li>If there's an existing task with the same affinity as the target activity, +that task will hold the instance that responds to the intent. (As noted above, +it could be an existing instance for a "{@code singleTop}" activity, but will +always be a new instance for a "{@code standard}" activity.)</li> + +<li>Otherwise, the activity is launched as the root of a new task.</li> </ul> -<p>Here is a detailed outline of the structure of an AndroidManifest.xml file, -describing all tags that are available.</p> +<p> +In contrast, the "{@code singleTask}" and "{@code singleInstance}" modes mark +activities that will always be at the root of a task; they can never be launched +as part of another task. Moreover, once a "{@code singleTask}" or +"{@code singleInstance}" activity has been launched, that instance is re-used +to handle all new intents, so there is never more than one instance of the +activity on the device. +</p> + +<p> +When a new intent arrives for an existing "{@code singleTask}" activity, all +other activities are removed from its stack, so that only the root activity +remains; it's as if the Intent object included the +<code>{@link android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP}</code> flag. The activity +is then at the top of its stack, and in a position to receive the new intent +in an <code>{@link android.app.Activity#onNewIntent onNewIntent()}</code> call. +</p></li> + +<li><p><b>Whether the instance can have other activities in its task</b>. +A "{@code singleInstance}" activity stands alone as the only activity in its +task. If it starts another activity, that activity will be launched in a +different task regardless of its launch mode. In all other respects, the +"{@code singleInstance}" mode is identical to "{@code singleTask}".</p> + +<p> +All modes other than "{@code singleInstance}" permit multiple activities +to belong to the task. +</p></li> +</ol> +</dd> + +<dt>{@code android:multiprocess}</dt> +<dd>Whether an instance of the activity can be launched into the process of the component +that started it — "{@code true}" if it can be, and "{@code false}" if not. +The default value is "{@code false}". + +<p> +Normally, a new instance of an activity is launched into the process of the +application that defined it, so all instances of the activity run in the same +process. However, if this flag is set to "{@code true}", instances of the +activity can run in multiple processes, allowing the system to create instances +wherever they are used (provided permissions allow it), something that is almost +never necessary or desirable. +</p></dd> + +<dt>{@code android:name}</dt> +<dd>The name of the class that implements the activity, a subclass of +{@link android.app.Activity}. The attribute value should be a fully qualified +class name (such as, "{@code com.example.project. ExtracurricularActivity}"). +However, as a shorthand, if the first character of the name is a period +(for example, "{@code . ExtracurricularActivity}"), it is appended to the +package name specified in the {@code <a href="#manf"><manifest></a>} +element. + +<p> +There is no default. The name must be specified. +</p></dd> + +<dt><a name="actv_prmsn"></a>{@code android:permission}</dt> +<dd>The name of a permission that clients must have to launch the activity +or otherwise get it to respond to an intent. If a caller of +<code>{@link android.content.Context#startActivity startActivity()}</code> or +<code>{@link android.app.Activity#startActivityForResult startActivityForResult()}</code> +has not been granted the specified permission, its intent will not be +delivered to the activity. + +<p> +If this attribute is not set, the permission set by the +{@code <a href="#app"><application></a>} element's +{@code <a href="#app_prmsn">permission</a>} attribute applies +to the activity. If neither attribute is set, the activity is +not protected by a permission. +</p> + +<p> +For more information on permissions, see the <a href="#sectperm">Permissions</a> +section earlier in this document and a separate document, +<a href="{@docRoot}guide/topics/security/security.html">Security and +Permissions</a>. +</p></dd> + +<dt>{@code android:process}</dt> +<dd>The name of the process in which the activity should run. Normally, +all components of an application run in the default process created for the +application. It has the same name as the application package. The {@code <a href="#app"><application></a>} element's +{@code <a href="#app_proc">process</a>} attribute can set a different +default for all components. But each component can override the default, +allowing you to spread your application across multiple processes. + +<p> +If the name assigned to this attribute begins with a colon (':'), a new +process, private to the application, is created when it's needed and +the activity runs in that process. +If the process name begins with a lowercase character, the activity will run +in a global process of that name, provided that it has permission to do so. +This allows components in different applications to share a process, reducing +resource usage. +</p></dd> + +<dt>{@code android:screenOrientation}</dt> +<dd>The orientation of the activity's display on the device. +The value can be any one of the following strings: + +<table> +<tr> + <td>"{@code unspecified}"</td> + <td>The default value. The system chooses the orientation. The policy it + uses, and therefore the choices made in specific contexts, may differ + from device to device.</td> +</tr><tr> + <td>"{@code landscape}"</td> + <td>Landscape orientation (the display is wider than it is tall).</td> +</tr><tr> + <td>"{@code portrait}"</td> + <td>Portrait orientation (the display is taller than it is wide).</td> +</tr><tr> + <td>"{@code user}"</td> + <td>The user's current preferred orientation.</td> +</tr><tr> + <td>"{@code behind}"</td> + <td>The same orientation as the activity that's immediately beneath it in + the activity stack.</td> +</tr><tr> + <td>"{@code sensor}"</td> + <td>The orientation determined by a physical orientation sensor. The + orientation of the display depends on how the user is holding the device; + it changes when the user rotates the device.</td> +</tr><tr> + <td>"{@code nosensor}"</td> + <td>An orientation determined without reference to a physical orientation sensor. + The sensor is ignored, so the display will not rotate based on how the user + moves the device. Except for this distinction, the system chooses the + orientation using the same policy as for the "{@code unspecified}" setting.</td> +</tr> +</table></dd> + +<dt>{@code android:stateNotNeeded}</dt> +<dd>Whether or not the activity can be killed and successfully restarted +without having saved its state — "{@code true}" if it can be restarted +without reference to its previous state, and "{@code false}" if its previous +state is required. The default value is "{@code false}". + +<p> +Normally, before an activity is temporarily shut down to save resources, its +<code>{@link android.app.Activity#onSaveInstanceState onSaveInstanceState()}</code> +method is called. This method stores the current state of the activity in a +{@link android.os.Bundle} object, which is then passed to +<code>{@link android.app.Activity#onCreate onCreate()}</code> when the activity +is restarted. If this attribute is set to "{@code true}", +{@code onSaveInstanceState()} may not be called and {@code onCreate()} will +be passed {@code null} instead of the Bundle — just as it was when the +activity started for the first time. +</p> + +<p> +A "{@code true}" setting ensures that the activity can be restarted in the +absence of retained state. For example, the activity that displays the +home screen uses this setting to make sure that it does not get removed if it +crashes for some reason. +</p></dd> + +<dt><a name="actv_aff"></a>{@code android:taskAffinity}</dt> +<dd>The task that the activity has an affinity for. Activities with +the same affinity conceptually belong to the same task (to the same +"application" from the user's perspective). The affinity of a task +is determined by the affinity of its root activity. + +<p> +The affinity determines two things — the task that the activity is re-parented +to (see the {@code <a href="#actv_reparent">allowTaskReparenting</a>} +attribute) and the task that will house the activity when it is launched +with the <code>{@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK}</code> +flag. +</p> + +<p> +By default, all activities in an application have the same affinity. You +can set this attribute to group them differently, and even place +activities defined in different applications within the same task. To +specify that the activity does not have an affinity for any task, set +it to an empty string. + +<p> +If this attribute is not set, the activity inherits the affinity set +for the application (see the {@code <a href="#app"><application></a>} +element's {@code <a href="#app_aff">taskAffinity</a>} attribute). +The name of the default affinity for an application is the package name set +by the {@code <a href="#manf"><manifest></a>} element. +</p> + +<dt><a name="actv_theme"></a>{@code android:theme}</dt> +<dd>A reference to a style resource defining an overall theme for the activity. +This automatically sets the activity's context to use this theme (see +<code>{@link android.content.Context#setTheme setTheme()}</code>, and may also +cause "starting" animations prior to the activity being launched (to better +match what the activity actually looks like). + +<p> +If this attribute is not set, the activity inherits the theme set for the +application as a whole — see the {@code <a href="#app"><application></a>} +element's {@code <a href="#app_theme">theme</a>} attribute. If that attribute is +also not set, the default system theme is used. +</p> +<dd> +</dl></dd> + +</dl> +<hr> + + +<h3 id="alias"><activity-alias></h3> + +<dl class="xml"> +<dt>syntax:</dt> +<dd><pre class="stx"><activity-alias android:enabled=["true" | "false"] + android:exported=["true" | "false"] + android:icon="<i>drawable resource</i>" + android:label="<i>string resource</i>" + android:name="<i>string</i>" + android:permission="<i>string</i>" + android:targetActivity="<i>string</i>" > + . . . +</activity-alias></pre></dd> + +<dt>contained in:</dt> +<dd>{@code <a href="#app"><application></a>}</dd> + +<dt>can contain:</dt> +<dd>{@code <a href="#ifilt"><intent-filter></a>} +<br/>{@code <a href="#meta"><meta-data></a>}</dd> + +<dt>description:</dt> +<dd>An alias for an activity, named by the {@code targetActivity} +attribute. The target must be in the same application as the +alias and it must be declared before the alias in the manifest. + +<p> +The alias presents the target activity as a independent entity. +It can have its own set of intent filters, and they, rather than the +intent filters on the target activity itself, determine which intents +can activate the target through the alias and how the system +treats the alias. For example, the intent filters on the alias may +specify the "<code>{@link android.content.Intent#ACTION_MAIN +android.intent.action.MAIN}</code>" +and "<code>{@link android.content.Intent#CATEGORY_LAUNCHER +android.intent.category.LAUNCHER}</code>" flags, causing it to be +represented in the application launcher, even though none of the +filters on the target activity itself set these flags. +</p> + +<p> +With the exception of {@code targetActivity}, {@code <activity-alias>} +attributes are a subset of {@code <a href="#actv"><activity></a>} attributes. +For attributes in the subset, none of the values set for the target carry over +to the alias. However, for attributes not in the subset, the values set for +the target activity also apply to the alias. +</p></dd> + +<dt>attributes:</dt> +<dd><dl class="attr"> +<dt>{@code android:enabled}</dt> +<dd>Whether or not the target activity can be instantiated by the system through +this alias — "{@code true}" if it can be, and "{@code false}" if not. +The default value is "{@code true}". + +<p> +The {@code <a href="#app"><application></a>} element has its own +{@code <a href="#app_enabled">enabled</a>} attribute that applies to all +application components, including activity aliases. The +{@code <a href="#app"><application></a>} and {@code <activity-alias>} +attributes must both be "{@code true}" for the system to be able to instantiate +the target activity through the alias. If either is "{@code false}", the alias +does not work. +</p></dd> + +<dt>{@code android:exported}</dt> +<dd>Whether or not components of other applications can launch the target activity +through this alias — "{@code true}" if they can, and "{@code false}" if not. +If "{@code false}", the target activity can be launched through the alias only by +components of the same application as the alias or applications with the same user ID. + +<p> +The default value depends on whether the alias contains intent filters. The +absence of any filters means that the activity can be invoked through the alias +only by specifying the exact name of the alias. This implies that the alias +is intended only for application-internal use (since others would not know its name) +— so the default value is "{@code false}". +On the other hand, the presence of at least one filter implies that the alias +is intended for external use — so the default value is "{@code true}". +</p></dd> + +<dt>{@code android:icon}</dt> +<dd>An icon for the target activity when presented to users through the alias. +See the {@code <a href="#actv"><activity></a>} element's +{@code <a href="#actv_icon">icon</a>} attribute for more information. + +<dt>{@code android:label}</dt> +<dd>A user-readable label for the alias when presented to users through the alias. +See the the {@code <a href="#actv"><activity></a>} element's +{@code <a href="#actv_label">label</a>} attribute for more information. +</p></dd> + +<dt>{@code android:name}</dt> +<dd>A unique name for the alias. The name should resemble a fully +qualified class name. But, unlike the name of the target activity, +the alias name is arbitrary; it does not refer to an actual class. +</p></dd> + +<dt>{@code android:permission}</dt> +<dd>The name of a permission that clients must have to launch the target activity +or get it to do something via the alias. If a caller of +<code>{@link android.content.Context#startActivity startActivity()}</code> or +<code>{@link android.app.Activity#startActivityForResult startActivityForResult()}</code> +has not been granted the specified permission, the target activity will not be +activated. + +<p>This attribute supplants any permission set for the target activity itself. If +it is not set, a permission is not needed to activate the target through the alias. +</p> + +<p> +For more information on permissions, see the {@code <a href="#perms">Permissions</a> +section earlier in this document. +</p></dd> + +<dt>{@code android:targetActivity}</dt> +<dd>The name of the activity that can be activated through the alias. +This name must match the {@code name} attribute of an +{@code <a href="#actv"><activity></a>} element that precedes +the alias in the manifest. +</p></dd> +</dl></dd> + +<dt>see also:</dt> +<dd>{@code <a href="#actv"><activity></a>}</dd> + +</dl> +<hr> + +<h3 id="app"><application></h3> + +<dl class="xml"> +<dt>syntax:</dt> +<dd><pre class="stx"><application android:allowClearUserData=["true" | "false"] + android:allowTaskReparenting=["true" | "false"] + android:debuggable=["true" | "false"] + android:description="<i>string resource</i>" + android:enabled=["true" | "false"] + android:hasCode=["true" | "false"] + android:icon="<i>drawable resource</i>" + android:label="<i>string resource</i>" + android:manageSpaceActivity="<i>string</i>" + android:name="<i>string</i>" + android:permission="<i>string</i>" + android:persistent=["true" | "false"] + android:process="<i>string</i>" + android:taskAffinity="<i>string</i>" + android:theme="<i>resource or theme</i>" > + . . . +</application></pre></dd> + +<dt>contained in:</dt> +<dd>{@code <a href="#manf"><manifest></a>}</dd> + +<dt>can contain:</dt> +<dd>{@code <a href="#actv"><activity></a>} +<br/>{@code <a href="#alias"><activity-alias></a>} +<br/>{@code <a href="#srvc"><service></a>} +<br/>{@code <a href="#rcvr"><receiver></a>} +<br/>{@code <a href="#pvdr"><provider></a>} +<br/>{@code <a href="#usesl"><uses-library></a>}</dd> + +<dt>description:</dt> +<dd>The declaration of the application. This element contains subelements +that declare each of the application's components and has attributes +that can affect all the components. Many of these attributes (such as +{@code icon}, {@code label}, {@code permission}, {@code process}, +{@code taskAffinity}, and {@code allowTaskReparenting}) set default values +for corresponding attributes of the component elements. Others (such as +{@code debuggable}, {@code enabled}, {@code description}, and +{@code allowClearUserData}) set values for the application as a whole and +cannot be overridden by the components.</dd> + +<dt>attributes</dt> +<dd><dl class="attr"> +<dt>{@code android:allowClearUserData}</dt> +<dd>Whether or not users are given the option to remove user data — +"{@code true}" if they are, and "{@code false}" if not. If the value is +"{@code true}", as it is by default, the application manager includes an +option that allows users to clear the data.</dd> + +<dt><a name="app_reparent"></a>{@code android:allowTaskReparenting}</dt> +<dd>Whether or not activities that the application defines can move from +the task that started them to the task they have an affinity for when that task +is next brought to the front — "{@code true}" if they can move, and +"{@code false}" if they must remain with the task where they started. +The default value is "{@code false}". + +<p> +The {@code <a href="#actv"><activity></a>} element has its own +{@code <a href="#act_reparent">allowTaskReparenting</a>} attribute +that can override the value set here. See that attribute for more +information. +</p></dd> + +<dt>{@code android:debuggable}</dt> +<dd>Whether or not the application can be debugged, even when running +on a device in user mode — "{@code true}" if it can be, and "{@code false}" +if not. The default value is "{@code false}".</dd> + +<dt>{@code android:description}</dt> +<dd>User-readable text about the application, longer and more descriptive than the application label. The value must be set as a reference to a string resource. Unlike the label, it cannot be a raw string. There is no default value.</dd> + +<dt><a name="app_enabled"></a>{@code android:enabled}</dt> +<dd>Whether or not the Android system can instantiate components of +the application — "{@code true}" if it can, and "{@code false}" +if not. If the value is "{@code true}", each component's +{@code enabled} attribute determines whether that component is enabled +or not. If the value is "{@code false}", it overrides the +component-specific values; all components are disabled. + +<p> +The default value is "{@code true}". +</p></dd> + +<dt>{@code android:hasCode}</dt> +<dd>Whether or not the application contains any code — "{@code true}" +if it does, and "{@code false}" if not. When the value is "{@code false}", +the system does not try to load any application code when launching components. +The default value is "{@code true}". + +<p> +An application would not have any code of its own only if it's using nothing +but built-in component classes, such as an activity that uses the {@link +android.app.AliasActivity} class, a rare occurrence. + +<dt><a name="app_icon"></a>{@code android:icon}</dt> +<dd>An icon for the application as whole, and the default icon for +each of the application's components. See the individual +{@code icon} attributes for +{@code <a href="#actv"><activity></a>}, +{@code <a href="#alias"><activity-alias></a>}, +{@code <a href="#srvc"><service></a>}, +{@code <a href="#rcvr"><receiver></a>}, and +{@code <a href="#pvdr"><provider></a>} elements. + +<p> +This attribute must be set as a reference to a drawable resource containing +the image definition. There is no default icon. +</p></dd> + +<dt><a name="app_label"></a>{@code android:label}</dt> +<dd>A user-readable label for the application as a whole, and a default +label for each of the application's components. See the individual +{@code label} attributes for +{@code <a href="#actv"><activity></a>}, +{@code <a href="#alias"><activity-alias></a>}, +{@code <a href="#srvc"><service></a>}, +{@code <a href="#rcvr"><receiver></a>}, and +{@code <a href="#pvdr"><provider></a>} elements. + +<p> +The label should be set as a reference to a string resource, so that +it can be localized like other strings in the user interface. +However, as a convenience while you're developing the application, +it can also be set as a raw string. +</p></dd> + +<dt>{@code android:manageSpaceActivity}</dt> +<dd>The fully qualified name of an Activity subclass that the system +can launch to let users manage the memory occupied by the application +on the device. The activity should also be declared with an +{@code <a href="#actv"><activity></a>} element. +</dd> + +<dt>{@code android:name}</dt> +<dd>The fully qualified name of an {@link android.app.Application} +subclass implemented for the application. When the application process +is started, this class is instantiated before any of the application's +components. + +<p> +The subclass is optional; most applications won't need one. +In the absence of a subclass, Android uses an instance of the base +Application class. +</p></dd> + +<dt><a name="app_prmsn"></a>{@code android:permission}</dt> +<dd>The name of a permission that clients must have in order to interact +with the application. This attribute is a convenient way to set a +permission that applies to all of the application's components. It can +be overwritten by setting the {@code permission} attributes of individual +components. + +<p> +For more information on permissions, see the <a href="#sectperm">Permissions</a> +section earlier in this document and a separate document, +<a href="{@docRoot}guide/topics/security/security.html">Security and +Permissions</a>. +</p></dd> + +<dt>{@code android:persistent}</dt> +<dd>Whether or not the application should remain running at all times — +"{@code true}" if it should, and "{@code false}" if not. The default value +is "{@code false}". Applications should not normally set this flag; +persistence mode is intended only for certain system applications.</dd> + +<dt><a name="app_proc"></a>{@code android:process}</dt> +<dd>The name of a process where all components of the application should run. +Each component can override this default by setting its own {@code process} +attribute. + +<p> +By default, Android creates a process for an application when the first +of its components needs to run. All components then run in that process. +The name of the default process matches the package name set by the +{@code <a href="#manf"><manifest></a>} element. +</p> + +<p>By setting this attribute to a process name that's shared with another +application, you can arrange for components of both applications to run in +the same process — but only if the two applications also share a +user ID and be signed with the same certificate. +</p> + +<p> +If the name assigned to this attribute begins with a colon (':'), a new +process, private to the application, is created when it's needed. +If the process name begins with a lowercase character, a global process +of that name is created. A global process can be shared with other +applications, reducing resource usage. +</p></dd> + +<dt><a href name="app_aff"></a>{@code android:taskAffinity}</dt> +<dd>An affinity name that applies to all activities within the application, +except for those that set a different affinity with their own {@code +<a href="#actv_aff">taskAffinity</a>} attributes. See that attribute +for more information. + +<p> +By default, all activities within an application share the same +affinity. The name of that affinity is the same as the package name +set by the {@code <a href="#manf"><manifest></a>} element. +</p></dd> + +<dt><a name="app_theme"></a>{@code android:theme}</dt> +<dd>A reference to a style resource defining a default theme for all +activities in the application. Individual activities can override +the default by setting their own {@code <a href="#actv_theme">theme</a>} +attributes; see that attribute for more information.</dd> + +</dl></dd> + +<dt>see also:</dt> +<dd>{@code <a href="#actv"><activity></a>} +<br/>{@code <a href="#srvc"><service></a>} +<br/>{@code <a href="#rcvr"><receiver></a>} +<br/>{@code <a href="#pvdr"><provider></a>}</dd> + +</dl> +<hr> + +<h3 id="catg"><category></h3> + +<dl class="xml"> +<dt>syntax:</dt> +<dd><pre class="stx"><category android:name="<i>string</i>" /></pre></dd> + +<dt>contained in:</dt> +<dd>{@code <a href="#ifilt"><intent-filter></a>}</dd> + +<dt>description:</dt> +<dd>Adds a category name to an intent filter. See +<a href="{@docRoot}guide/topics/intents/intents-filters.html">Intents and +Intent Filters</a> for details on intent filters and the role of category +specifications within a filter.</dd> + +<dt>attributes:</dt> +<dd><dl class="attr"> +<dt>{@code android:name}</dt> +<dd>The name of the category. Standard categories are defined in the +{@link android.content.Intent} class as {@code CATEGORY_<i>name</i>} +constants. The name assigned here can be derived from those constants +by prefixing "{@code android.intent.category.}" to the +{@code <i>name</i>} that follows {@code CATEGORY_}. For example, +the string value for {@code CATEGORY_LAUNCHER} is +"{@code android.intent.category.LAUNCHER}". + +<p> +Custom categories should use the package name as a prefix, to ensure +that they are unique. +</p></dd> +</dl></dd> + +<dt>see also:</dt> +<dd>{@code <a href="#actn"><action></a>} +<br/>{@code <a href="#data"><data></a>}</dd> + +</dl> +<hr> + +<h3 id="data"><data></h3> + +<dl class="xml"> +<dt>syntax:</dt> +<dd><pre class="stx"><data android:host="<i>string</i>" + android:mimeType="<i>string</i>" + android:path="<i>string</i>" + android:pathPattern="<i>string</i>" + android:pathPrefix="<i>string</i>" + android:port="<i>string</i>" + android:scheme="<i>string</i>" /></pre></dd> + + +<dt>contained in:</dt> +<dd>{@code <a href="#ifilt"><intent-filter></a>}</dd> + +<dt>description:</dt> +<dd>Adds a data specification to an intent filter. The specification can +be just a data type (the {@code <a href="#data_mime">mimeType</a>} attribute), +just a URI, or both a data type and a URI. A URI is specified by separate +attributes for each of its parts: + +<p style="margin-left: 2em">{@code scheme://host:port/path} <i>or</i> +{@code pathPrefix} <i>or</i> {@code pathPattern}</p> + +<p> +These attributes are optional, but also mutually dependent: +If a {@code <a href="#data_scheme">scheme</a>} is not specified for the +intent filter, all the other URI attributes are ignored. If a +{@code <a href="#data_host">host</a>} is not specified for the filer, +the {@code port} attribute and all the path attributes are ignored. +</p> + +<p> +All the {@code <data>} elements contained within the same +{@code <a href="#ifilt"><intent-filter></a>} element contribute to +the same filter. So, for example, the following filter specification, +</p> + +<pre><intent-filter . . . > + <data android:scheme="something" android:host="project.example.com" /> + . . . +</intent-filter></pre> + +<p>is equivalent to this one:</p> + +<pre><intent-filter . . . > + <data android:scheme="something" /> + <data android:host="project.example.com" /> + . . . +</intent-filter></pre> + +<p> +You can place any number of <data> elements inside an +{@code <a href="#ifilt"><intent-filter></a>} to give it multiple data +options. None of its attributes have default values. +</p> + +<p> +Information on how intent filters work, including the rules for how Intent objects +are matched against filters, can be found in another document, +<a href="{@docRoot}guide/topics/intents/intents-filters.html">Intents and +Intent Filters</a>. See also the <a href="#ifs">Intent Filters</a> section +earlier in this document. +</p></dd> + +<dt>attributes:</dt> +<dd><dl class="attr"> +<dt><a name="data_host"></a>{@code android:host}</dt> +<dd>The host part of a URI authority. This attribute is meaningless +unless a {@code <a href="#data_scheme">scheme</a>} attribute is also +specified for the filter. +</dd> + +<dt><a name="data_mime"></a>{@code android:mimeType}</dt> +<dd>A MIME media type, such as {@code image/jpeg} or {@code audio/mpeg4-generic}. +The subtype can be the asterisk wildcard ({@code *}) to indicate that any +subtype matches.</dd> + +<dt>{@code android:path} +<br/>{@code android:pathPrefix} +<br/>{@code android:pathPattern}</dt> +<dd>The path part of a URI. The {@code path} attribute specifies a complete +path that is matched against the complete path in an Intent object. The +{@code pathPrefix} attribute specifies a partial path that is matched against +only the initial part of the path in the Intent object. The {@code pathPattern} +attribute specifies a complete path that is matched against the complete path +in the Intent object, but it can contain the following wildcards: + +<ul> +<li>An asterisk ('{@code *}') matches a sequence of 0 to many occurrences of +the immediately preceding character.</li> + +<li><p>A period followed by an asterisk ("{@code .*}") matches any sequence of +0 to many characters.</p></li> +</ul> + +<p> +Because '{@code \}' is used as an escape character when the string is read +from XML (before it is parsed as a pattern), you will need to double-escape: +For example, a literal '{@code *}' would be written as "{@code \\*}" and a +literal '{@code \}' would be written as "{@code \\\\}". This is basically +the same as what you would need to write if constructing the string in Java code. +</p> + +<p> +For more information on these three types of patterns, see the descriptions of +{@link android.os.PatternMatcher#PATTERN_LITERAL}, +{@link android.os.PatternMatcher#PATTERN_PREFIX}, and +{@link android.os.PatternMatcher#PATTERN_SIMPLE_GLOB} in the +{@link android.os.PatternMatcher} class. +</p> + +<p>These attributes are meaningful only if the +{@code <a href="#data_scheme">scheme</a>} and +{@code <a href="#data_host">host</a>} +attributes are also specified for the filter. +</p></dd> + +<dt>{@code android:port}</dt> +<dd>The port part of a URI authority. This attribute is meaningful only +if the {@code <a href="#data_scheme">scheme</a>} and +{@code <a href="#data_host">host</a>} attributes are also specified for +the filter.</dd> + +<dt><a name="data_scheme"></a>{@code android:scheme}</dt> +<dd>The scheme part of a URI. This is the minimal essential attribute for +specifying a URI; at least one {@code scheme} attribute must be set +for the filter, or none of the other URI attributes are meaningful. + +<p> +A scheme is specified without the trailing colon (for example, +{@code http}, rather than {@code http:}). +</p> + +<p> +If the filter has a data type set (the {@code <a href="#data_mime">mimeType</a>} +attribute) but no scheme, the {@code content:} and {@code file:} schemes are +assumed. +</p></dd> +</dl></dd> + +<dt>see also:</dt> +<dd>{@code <a href="#actn"><action></a>} +<br/>{@code <a href="#catg"><category></a>}</dd> + +</dl> +<hr> + +<h3 id="grantp"><grant-uri-permission></h3> + +<dl class="xml"> +<dt>syntax:</dt> +<dd><pre class="stx"><grant-uri-permission android:path="<i>string</i>" + android:pathPattern="<i>string</i>" + android:pathPrefix="<i>string</i>" /></pre></dd> + +<dt>contained in:</dt> +<dd>{@code <a href="#pvdr"><provider></a>}</dd> + +<dt>description:</dt> +<dd>Specifies which data subsets of the parent content provider permission +can be granted for. Data subsets are indicated by the path part of a +{@code content:} URI. (The authority part of the URI identifies the +content provider.) +Granting permission is a way of enabling clients of the provider that don't +normally have permission to access its data to overcome that restriction on +a one-time basis. + +<p> +If a content provider's {@code <a href="#pvdr_gprmsn">grantUriPermissions</a>} +attribute is "{@code true}", permission can be granted for any the data under +the provider's purview. However, if that attribute is "{@code false}", permission +can be granted only to data subsets that are specified by this element. +A provider can contain any number of {@code <grant-uri-permission>} elements. +Each one can specify only one path (only one of the three possible attributes). +</p> + +<p> +For information on how permission is granted, see the +{@code <a href="#ifilt"><intent-filter></a>} element's +{@code <a href="#pvdr_gprmsn">grantUriPermissions</a>} attribute. +</p></dd> + +<dt>attributes:</dt> +<dd><dl class="attr"> +<dt>{@code android:path} +<br/>{@code android:pathPrefix} +<br/>{@code android:pathPattern}</dt> +<dd>A path identifying the data subset or subsets that permission can be +granted for. The {@code path} attribute specifies a complete path; +permission can be granted only to the particular data subset identified +by that path. +The {@code pathPrefix} attribute specifies the initial part of a path; +permission can be granted to all data subsets with paths that share that +initial part. +The {@code pathPattern} attribute specifies a complete path, but one +that can contain the following wildcards: + +<ul> +<li>An asterisk ('{@code *}') matches a sequence of 0 to many occurrences of +the immediately preceding character.</li> + +<li><p>A period followed by an asterisk ("{@code .*}") matches any sequence of +0 to many characters.</p></li> +</ul> + +<p> +Because '{@code \}' is used as an escape character when the string is read +from XML (before it is parsed as a pattern), you will need to double-escape: +For example, a literal '{@code *}' would be written as "{@code \\*}" and a +literal '{@code \}' would be written as "{@code \\\\}". This is basically +the same as what you would need to write if constructing the string in Java code. +</p> + +<p> +For more information on these types of patterns, see the descriptions of +{@link android.os.PatternMatcher#PATTERN_LITERAL}, +{@link android.os.PatternMatcher#PATTERN_PREFIX}, and +{@link android.os.PatternMatcher#PATTERN_SIMPLE_GLOB} in the +{@link android.os.PatternMatcher} class. +</p></dd> +</dl></dd> + +<dt>see also:</dt> +<dd>the {@code <a href="#pvdr_gprmsn">grantUriPermissions</a>} attribute +of the {@code <a href="#pvdr"><provider></a>} element</dd> + + +</dl> +<hr> + +<h3 id="instru"><instrumentation></h3> + +<dl class="xml"> +<dt>syntax:</dt> +<dd><pre class="stx"><instrumentation android:functionalTest=["true" | "false"] + android:handleProfiling=["true" | "false"] + android:icon="<i>drawable resource</i>" + android:label="<i>string resource</i>" + android:name="<i>string</i>" + android:targetPackage="<i>string</i>" /></pre></dd> + +<dt>contained in:</dt> +<dd>{@code <a href="#manf"><manifest></a>}</dd> + +<dt>description:</dt> +<dd>Declares an {@link android.app.Instrumentation} class that enables you +to monitor an application's interaction with the system. The Instrumentation +object is instantiated before any of the application's components.</dd> + +<dt>attributes:</dt> +<dd><dl class="attr"> +<dt>{@code android:functionalTest}</dt> +<dd>Whether or not the Instrumentation class should run as a functional test +— "{@code true}" if it should, and "{@code false}" if not. The +default value is "{@code false}".</dd> + +<dt>{@code android:handleProfiling}</dt> +<dd>Whether or not the Instrumentation object will turn profiling on and +off — "{@code true}" if it determines when profiling starts and +stops, and "{@code false}" if profiling continues the entire time it is +running. A value of "{@code true}" enables the object to target profiling +at a specific set of operations. The default value is "{@code false}".</dd> + +<dt>{@code android:icon}</dt> +<dd>An icon that represents the Instrumentation class. This attribute must +be set as a reference to a drawable resource.</dd> + +<dt>{@code android:label}</dt> +<dd>A user-readable label for the Instrumentation class. The label can +be set as a raw string or a reference to a string resource.</dd> + +<dt>{@code android:name}</dt> +<dd>The name of the {@link android.app.Instrumentation} subclass. +This should be a fully qualified class name (such as, +"{@code com.example.project.StringInstrumentation}"). However, as a shorthand, +if the first character of the name is a period, it is appended to the package +name specified in the {@code <a href="#manf"><manifest></a>} element. + +<p> +There is no default. The name must be specified. +</p></dd> + +<dt>{@code android:targetPackage}</dt> +<dd>The application that the Instrumentation object will run against. +An application is identified by the package name assigned in its manifest +file by the {@code <a href="#manf"><manifest></a>} element.</dd> + +</dl></dd> + +</dl> +<hr> + +<h3 id="ifilt"><intent-filter></h3> + +<dl class="xml"> +<dt>syntax:</dt> +<dd><pre class="stx"><intent-filter android:icon="<i>drawable resource</i>" + android:label="<i>string resource</i>" + android:priority="<i>integer</i>" > + . . . +</intent-filter></pre></dd> + +<dt>contained in:</dt> +<dd>{@code <a href="#actv"><activity></a>} +<br/>{@code <a href="#alias"><activity-alias></a>} +<br/>{@code <a href="#srvc"><service></a>} +<br/>{@code <a href="#rcvr"><receiver></a>}</dd> + +<dt>must contain:</dt> +<dd>{@code <a href="#actn"><action></a>}</dd> + +<dt>can contain:</dt> +<dd>{@code <a href="#catg"><category></a>} +<br/>{@code <a href="#data"><data></a>}</dd> + +<dt>description:</dt> +<dd>Specifies the types of intents that an activity, service, or broadcast +receiver can respond to. An intent filter declares the capabilities of its +parent component — what an activity or service can do and what types +of broadcasts a receiver can handle. It opens the component to receiving +intents of the advertised type, while filtering out those that are not +meaningful for the component. + +<p> +Most of the contents of the filter are described by its +{@code <a href="#actn"><action></a>}, +{@code <a href="#catg"><category></a>}, and +{@code <a href="#data"><data></a>} subelements. +</p> + +<p> +For a more detailed discussion of filters, see the separate +<a href="{@docRoot}guide/topics/intents/intents-filters.html">Intents +and Intent Filters</a> document, as well as the +<a href="#ifs">Intents Filters</a> section earlier in this document. +</p></dd> + +<dt>attributes:</dt> +<dd><dl class="attr"> +<dt><a name="ifilt_icon"></a>{@code android:icon}</dt> +<dd>An icon that represents the parent activity, service, or broadcast +receiver when that component is presented to the user as having the +capability described by the filter. + +<p> +This attribute must be set as a reference to a drawable resource +containing the image definition. The default value is the icon set +by the parent component's {@code icon} attribute. If the parent +does not specify an icon, the default is the icon set by the +{@code <a href="#app"><application></a>} element. +</p> + +<p> +For more on intent filter icons, see <a href="#iconlabel">Icons and Labels</a>, +earlier. +</p></dd> + +<dt>{@code android:label}</dt> +<dd>A user-readable label for the parent component. This label, rather than +the one set by the parent component, is used when the component is presented +to the user as having the capability described by the filter. + +<p> +The label should be set as a reference to a string resource, so that +it can be localized like other strings in the user interface. +However, as a convenience while you're developing the application, +it can also be set as a raw string. +</p> + +<p> +The default value is the label set by the parent component. If the +parent does not specify a label, the default is the label set by the +{@code <a href="#app"><application></a>} element's +{@code <a href="#app_label"> label</a>} attribute. +</p> + +<p> +For more on intent filter labels, see <a href="#iconlabel">Icons and Labels</a>, +earlier. +</p></dd> + +<dt>{@code android:priority}</dt> +<dd>The priority that should be given to the parent component with regard +to handling intents of the type described by the filter. This attribute has +meaning for both activities and broadcast receivers: + +<ul> +<li>It provides information about how able an activity is to respond to +an intent that matches the filter, relative to other activities that could +also respond to the intent. When an intent could be handled by multiple +activities with different priorities, Android will consider only those with +higher priority values as potential targets for the intent.</li> + +<li><p>It controls the order in which broadcast receivers are executed to +receive broadcast messages. Those with higher priority +values are called before those with lower values. (The order applies only +to synchronous messages; it's ignored for asynchronous messages.)</p></li> +</ul> + +<p> +Use this attribute only if you really need to impose a specific order in +which the broadcasts are received, or want to force Android to prefer +one activity over others. +</p> + +<p> +The value must be an integer, such as "{@code 100}". Higher numbers have a +higher priority. +</p></dd> + +</dl></dd> + +<dt>see also:</dt> +<dd>{@code <a href="#actn"><action></a>} +<br/>{@code <a href="#catg"><category></a>} +<br/>{@code <a href="#data"><data></a>}</dd> + +</dl> +<hr> + + +<h3 id="manf"><manifest></h3> + +<dl class="xml"> +<dt>syntax:</dt> +<dd><pre class="stx"><manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="<i>string</i>" + android:sharedUserId="<i>string</i>" + android:versionCode="<i>integer</i>" + android:versionName="<i>string</i>" > + . . . +</manifest></pre></dd> + +<p> +<dt>contained in:</dt> +<dd><i>none</i></dd> + +<p> +<p> +<dt>must contain:</dt> +<dd>{@code <a href="#app"><application></a>}</dd> + +<dt>can contain:</dt> +<dd>{@code <a href="#instru"><instrumentation></a>} +<br/>{@code <a href="#prmsn"><permission></a>} +<br/>{@code <a href="#pgroup"><permission-group></a>} +<br/>{@code <a href="#ptree"><permission-tree></a>} +<br/>{@code <a href="#usesp"><uses-permission></a>}</dd> + +<p> +<dt>description:</dt> +<dd>The root element of the AndroidManifest.xml file. It must +contain an {@code <a href="#app"><application></a>} element +and specify {@code xlmns:android} and {@code package} attributes.</dd> + +<dt>attributes:</dt> +<dd><dl class="attr"> +<dt>{@code xmlns:android}</dt> +<dd>Defines the Android namespace. This attribute should always be set +to "{@code http://schemas.android.com/apk/res/android}".</dd> + +<dt><a name="manf_package"></a>{@code package}</dt> +<dd>A full Java package name for the application. The name should +be unique. For example, applications published by Google could have +names in the form <code>com.google.app.<i>application_name</i></code>. + +<p> +The package name serves as a unique identifier for the application. +It's also the default name for the task affinity of components +(see the {@code <a href="#app_aff">taskAffinity</a>} attribute). +</p></dd> + +<dt>{@code android:sharedUserId}</dt> +<dd>The name of a Linux user ID that will be shared with other applications. +By default, Android assigns each application its own unique user ID. +However, if this attribute is set to the same value for two or more applications, +they will all share the same ID — provided that they are also signed +by the same certificate. Application with the same user ID can access each +other's data and, if desired, run in the same process.</dd> + +<dt>{@code android:versionCode}</dt> +<dd>An internal version number. This number is used only to determine whether +one version is more recent than another, with higher numbers indicating more +recent versions. This is not the version number shown to users; that number +is set by the {@code versionName} attribute. + +<p> +The value must be set as an integer, such as "100". You can define it however +you want, as long as each successive version has a higher number. For example, +it could be a build number. Or you could translate a version number in "x.y" +format to an integer by encoding the "x" and "y" separately in the lower and +upper 16 bits. Or you could simply increase the number by one each time a new +version is released. +</p></dd> + +<dt>{@code android:versionName}</dt> +<dd>The version number shown to users. This attribute can be set as a raw +string or as a reference to a string resource. The string has no other purpose +than to be displayed to users. The {@code versionCode} attribute holds +the significant version number used internally. +</dl></dd> + +<p> +<dt>see also:</dt> +<dd>{@code <a href="#app"><application></a>}</dd> + +</dl> +<hr> + +<h3 id="meta"><meta-data></h3> + +<dl class="xml"> +<dt>syntax:</dt> +<dd><pre class="stx"><meta-data android:name="<i>string</i>" + android:resource="<i>resource specification</i>" + android:value="<i>string</i>" /></pre></dd> + +<dt>contained in:</dt> +<dd>{@code <a href="#actv"><activity></a>} +<br/>{@code <a href="#alias"><activity-alias></a>} +<br/>{@code <a href="#srvc"><service></a>} +<br/>{@code <a href="#rcvr"><receiver></a>}</dd> + +<dt>description:</dt> +<dd>A name-value pair for an item of additional, arbitrary data that can +be supplied to the parent component. A component element can contain any +number of {@code <meta-data>} subelements. The values from all of +them are collected in a single {@link android.os.Bundle} object and made +available to the component as the +{@link android.content.pm.PackageItemInfo#metaData +PackageItemInfo.metaData} field. + +<p> +Ordinary values are specified through the {@code <a href="#meta_value">value</a>} +attribute. However, to assign a resource ID as the value, use the +{@code <a href="#meta_resource">resource</a>} attribute instead. For example, +the following code assigns whatever value is stored in the {@code @string/kangaroo} +resource to the "{@code zoo}" name: +</p> + +<pre><meta-data android:name="zoo" android:value="@string/kangaroo" /></pre> + +<p> +On the other hand, using the {@code resource} attribute would assign "{@code zoo}" +the numeric ID of the resource, not the value stored in the resource: +</p> + +<pre><meta-data android:name="zoo" android:resource="@string/kangaroo" /></pre> + +<p> +It is highly recommended that you avoid supplying related data as +multiple separate {@code <meta-data>} entries. Instead, if you +have complex data to associate with a component, store it as a resource and +use the {@code resource} attribute to inform the component of its ID. +</p></dd> + +<dt>attributes:</dt> +<dd><dl class="attr"> +<dt>{@code android:name}</dt> +<dd>A unique name for the item. To ensure that the name is unique, use a +Java-style naming convention — for example, +"{@code com.example.project.activity.fred}".</dd> + +<dt>{@code android:resource}</dt> +<dd>A reference to a resource. The ID of the resource is the value assigned +to the item. The ID can be retrieved from the meta-data Bundle by the +{@link android.os.Bundle#getInt Bundle.getInt()} method.</dd> + +<dt>{@code android:value}</dt> +<dd>The value assigned to the item. The data types that can be assigned as values and the Bundle methods that components use to retrieve those values are listed in the following table: + +<table> +<tr> + <th>Type</th> + <th>Bundle method</th> +</tr><tr> + <td>String value, using double backslashes ({@code \\}) to escape characters + — such as "{@code \\n}" and "{@code \\uxxxxx}" for a Unicode character.</td> + <td>{@link android.os.Bundle#getString(String) getString()}</td> +</tr><tr> + <td>Integer value, such as "{@code 100}"</td> + <td>{@link android.os.Bundle#getInt(String) getInt()}</td> +</tr><tr> + <td>Boolean value, either "{@code true}" or "{@code false}"</td> + <td>{@link android.os.Bundle#getBoolean(String) getBoolean()}</td> +</tr><tr> + <td>Color value, in the form "{@code #rgb}", "{@code #argb}", + "{@code #rrggbb}", or "{@code #aarrggbb}"</td> + <td>{@link android.os.Bundle#getString(String) getString()}</td> +</tr><tr> + <td>Float value, such as "{@code 1.23}"</td> + <td>{@link android.os.Bundle#getFloat(String) getFloat()}</td> +</tr> +</table> +</dd> +</dl></dd> + +</dl> +<hr> + +<h3 id="prmsn"><permission></h3> + +<dl class="xml"> +<dt>syntax:</dt></dt> +<dd><pre class="stx"><permission android:description="<i>string resource</i>" + android:icon="<i>drawable resource</i>" + android:label="<i>string resource</i>" + android:name="<i>string</i>" + android:permissionGroup="<i>string</i>" + android:protectionLevel=["normal" | "dangerous" | + "signature" | "signatureOrSystem"] /></pre></dd> + +<dt>contained in:</dt> +<dd>{@code <a href="#manf"><manifest></a>}</dd> + +<dt>description:</dt> +<dd>Declares a security permission that can be used to limit access +to specific components or features of this or other applications. +See the <a href="#perms">Permissions</a>, earlier in this document, +and the <a href="{@docRoot}guide/topics/security/security.html">Security Model</a> +document for more information on how permissions work.</dd> + +<dt>attributes:</dt> +<dd><dl class="attr"> +<dt>{@code android:description}</dt> +<dd>A user-readable description of the permission, longer and more +informative than the label. It may be displayed to explain the +permission to the user — for example, when the user is asked +whether to grant the permission to another application. + +<p> +This attribute must be set as a reference to a string resource; +unlike the {@code label} attribute, it cannot be a raw string. +</p></dd> + +<dt>{@code android:icon}</dt> +<dd>A reference to a drawable resource for an icon that represents the +permission.</dd> + +<dt>{@code android:label}</dt> +<dd>A name for the permission, one that can be displayed to users. + +<p> +As a convenience, the label can be directly set +as a raw string while you're developing the application. However, +when the application is ready to be published, it should be set as a +reference to a string resource, so that it can be localized like other +strings in the user interface. +</p></dd> + +<dt>{@code android:name}</dt> +<dd>The name of the permission. This is the name that will be used in +code to refer to the permission — for example, in a +{@code <a href="#usesp"><uses-permission></a>} element and the +{@code permission} attributes of application components.</dd> + +<p> +The name must be unique, so it should use Java-style scoping — +for example, "{@code com.example.project.PERMITTED_ACTION}". +</p></dd> + +<dt>{@code android:permissionGroup}</dt> +<dd>Assigns this permission to a group. The value of this attribute is +the name of the group, which must be declared with the +{@code <a href="#pgroup"><permission-group></a>} element in this +or another application. If this attribute is not set, the permission +does not belong to a group.</dd> + +<dt>{@code android:protectionLevel}</dt> +<dd>Characterizes the potential risk implied in the permission and +indicates the procedure the system should follow when determining +whether or not to grant the permission to an application requesting it. +The value can be set to one of the following strings: + +<table> +<tr> + <th>Value</th> + <th>Meaning</th> +</tr><tr> + <td>"{@code normal}"</td> + <td>The default value. A lower-risk permission that gives requesting + applications access to isolated application-level features, with + minimal risk to other applications, the system, or the user. + The system automatically grants this type + of permission to a requesting application at installation, without + asking for the user's explicit approval (though the user always + has the option to review these permissions before installing). +</tr><tr> + <td>"{@code dangerous}"</td> + <td>A higher-risk permission that would give a requesting application + access to private user data or control over the device that can + negatively impact the user. Because this type of permission + introduces potential risk, the system may not automatically + grant it to the requesting application. For example, any dangerous + permissions requested by an application may be displayed to the + user and require confirmation before proceeding, or some other + approach may be taken to avoid the user automatically allowing + the use of such facilities. +</tr><tr> + <td>"{@code signature}"</td> + <td>A permission that the system grants only if the requesting + application is signed with the same certificate as the application + that declared the permission. If the certificates match, the system + automatically grants the permission without notifying the user or + asking for the user's explicit approval. +</tr><tr> + <td>"{@code signatureOrSystem}"</td> + <td>A permission that the system grants only to applications that are + in the Android system image <em>or</em> that are signed with the same + certificates as those in the system image. Please avoid using this + option, as the {@code signature} protection level should be sufficient + for most needs and works regardless of exactly where applications are + installed. The "{@code signatureOrSystem}" + permission is used for certain special situations where multiple + vendors have applications built into a system image and need + to share specific features explicitly because they are being built + together. +</tr> +</table> +</dd> +</dl></dd> + +<dt>see also:</dt> +<dd>{@code <a href="#usesp"><uses-permission></a>} +<br/>{@code <a href="#ptree"><permission-tree></a>} +<br/>{@code <a href="#pgroup"><permission-group></a>}</dd> +</dd> + +</dl> +<hr> + +<h3 id="pgroup"><permission-group></h3> + +<dl class="xml"> +<dt>syntax:</dt> +<dd><pre class="stx"><permission-group android:description="<i>string resource</i>" + android:icon="<i>drawable resource</i>" + android:label="<i>string resource</i>" + android:name="<i>string</i>" /></pre></dd> + +<dt>contained in:</dt> +<dd>{@code <a href="#manf"><manifest></a>}</dd> + +<dt>description:</dt> +<dd>Declares a name for a logical grouping of related permissions. Individual +permission join the group through the {@code permissionGroup} attribute of the +{@code <a href="#prmsn"><permission></a>} element. Members of a group are +presented together in the user interface. + +<p> +Note that this element does not declare a permission itself, only a category in +which permissions can be placed. See the +{@code <a href="#prmsn"><permission></a>} element for element for information +on declaring permissions and assigning them to groups. +</p></dd> + +<dt>attributes:</dt> +<dd><dl class="attr"> +<dt>{@code android:description}</dt> +<dd>User-readable text that describes the group. The text should be +longer and more explanatory than the label. This attribute must be +set as a reference to a string resource. Unlike the {@code label} +attribute, it cannot be a raw string.</dd> + +<dt>{@code android:icon}</dt> +<dd>An icon representing the permission. This attribute must be set +as a reference to a drawable resource containing the image definition.</dd> + +<dt>{@code android:label}</dt> +<dd>A user-readable name for the group. As a convenience, the label can +be directly set as a raw string while you're developing the application. +However, when the application is ready to be published, it should be set +as a reference to a string resource, so that it can be localized like other +strings in the user interface.</dd> + +<dt>{@code android:name}</dt> +<dd>The name of the group. This is the name that can be assigned to a +{@code <a href="#prmsn"><permission></a>} element's +{@code permissionGroup} attribute.</dd> +</dl></dd> + +<dt>see also:</dt> +<dd>{@code <a href="#prmsn"><permission></a>} +<br/>{@code <a href="#ptree"><permission-tree></a>} +<br/>{@code <a href="#usesp"><uses-permission></a>}</dd> + +</dl> +<hr> + +<h3 id="ptree"><permission-tree></h3> + +<dl class="xml"> +<dt>syntax:</dt> +<dd><pre class="stx"><permission-tree android:icon="<i>drawable resource</i>" + android:label="<i>string resource</i>" ] + android:name="<i>string</i>" /></pre></dd> + +<dt>contained in:</dt> +<dd>{@code <a href="#manf"><manifest></a>}</dd> + +<dt>description:</dt> +<dd>Declares the base name for a tree of permissions. The application takes +ownership of all names within the tree. It can dynamically add new permissions +to the tree by calling <code>{@link android.content.pm.PackageManager#addPermission PackageManager.addPermission()}</code>. Names within the tree are separated by +periods ('{@code .}'). For example, if the base name is +{@code com.example.project.taxes}, permissions like the following might be +added: + +<p style="margin-left: 2em">{@code com.example.project.taxes.CALCULATE} +<br/>{@code com.example.project.taxes.deductions.MAKE_SOME_UP} +<br/>{@code com.example.project.taxes.deductions.EXAGGERATE}</p> + +<p> +Note that this element does not declare a permission itself, only a +namespace in which further permissions can be placed. +See the {@code <a href="#prmsn"><permission></a>} element for +information on declaring permissions. + +<dt>attributes:</dt> +<dd><dl class="attr"> +<dt>{@code android:icon}</dt> +<dd>An icon representing all the permissions in the tree. This attribute +must be set as a reference to a drawable resource containing the image +definition.</dd> + +<dt>{@code android:label}</dt> +<dd>A user-readable name for the group. As a convenience, the label can +be directly set as a raw string for quick and dirty programming. However, +when the application is ready to be published, it should be set as a +reference to a string resource, so that it can be localized like other +strings in the user interface.</dd> + +<dt>{@code android:name}</dt> +<dd>The name that's at the base of the permission tree. It serves as +a prefix to all permission names in the tree. Java-style scoping should +be used to ensure that the name is unique. The name must have more than +two period-separated seqments in its path — for example, +{@code com.example.base} is OK, but {@code com.example} is not.</dd> + +</dl></dd> + +<p> +<dt>see also:</dt> +<dd>{@code <a href="#prmsn"><permission></a>} +<br/>{@code <a href="#pgroup"><permission-group></a>} +<br/>{@code <a href="#usesp"><uses-permission></a>} +</dd> -<dl> - <dt>{@link android.R.styleable#AndroidManifest <manifest>}</dt> - <dd>The root node of the file, describing the complete contents of - the package. Under it you can place: - <dl> - <dt>{@link android.R.styleable#AndroidManifestUsesPermission <uses-permission>}</dt> - <dd>Requests a security permission that your package must be granted in - order for it to operate correctly. See the - <a href="{@docRoot}devel/security.html">Security Model</a> - document for more information on permissions. A manifest can - contain zero or more of these elements.</dd> - <dt>{@link android.R.styleable#AndroidManifestPermission <permission>}</dt> - <dd>Declares a security permission that can be used to restrict which - applications can access components or features in your (or - another) package. See the - <a href="{@docRoot}devel/security.html">Security Model</a> - document for more information on permissions. A manifest can - contain zero or more of these elements.</dd> - <dt>{@link android.R.styleable#AndroidManifestInstrumentation <instrumentation>}</dt> - <dd>Declares the code of an instrumentation component that is available - to test the functionality of this <em>or another</em> package. - See {@link android.app.Instrumentation} for more details. A manifest can - contain zero or more of these elements.</dd> - <dt>{@link android.R.styleable#AndroidManifestApplication <application>}</dt> - <dd>Root element containing declarations of the application-level - components contained in the package. This element can also - include global and/or default attributes for the application, - such as a label, icon, theme, required permission, etc. A manifest - can contain zero or one of these elements (more than one application - tag is not allowed). Under it you can place zero or more of - each of the following component declarations: - <dl> - <dt>{@link android.R.styleable#AndroidManifestActivity <activity>}</dt> - <dd>An {@link android.app.Activity} is the primary facility for - an application to interact with the user. The initial screen - the user sees when launching an application is an activity, - and most other screens they use will be implemented as - separate activities declared with additional activity tags. - - <p><em><strong>Note:</strong></em> Every - Activity must have an <activity> tag in the manifest whether it is exposed - to the world or intended for use only within its own package. If an Activity - has no matching tag in the manifest, you won't be able to launch it. - - <p>Optionally, to support late runtime lookup of your - activity, you can include one or more <intent-filter> - elements to describe the actions the activity supports. - <dl> - <dt><a name="intent-filter"> - {@link android.R.styleable#AndroidManifestIntentFilter <intent-filter>}</a></dt> - <dd>Declares a specific set of {@link android.content.Intent} values - that a component supports, in the form of an - {@link android.content.IntentFilter}. In addition to the - various kinds of values - that can be specified under this element, attributes - can be given here to supply a unique label, icon, and - other information for the action being described. - <dl> - <dt>{@link android.R.styleable#AndroidManifestAction <action>}</dt> - <dd>An {@link android.content.IntentFilter#addAction Intent action} - that the component supports.</dd> - <dt>{@link android.R.styleable#AndroidManifestCategory <category>}</dt> - <dd>An {@link android.content.IntentFilter#addCategory Intent category} - that the component supports.</dd> - <dt>{@link android.R.styleable#AndroidManifestData <data>}</dt> - <dd>An {@link android.content.IntentFilter#addDataType Intent data MIME type}, - {@link android.content.IntentFilter#addDataScheme Intent data URI scheme}, - {@link android.content.IntentFilter#addDataAuthority Intent data URI authority}, or - {@link android.content.IntentFilter#addDataPath Intent data URI path} - that the component supports.</dd> - </dl> - </dl> - - <p>You can also optionally associate one or more pieces of meta-data - with your activity that other clients can retrieve to find - additional arbitrary information about it:</p> - <dl> - <dt><a name="meta-data"> - {@link android.R.styleable#AndroidManifestMetaData <meta-data>}</a></dt> - <dd>Adds a new piece of meta data to the activity, which clients - can retrieve through - {@link android.content.pm.ComponentInfo#metaData - ComponentInfo.metaData}. - </dl> - <dt>{@link android.R.styleable#AndroidManifestReceiver <receiver>}</dt> - <dd>An {@link android.content.BroadcastReceiver} allows an application - to be told about changes to data or actions that happen, - even if it is not currently running. As with the activity - tag, you can optionally include one or more <intent-filter> - elements that the receiver supports or <meta-data> values; - see the activity's - <a href="#intent-filter"><intent-filter></a> and - <a href="#meta-data"><meta-data></a> descriptions - for more information.</dd> - <dt>{@link android.R.styleable#AndroidManifestService <service>}</dt> - <dd>A {@link android.app.Service} is a component that can run in - the background for an arbitrary amount of time. As with the activity - tag, you can optionally include one or more <intent-filter> - elements that the service supports or <meta-data> values; - see the activity's - <a href="#intent-filter"><intent-filter></a> and - <a href="#meta-data"><meta-data></a> descriptions - for more information.</dd> - <dt>{@link android.R.styleable#AndroidManifestProvider <provider>}</dt> - <dd>A {@link android.content.ContentProvider} is a component that - manages persistent data and publishes it for access by other - applications. You can also optionally attach one or more - <meta-data> values, as described in the activity's - <a href="#meta-data"><meta-data></a> description.</dd> - </dl> - </dl> </dl> +<hr> + +<h3 id="pvdr"><provider></h3> + +<dl class="xml"> +<dt>syntax:</dt> +<dd><pre class="stx"><provider android:authorities="<i>list</i>" + android:enabled=["true" | "false"] + android:exported=["true" | "false"] + android:grantUriPermissions=["true" | "false"] + android:icon="<i>drawable resource</i>" + android:initOrder="<i>integer</i>" + android:label="<i>string resource</i>" + android:multiprocess=["true" | "false"] + android:name="<i>string</i>" + android:permission="<i>string</i>" + android:process="<i>string</i>" + android:readPermission="<i>string</i>" + android:syncable=["true" | "false"] + android:writePermission="<i>string</i>" > + . . . +</provider></pre></dd> + +<dt>contained in:</dt> +<dd>{@code <a href="#app"><application></a>}</dd> + +<dt>can contain:</dt> +<dd>{@code <a href="#meta"><meta-data></a>} +<br/>{@code <a href="#grantp"><grant-uri-permission></a>}</dd> + +<dt>description:</dt> +<dd>Declares a content provider — a subclass of +{@link android.content.ContentProvider} — that supplies structured +access to data managed by the application. All content providers that +are part of the application must be represented by {@code <provider>} +elements in the manifest file. The system cannot see, and therefore will +not run, any that are not declared. (You need to declare only +those content providers that you develop as part of your application, +not those developed by others that your application uses.) + +<p> +The Android system identifies content providers by the authority part + of a {@code content:} URI. For example, suppose that the following URI +is passed to <code>{@link android.content.ContentResolver#query +ContentResolver.query()}</code>: + +<p style="margin-left: 2em">{@code content://com.example.project.healthcareprovider/nurses/rn}</p> + +<p> +The {@code content:} scheme identifies the data as belonging to a content +provider and the authority ({@code com.example.project.healthcareprovider}) +identifies the particular provider. The authority therefore must be unique. +Typically, as in this example, it's the fully qualified name of a +ContentProvider subclass. The path part of a URI may be used by a content +provider to identify particular data subsets, but those paths are not +declared in the manifest. +</p> + +<p> +For information on using and developing content providers, see a separate document, +<a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>. +</p></dd> + +<dt>attributes:</dt> +<dd><dl class="attr"> +<dt>{@code android:authorities}</dt> +<dd>A list of one or more URI authorities that identify data under the purview +of the content provider. +Multiple authorities are listed by separating their names with a semicolon. +To avoid conflicts, authority names should use a Java-style naming convention +(such as {@code com.example.provider.cartoonprovider}). Typically, it's the name +of the ContentProvider subclass. + +<p> +There is no default. At least one authority must be specified. +</p></dd> + +<dt>{@code android:enabled}</dt> +<dd>Whether or not the content provider can be instantiated by the system — +"{@code true}" if it can be, and "{@code false}" if not. The default value +is "{@code true}". + +<p> +The {@code <a href="#app"><application></a>} element has its own +{@code <a href="#app_enabled">enabled</a>} attribute that applies to all +application components, including content providers. The +{@code <a href="#app"><application></a>} and {@code <provider>} +attributes must both be "{@code true}" (as they both +are by default) for the content provider to be enabled. If either is +"{@code false}", the provider is disabled; it cannot be instantiated. +</p></dd> + +<dt>{@code android:exported}</dt> +<dd>Whether or not the content provider can be used by components of other +applications — "{@code true}" if it can be, and "{@code false}" if not. +If "{@code false}", the provider is available only to components of the +same application or applications with the same user ID. The default value +is "{@code true}". + +<p> +You can export a content provider but still limit access to it with the +{@code <a href="#pvdr_prmsn">permission</a>} attribute. +</p></dd> + +<dt><a name="grantp_gprmns"></a>{@code android:grantUriPermissions}</dt> +<dd>Whether or not those who ordinarily would not have permission to +access the content provider's data can be granted permission to do so, +temporarily overcoming the restriction imposed by the +{@code <a href="#pvdr_rprmsn">readPermission</a>}, +{@code <a href="#pvdr_wprmsn">writePermission</a>}, and +{@code <a href="#pvdr_prmsn">permission</a>} attributes +— +"{@code true}" if permission can be granted, and "{@ code false}" if not. +If "{@code true}", permission can be granted to any of the content +provider's data. If "{@code false}", permission can be granted only +to the data subsets listed in +{@code <a href="#grantp"><grant-uri-permission></a>} subelements, +if any. The default value is "{@code false}". + +<p> +Granting permission is a way of giving an application component one-time +access to data protected by a permission. For example, when an e-mail +message contains an attachment, the mail application may call upon the +appropriate viewer to open it, even though the viewer doesn't have general +permission to look at all the content provider's data. +</p> + +<p> +In such cases, permission is granted by +<code>{@link android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION}</code> +and <code>{@link android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION}</code> +flags in the Intent object that activates the component. For example, the +mail application might put {@code FLAG_GRANT_READ_URI_PERMISSION} in the +Intent passed to {@code Context.startActivity()}. The permission is specific +to the URI in the Intent. +</p> + +<p> +If you enable this feature, either by setting this attribute to "{@code true}" +or by defining {@code <a href="#grantp"><grant-uri-permission></a>} +subelements, you must call +<code>{@link android.content.Context#revokeUriPermission +Context.revokeUriPermission()}</code> when a covered URI is deleted from +the provider. +</p> + +<p> +See also the {@code <a href="#grantp"><grant-uri-permission></a>} +element. +</p></dd> + +<dt><a name="pvdr_icon"></a>{@code android:icon}</dt> +<dd>An icon representing the content provider. +This attribute must be set as a reference to a drawable resource containing +the image definition. If it is not set, the icon specified for the application +as a whole is used instead (see the {@code <a href="#app"><application></a>} +element's {@code <a href="#app_icon">icon</a>} attribute).</dd> + +<dt>{@code android:initOrder}</dt> +<dd>The order in which the content provider should be instantiated, +relative to other content providers hosted by the same process. +When there are dependencies among content providers, setting this +attribute for each of them ensures that they are created in the order +required by those dependencies. The value is a simple integer, +with higher numbers being initialized first.</dd> + +<dt>{@code android:label}</dt> +<dd>A user-readable label for the content provided. +If this attribute is not set, the label set for the application as a whole is +used instead (see the {@code <a href="#app"><application></a>} element's +{@code <a href="#app_label">label</a>} attribute). + +<p> +The label should be set as a reference to a string resource, so that +it can be localized like other strings in the user interface. +However, as a convenience while you're developing the application, +it can also be set as a raw string. +</p></dd> + +<dt>{@code android:multiprocess}</dt> +<dd>Whether or not an instance of the content provider can be created in +every client process — "{@code true}" if instances can run in multiple +processes, and "{@code false}" if not. The default value is "{@code false}". + +<p> +Normally, a content provider is instantiated in the process of the +application that defined it. However, if this flag is set to "{@code true}", +the system can create an instance in every process where there's a client +that wants to interact withit, thus avoiding the overhead of interprocess +communication. +</p></dd> + +<dt>{@code android:name}</dt> +<dd>The name of the class that implements the content provider, a subclass of +{@link android.content.ContentProvider}. This should be a fully qualified +class name (such as, "{@code com.example.project.TransportationProvider}"). +However, as a shorthand, if the first character of the name is a period, +it is appended to the package name specified in the +{@code <a href="#manf"><manifest></a>} element. + +<p> +There is no default. The name must be specified. +</p></dd> + + +<dt>{@code android:permission}</dt> +<dd>The name of a permission that clients must have to read or write the +content provider's data. This attribute is a convenient way of setting a +single permission for both reading and writing. However, the +{@code <a href="#pvdr_rprmsn">readPermission</a>} and +{@code <a href="#pvdr_wprmsn">writePermission</a>} attributes take precedence +over this one. If the {@code <a href="#pvdr_rprmsn">readPermission</a>} +attribute is also set, it controls access for querying the content provider. +And if the {@code <a href="#pvdr_wprmsn">writePermission</a>} attribute is set, +it controls access for modifying the provider's data. + +<p> +For more information on permissions, see the <a href="#sectperm">Permissions</a> +section earlier in this document and a separate document, +<a href="{@docRoot}guide/topics/security/security.html">Security and +Permissions</a>. +</p></dd> + +<dt>{@code android:process}</dt> +<dd>The name of the process in which the content provider should run. Normally, +all components of an application run in the default process created for the +application. It has the same name as the application package. The {@code <a href="#app"><application></a>} element's +{@code <a href="#app_proc">process</a>} attribute can set a different +default for all components. But each component can override the default +with its own {@code process} attribute, allowing you to spread your +application across multiple processes. + +<p> +If the name assigned to this attribute begins with a colon (':'), a new +process, private to the application, is created when it's needed and +the activity runs in that process. +If the process name begins with a lowercase character, the activity will run +in a global process of that name, provided that it has permission to do so. +This allows components in different applications to share a process, reducing +resource usage. +</p></dd> + +<dt>{@code android:readPermission}</dt> +<dd>A permission that clients must have to query the content provider. +See also the {@code <a href="#pvdr_prmsn">permission</a>} and +{@code <a href="#pvdr_wprmsn">writePermission</a>} attributes.</dd> + +<dt>{@code android:syncable}</dt> +<dd>Whether or not the data under the content provider's control +is to be synchronized with data on a server — "{@code true}" +if it is to be synchronized, and "{@ code false}" if not.</dd> + +<dt>{@code android:writePermission}</dt> +<dd>A permission that clients must have to make changes to the data +controlled by the content provider. +See also the {@code <a href="#pvdr_prmsn">permission</a>} and +{@code <a href="#pvdr_rprmsn">readPermission</a>} attributes.</dd> + +</dl></dd> + +<p> +<dt>see also:</dt> +<dd><a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a></dd> + +</dl> +<hr> + +<h3 id="rcvr"><receiver></h3> + +<dl class="xml"> +<dt>syntax:</dt> +<dd><pre class="stx"><receiver android:enabled=["true" | "false"] + android:exported=["true" | "false"] + android:icon="<i>drawable resource</i>" + android:label="<i>string resource</i>" + android:name="<i>string</i>" + android:permission="<i>string</i>" + android:process="<i>string</i>" > + . . . +</receiver></pre></dd> + +<dt>contained in:</dt> +<dd>{@code <a href="#app"><application></a>}</dd> + +<dt>can contain:</dt> +<dd>{@code <a href="#ifilt"><intent-filer></a>} +<br/>{@code <a href="#meta"><meta-data></a>}</dd> + +<dt>description:</dt> +<dd>Declares a broadcast receiver (a {@link android.content.BroadcastReceiver} +subclass) as one of the application's components. Broadcast receivers enable +applications to receive intents that are broadcast by the system or by other +applications, even when other components of the application are not running. + +<p> +There are two ways to make a broadcast receiver known to the system: One is +declare it in the manifest file with this element. The other is to create +the receiver dynamically in code and register it with the <code>{@link +android.content.Context#registerReceiver Context.registerReceiver()}</code> +method. See the {@link android.content.BroadcastReceiver} class description +for more on dynamically created receivers. +</p></dd> + +<dt>attributes:</dt> +<dd><dl class="attr"> +<dt>{@code android:enabled}</dt> +<dd>Whether or not the broadcast receiver can be instantiated by the system — +"{@code true}" if it can be, and "{@code false}" if not. The default value +is "{@code true}". + +<p> +The {@code <a href="#app"><application></a>} element has its own +{@code <a href="#app_enabled">enabled</a>} attribute that applies to all +application components, including broadcast receivers. The +{@code <a href="#app"><application></a>} and +{@code <receiver>} attributes must both be "{@code true}" for +the broadcast receiver to be enabled. If either is "{@code false}", it is +disabled; it cannot be instantiated. +</p></dd> + +<dt>{@code android:exported}</dt> +<dd>Whether or not the broadcast receiver can receive messages from sources +outside its application — "{@code true}" if it can, and "{@code false}" +if not. If "{@code false}", the only messages the broadcast receiver can +receive are those sent by components of the same application or applications +with the same user ID. + +<p> +The default value depends on whether the broadcast receiver contains intent filters. +The absence of any filters means that it can be invoked only by Intent objects that +specify its exact class name. This implies that the receiver is intended only for +application-internal use (since others would not normally know the class name). +So in this case, the default value is "{@code false}". +On the other hand, the presence of at least one filter implies that the broadcast +receiver is intended to receive intents broadcast by the system or other applications, +so the default value is "{@code true}". +</p> + +<p> +This attribute is not the only way to limit a broadcast receiver's external exposure. +You can also use a permission to limit the external entities that can send it messages +(see the {@code <a href="#rcvr_prmsn">permission</a>} attribute). +</p></dd> + +<dt><a name="rcvr_icon"></a>{@code android:icon}</dt> +<dd>An icon representing the broadcast receiver. This attribute must be set +as a reference to a drawable resource containing the image definition. +If it is not set, the icon specified for the application as a whole is used +instead (see the {@code <a href="#app"><application></a>} +element's {@code <a href="#app_icon">icon</a>} attribute). + +<p> +The broadcast receiver's icon — whether set here or by the +{@code <a href="#app"><application></a>} element — is also the +default icon for all the receiver's intent filters (see the +{@code <a href="#ifilt"><intent-filter></a>} element's +{@code <a href="#ifilt_icon">icon</a>} attribute). +</p></dd> + +<dt>{@code android:label}</dt> +<dd>A user-readable label for the broadcast receiver. If this attribute is not +set, the label set for the application as a whole is +used instead (see the {@code <a href="#app"><application></a>} element's +{@code <a href="#app_label">label</a>} attribute). + +<p> +The broadcast receiver's label — whether set here or by the +{@code <a href="#app"><application></a>} element — is also the +default label for all the receiver's intent filters (see the +{@code <a href="#ifilt"><intent-filter></a>} element's +{@code <a href="#ifilt_label">label</a>} attribute). +</p> + +<p> +The label should be set as a reference to a string resource, so that +it can be localized like other strings in the user interface. +However, as a convenience while you're developing the application, +it can also be set as a raw string. +</p></dd> + +<dt>{@code android:name}</dt> +<dd>The name of the class that implements the broadcast receiver, a subclass of +{@link android.content.BroadcastReceiver}. This should be a fully qualified +class name (such as, "{@code com.example.project.ReportReceiver}"). However, +as a shorthand, if the first character of the name is a period (for example, +"{@code . ReportReceiver}"), it is appended to the package name specified in +the {@code <a href="#manf"><manifest></a>} element. + +<p> +There is no default. The name must be specified. +</p></dd> + +<dt><a name="rcvr_prmsn"></a>{@code android:permission}</dt> +<dd>The name of a permission that broadcasters must have to send a +message to the broadcast receiver. +If this attribute is not set, the permission set by the +{@code <a href="#app"><application></a>} element's +{@code <a href="#app_prmsn">permission</a>} attribute applies +to the broadcast receiver. If neither attribute is set, the receiver +is not protected by a permission. + +<p> +For more information on permissions, see the <a href="#sectperm">Permissions</a> +section earlier in this document and a separate document, +<a href="{@docRoot}guide/topics/security/security.html">Security and +Permissions</a>. +</p></dd> + +<dt>{@code android:process}</dt> +<dd>The name of the process in which the broadcast receiver should run. +Normally, all components of an application run in the default process created +for the application. It has the same name as the application package. The +{@code <a href="#app"><application></a>} element's +{@code <a href="#app_proc">process</a>} attribute can set a different +default for all components. But each component can override the default +with its own {@code process} attribute, allowing you to spread your +application across multiple processes. + +<p> +If the name assigned to this attribute begins with a colon (':'), a new +process, private to the application, is created when it's needed and +the broadcast receiver runs in that process. +If the process name begins with a lowercase character, the receiver will run +in a global process of that name, provided that it has permission to do so. +This allows components in different applications to share a process, reducing +resource usage. +</p></dd> +</dl></dd> + +</dl> +<hr> + +<h3 id="srvc"><service></h3> + +<dl class="xml"> +<dt>syntax:</dt> +<dd><pre class="stx"><service android:enabled=["true" | "false"] + android:exported[="true" | "false"] + android:icon="<i>drawable resource</i>" + android:label="<i>string resource</i>" + android:name="<i>string</i>" + android:permission="<i>string</i>" + android:process="<i>string</i>" > + . . . +</service></pre></dd> + +<dt>contained in:</dt> +<dd>{@code <a href="#app"><application></a>}</dd> + +<dt>can contain:</dt> +<dd>{@code <a href="#ifilt"><intent-filer></a>} +<br/>{@code <a href="#meta"><meta-data></a>}</dd> + +<dt>description:</dt> +<dd>Declares a service (a {@link android.app.Service} subclass) as one +of the application's components. Unlike activities, services lack a +visual user interface. They're used to implement long-running background +operations or a rich communications API that can be called by other +applications. + +<p> +All services must be represented by {@code <service>} elements in +the manifest file. Any that are not declared there will not be seen +by the system and will never be run. +</p></dd> + +<dt>attributes:</dt> +<dd><dl class="attr"> +<dt>{@code android:enabled}</dt> +<dd>Whether or not the service can be instantiated by the system — +"{@code true}" if it can be, and "{@code false}" if not. The default value +is "{@code true}". + +<p> +The {@code <a href="#app"><application></a>} element has its own +{@code <a href="#app_enabled">enabled</a>} attribute that applies to all +application components, including services. The +{@code <a href="#app"><application></a>} and {@code <service>} +attributes must both be "{@code true}" (as they both +are by default) for the service to be enabled. If either is +"{@code false}", the service is disabled; it cannot be instantiated. +</p></dd> + +<dt>{@code android:exported}</dt> +<dd>Whether or not components of other applications can invoke +the service or interact with it — "{@code true}" if they can, and +"{@code false}" if not. When the value is "{@code false}", only +components of the same application or applications +with the same user ID can start the service or bind to it. + +<p> +The default value depends on whether the service contains intent filters. The +absence of any filters means that it can be invoked only by specifying +its exact class name. This implies that the service is intended only for +application-internal use (since others would not know the class name). So in +this case, the default value is "{@code false}". +On the other hand, the presence of at least one filter implies that the service +is intended for external use, so the default value is "{@code true}". +</p> + +<p> +This attribute is not the only way to limit the exposure of a service to other +applications. You can also use a permission to limit the external entities that +can interact with the service (see the {@code <a href="#srvc_prmsn">permission</a>} +attribute). +</p></dd> + +<dt><a name="srvc_icon"></a>{@code android:icon}</dt> +<dd>An icon representing the service. This attribute must be set as a +reference to a drawable resource containing the image definition. +If it is not set, the icon specified for the application +as a whole is used instead (see the {@code <a href="#app"><application></a>} +element's {@code <a href="#app_icon">icon</a>} attribute). +</p> + +<p> +The service's icon — whether set here or by the +{@code <a href="#app"><application></a>} element — is also the +default icon for all the service's intent filters (see the +{@code <a href="#ifilt"><intent-filter></a>} element's +{@code <a href="#ifilt_icon">icon</a>} attribute). +</p></dd> + +<dt>{@code android:label}</dt> +<dd>A name for the service that can be displayed to users. +If this attribute is not set, the label set for the application as a whole is +used instead (see the {@code <a href="#app"><application></a>} element's +{@code <a href="#app_label">label</a>} attribute). + +<p> +The service's label — whether set here or by the +{@code <a href="#app"><application></a>} element — is also the +default label for all the service's intent filters (see the +{@code <a href="#ifilt"><intent-filter></a>} element's +{@code <a href="#ifilt_label">label</a>} attribute). +</p> + +<p> +The label should be set as a reference to a string resource, so that +it can be localized like other strings in the user interface. +However, as a convenience while you're developing the application, +it can also be set as a raw string. +</p></dd> + +<dt>{@code android:name}</dt> +<dd>The name of the {@link android.app.Service} subclass that implements +the service. This should be a fully qualified class name (such as, +"{@code com.example.project.RoomService}"). However, as a shorthand, if +the first character of the name is a period (for example, "{@code .RoomService}"), +it is appended to the package name specified in the +{@code <a href="#manf"><manifest></a>} element. + +<p> +There is no default. The name must be specified. +</p></dd> + +<dt><a name="srvc_prmsn"></a>{@code android:permission}</dt> +<dd>The name of a permission that that an entity must have in order to +launch the service or bind to it. If a caller of +<code>{@link android.content.Context#startService startService()}</code>, +<code>{@link android.content.Context#bindService bindService()}</code>, or +<code>{@link android.content.Context#stopService stopService()}</code>, +has not been granted this permission, the method will not work and the +Intent object will not be delivered to the service. + +<p> +If this attribute is not set, the permission set by the +{@code <a href="#app"><application></a>} element's +{@code <a href="#app_prmsn">permission</a>} attribute applies +to the service. If neither attribute is set, the service is +not protected by a permission. +</p> + +<p> +For more information on permissions, see the <a href="#sectperm">Permissions</a> +section earlier in this document and a separate document, +<a href="{@docRoot}guide/topics/security/security.html">Security and +Permissions</a>. +</p></dd> + +<dt>{@code android:process}</dt> +<dd>The name of the process where the service is to run. Normally, +all components of an application run in the default process created for the +application. It has the same name as the application package. The +{@code <a href="#app"><application></a>} element's +{@code <a href="#app_proc">process</a>} attribute can set a different +default for all components. But component can override the default +with its own {@code process} attribute, allowing you to spread your +application across multiple processes. + +<p> +If the name assigned to this attribute begins with a colon (':'), a new +process, private to the application, is created when it's needed and +the service runs in that process. +If the process name begins with a lowercase character, the service will run +in a global process of that name, provided that it has permission to do so. +This allows components in different applications to share a process, reducing +resource usage. +</p></dd> +</dl></dd> + +<dt>see also:</dt> +<dd>{@code <a href="#app"><application></a>} +<br>{@code <a href="#actv"><activity></a>}</dd> + +</dl> +<hr> + +<h3 id="usesl"><uses-library></h3> + +<dl class="xml"> +<dt>syntax:</dt> +<dd><pre><uses-library android:name="<i>string</i>" /></pre></dd> + +<dt>contained in:</dt> +<dd>{@code <a href="#app"><application></a>}</dd> + +<dt>description:</dt> +<dd>Specifies a shared library that the application must be linked against. +This element tells the system to include the library's code in the class +loader for the package. + +<p> +All of the {@code android} packages (such as {@link android.app}, +{@link android.content}, {@link android.view}, and {@link android.widget}) +are in the default library that all applications are automatically linked +against. However, some packages (such as {@code maps} and {@code awt} are +in separate libraries that are not automatically linked. Consult the +documentation for the packages you're using to determine which library +contains the package code. +</p></dd> + +<dt>attributes:</dt> +<dd><dl class="attr"> +<dt>{@code android:name}</dt> +<dd>The name of the library.</dd> +</dl></dd> + +</dl> +<hr> + + +<h3 id="usesp"><uses-permission></h3> + +<dl class="xml"> +<dt>syntax:</dt> +<dd><pre class="stx"><uses-permission android:name="<i>string</i>" /></pre></dd> + +<dt>contained in:</dt> +<dd>{@code <a href="#manf"><manifest></a>}</dd> + +<dt>description:</dt> +<dd>Requests a permission that the application must be granted in +order for it to operate correctly. Permissions are granted when the +application is installed, not while it's running. + +<p> +For more information on permissions, see the +{@code <a href="#perms">Permissions</a>} section earlier in this document +and the separate <a href="{@docRoot}guide/topics/security/security.html">Security Model</a> +document. +A list of permissions defined by the base platform can be found at +{@link android.Manifest.permission android.Manifest.permission}. + +<dt>attributes:</dt> +<dd><dl class="attr"> +<dt>{@code android:name}</dt> +<dd>The name of the permission. It can be a permission defined by the +application with the {@code <a href="#prmsn"><permission></a>} +element, a permission defined by another application, or one of the +standard system permissions, such as "{@code android.permission.CAMERA}" +or "{@code android.permission.READ_CONTACTS}". As these examples show, +a permission name typically includes the package name as a prefix.</dd> + +</dl></dd> + +<dt>see also:</dt> +<dd>{@code <a href="#prmsn"><permission></a>}</dd> + +</dl> +<hr> + + +<h3 id="usess"><uses-sdk></h3> + +<dl class="xml"> +<dt>syntax:</dt> +<dd><pre class="stx"><uses-sdk android:minSdkVersion="<i>integer</i>" /></pre></dd> + +<dt>contained in:</dt> +<dd>{@code <a href="#manf"><manifest></a>}</dd> + +<dt>description:</dt> +<dd>Declares which versions of the Android SDK (software development kit) +the application can run against. The version number is incremented when +there are additions to the API and resource tree, so an application developed +using version 3 of the SDK may not run against versions 1 or 2, but should +run against version 3, 4, 5, and above. + +<p> +The default is version 1. The current version is also 1. +</p></dd> + +<dt>attributes:</dt> +<dd><dl class="attr"> +<dt>{@code android:minSdkVersion}</dt> +<dd>An integer designating the minimum version of the SDK that's required +for the application to run.</dd> + +</dl></dd> + +</dl> + + diff --git a/docs/html/guide/topics/media/index.jd b/docs/html/guide/topics/media/index.jd new file mode 100644 index 0000000..ba6d89f --- /dev/null +++ b/docs/html/guide/topics/media/index.jd @@ -0,0 +1,188 @@ +page.title=Audio and Video +@jd:body + + <div id="qv-wrapper"> + <div id="qv"> + +<h2>Audio/Video quickview</h2> +<ul> +<li>Audio playback and record</li> +<li>Video playback</li> +<li>Handles data from raw resources, files, streams</li> +<li>Built-in codecs for a variety of media. See <a href="{@docRoot}guide/appendix/media-formats.html">Android 1.0 Media Formats</a></li> +</ul> + +<h2>Key classes</h2> +<ol> +<li><a href="{@docRoot}reference/android/media/MediaPlayer.html">MediaPlayer</a> (all audio and video formats)</li> +<li><a href="{@docRoot}reference/android/media/MediaRecorder.html">MediaRecorder</a> (record, all audio formats)</li> +</ol> + +<h2>In this document</h2> +<ol> +<li><a href="#playback.html">Audio and Video Playback</a></li> +<li><a href="#capture">Audio Capture</a></li> +</ol> + +<h2>See also</h2> +<ol> +<li><a href="{@docRoot}guide/topics/data/data-storage.html">Data Storage</a></li> +</ol> + +</div> +</div> + +<p>The Android platform offers built-in encoding/decoding for a variety of +common media types, so that you can easily integrate audio, video, and images into your +applications. Accessing the platform's media capabilities is fairly straightforward +— you do so using the same intents and activities mechanism that the rest of +Android uses.</p> + +<p>Android lets you play audio and video from several types of data sources. You +can play audio or video from media files stored in the application's resources +(raw resources), from standalone files in the filesystem, or from a data stream +arriving over a network connection. To play audio or video from your +application, use the {@link android.media.MediaPlayer} class.</p> + +<p>The platform also lets you record audio, where supported by the mobile device +hardware. Recording of video is not currently supported, but is planned for a +future release. To record audio, use the +{@link android.media.MediaRecorder} class. Note that the emulator doesn't have +hardware to capture audio, but actual mobile devices are likely to provide these +capabilities that you can access through MediaRecorder. </p> + +<p>For a list of the media formats for which Android offers built-in support, +see the <a href="{@docRoot}guide/appendix/media-formats.html">Android Media +Formats</a> appendix. </p> + +<h2 id="play">Audio and Video Playback</h2> +<p>Media can be played from anywhere: from a raw resource, from a file from the system, +or from an available network (URL).</p> + +<p>You can play back the audio data only to the standard +output device; currently, that is the mobile device speaker or Bluetooth headset. You +cannot play sound files in the conversation audio. </p> + +<h3 id="playraw">Playing from a Raw Resource</h3> +<p>Perhaps the most common thing to want to do is play back media (notably sound) +within your own applications. Doing this is easy:</p> +<ol> + <li>Put the sound (or other media resource) file into the <code>res/raw</code> + folder of your project, where the Eclipse plugin (or aapt) will find it and + make it into a resource that can be referenced from your R class</li> + <li>Create an instance of <code>MediaPlayer</code>, referencing that resource using + {@link android.media.MediaPlayer#create MediaPlayer.create}, and then call + {@link android.media.MediaPlayer#start() start()} on the instance:</li> +</ol> +<pre> + MediaPlayer mp = MediaPlayer.create(context, R.raw.sound_file_1); + mp.start(); +</pre> +<p>To stop playback, call {@link android.media.MediaPlayer#stop() stop()}. If +you wish to later replay the media, then you must +{@link android.media.MediaPlayer#reset() reset()} and +{@link android.media.MediaPlayer#prepare() prepare()} the MediaPlayer object +before calling {@link android.media.MediaPlayer#start() start()} again. +(<code>create()</code> calls <code>prepare()</code> the first time.)</p> +<p>To pause playback, call {@link android.media.MediaPlayer#pause() pause()}. +Resume playback from where you paused with +{@link android.media.MediaPlayer#start() start()}.</p> + +<h3 id="playfile">Playing from a File or Stream</h3> +<p>You can play back media files from the filesystem or a web URL:</p> +<ol> + <li>Create an instance of the <code>MediaPlayer</code> using <code>new</code></li> + <li>Call {@link android.media.MediaPlayer#setDataSource setDataSource()} + with a String containing the path (local filesystem or URL) + to the file you want to play</li> + <li>First {@link android.media.MediaPlayer#prepare prepare()} then + {@link android.media.MediaPlayer#start() start()} on the instance:</li> +</ol> +<pre> + MediaPlayer mp = new MediaPlayer(); + mp.setDataSource(PATH_TO_FILE); + mp.prepare(); + mp.start(); +</pre> +<p>{@link android.media.MediaPlayer#stop() stop()} and +{@link android.media.MediaPlayer#pause() pause()} work the same as discussed +above.</p> + <p class="note"><strong>Note:</strong> It is possible that <code>mp</code> could be + null, so good code should <code>null</code> check after the <code>new</code>. + Also, <code>IllegalArgumentException</code> and <code>IOException</code> either + need to be caught or passed on when using <code>setDataSource()</code>, since + the file you are referencing may not exist.</p> +<p class="note"><strong>Note:</strong> +If you're passing a URL to an online media file, the file must be capable of +progressive download.</p> + +<h2 id="capture">Audio Capture</h2> +<p>Audio capture from the device is a bit more complicated than audio/video playback, but still fairly simple:</p> +<ol> + <li>Create a new instance of {@link android.media.MediaRecorder + android.media.MediaRecorder} using <code>new</code></li> + <li>Create a new instance of {@link android.content.ContentValues + android.content.ContentValues} and put in some standard properties like + <code>TITLE</code>, <code>TIMESTAMP</code>, and the all important + <code>MIME_TYPE</code></li> + <li>Create a file path for the data to go to (you can use {@link + android.content.ContentResolver android.content.ContentResolver} to + create an entry in the Content database and get it to assign a path + automatically which you can then use)</li> + <li>Set the audio source using {@link android.media.MediaRecorder#setAudioSource + MediaRecorder.setAudioSource()}. You will probably want to use + <code>MediaRecorder.AudioSource.MIC</code></li> + <li>Set output file format using {@link + android.media.MediaRecorder#setOutputFormat MediaRecorder.setOutputFormat()} + </li> + <li>Set the audio encoder using + {@link android.media.MediaRecorder#setAudioEncoder MediaRecorder.setAudioEncoder()} + </li> + <li>Call {@link android.media.MediaRecorder#prepare prepare()} + on the MediaRecorder instance.</li> + <li>To start audio capture, call + {@link android.media.MediaRecorder#start start()}. </li> + <li>To stop audio capture, call {@link android.media.MediaRecorder#stop stop()}. + <li>When you are done with the MediaRecorder instance, call +{@link android.media.MediaRecorder#release release()} on it. </li> +</ol> + +<h3>Example: Audio Capture Setup and Start</h3> +<p>The example below illustrates how to set up, then start audio capture.</p> +<pre> + recorder = new MediaRecorder(); + ContentValues values = new ContentValues(3); + + values.put(MediaStore.MediaColumns.TITLE, SOME_NAME_HERE); + values.put(MediaStore.MediaColumns.TIMESTAMP, System.currentTimeMillis()); + values.put(MediaStore.MediaColumns.MIME_TYPE, recorder.getMimeContentType()); + + ContentResolver contentResolver = new ContentResolver(); + + Uri base = MediaStore.Audio.INTERNAL_CONTENT_URI; + Uri newUri = contentResolver.insert(base, values); + + if (newUri == null) { + // need to handle exception here - we were not able to create a new + // content entry + } + + String path = contentResolver.getDataFilePath(newUri); + + // could use setPreviewDisplay() to display a preview to suitable View here + + recorder.setAudioSource(MediaRecorder.AudioSource.MIC); + recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); + recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); + recorder.setOutputFile(path); + + recorder.prepare(); + recorder.start(); +</pre> +<h3>Stop Recording</h3> +<p>Based on the example above, here's how you would stop audio capture. </p> +<pre> + recorder.stop(); + recorder.release(); +</pre> + diff --git a/docs/html/guide/topics/media/media.jd b/docs/html/guide/topics/media/media.jd index 16ad2b7..463686d 100644 --- a/docs/html/guide/topics/media/media.jd +++ b/docs/html/guide/topics/media/media.jd @@ -28,6 +28,7 @@ page.title=Media Capabilities <li>{@link android.media.MediaPlayer} (playback, all audio and video formats)</li> <li>{@link android.media.MediaRecorder} (record, all audio formats)</li> </ul> +</div> <p>The Android platform offers built-in encoding/decoding for a variety of common media types, so that you can easily integrate audio, video, and images into your applications. Accessing the platform's media diff --git a/docs/html/guide/topics/providers/content-providers.jd b/docs/html/guide/topics/providers/content-providers.jd index 93b379e..86dcebf 100644 --- a/docs/html/guide/topics/providers/content-providers.jd +++ b/docs/html/guide/topics/providers/content-providers.jd @@ -1,12 +1,31 @@ page.title=Content Providers @jd:body -<h1>Content Providers</h1> +<div id="qv-wrapper"> +<div id="qv"> +<h2>Key classes</h2> +<ol> +<li>{@link android.content.ContentProvider}</li> +<li>{@link android.content.ContentResolver}</li> +<li>{@link android.database.Cursor}</li> +</ol> + +<h2>In this document</h2> +<ol> +<li><a href="#basics">Content provider basics</a></li> +<li><a href="#querying">Querying a content provider</a></li> +<li><a href="#modifying">Modifying data in a provider</a></li> +<li><a href="#creating">Creating a content provider</a></li> +<li><a href="#urisum">Content URI summary</a></li> +</ol> +</div> +</div> <p> Content providers store and retrieve data and make it accessible to all applications. They're the only way to share data across applications; there's -no common storage area that all Android packages can access. +no common storage area that all Android packages can access. +</p> <p> Android ships with a number of content providers for common data types @@ -14,30 +33,31 @@ Android ships with a number of content providers for common data types see some of them listed in the {@link android.provider android.provider} package. You can query these providers for the data they contain (although, for some, you must acquire the proper permission to read the data). +</p> <p> If you want to make your own data public, you have two options: You can create your own content provider (a {@link android.content.ContentProvider} subclass) or you can add the data to an existing provider — if there's one that controls the same type of data and you have permission to write to it. +</p> <p> -This document is an introduction to using content providers. It explores -the following topics: +This document is an introduction to using content providers. After a +brief discussion of the fundamentals, it explores how to query a content +provider, how to modify data controlled by a provider, and how to create +a content provider of your own. +</p> -<dl><dd><a href="#basics">Content provider basics</a> -<br/><a href="#querying">Querying a content provider</a> -<br/><a href="#modifying">Modifying data in a provider</a> -<br/><a href="#creating">Creating a content provider</a></dd></dl> - -<h2>Content Provider Basics<a href="#basics"></a></h2> +<h2><a name="basics"></a>Content Provider Basics</h2> <p> How a content provider actually stores its data under the covers is up to its designer. But all content providers implement a common interface for querying the provider and returning results — as well as for adding, altering, and deleting data. +</p> <p> It's an interface that clients use indirectly, most generally through @@ -45,12 +65,14 @@ It's an interface that clients use indirectly, most generally through by calling <code>{@link android.content.Context#getContentResolver getContentResolver()}</code> from within the implementation of an Activity or other application component: +</p> <pre>ContentResolver cr = getContentResolver();</pre> <p> You can then use the ContentResolver's methods to interact with whatever content providers you're interested in. +</p> <p> When a query is initiated, the Android system identifies the content provider @@ -61,6 +83,7 @@ at all. Typically, there's just a single instance of each type of ContentProvider. But it can communicate with multiple ContentResolver objects in different applications and processes. The interaction between processes is handled by the ContentResolver and ContentProvider classes. +</p> <h3>The data model</h3> @@ -70,6 +93,7 @@ Content providers expose their data as a simple table on a database model, where each row is a record and each column is data of a particular type and meaning. For example, information about people and their phone numbers might be exposed as follows: +</p> <table> <tr> @@ -119,6 +143,7 @@ Every record includes a numeric {@code _ID} field that uniquely identifies the record within the table. IDs can be used to match records in related tables — for example, to find a person's phone number in one table and pictures of that person in another. +</p> <p> A query returns a {@link android.database.Cursor} object that can move from @@ -126,9 +151,10 @@ record to record and column to column to read the contents of each field. It has specialized methods for reading each type of data. So, to read a field, you must know what type of data the field contains. (There's more on query results and Cursor objects later.) +</p> -<h3>URIs</h3><a name="uri"></a> +<h3><a name="uri"></a>URIs</h3> <p> Each content provider exposes a public URI (wrapped as a {@link android.net.Uri} @@ -136,6 +162,7 @@ object) that uniquely identifies its data set. A content provider that controls multiple data sets (multiple tables) exposes a separate URI for each one. All URIs for providers begin with the string "{@code content://}". The {@code content:} scheme identifies the data as being controlled by a content provider. +</p> <p> If you're defining a content provider, it's a good idea to also define a @@ -144,38 +171,46 @@ Android defines {@code CONTENT_URI} constants for all the providers that come with the platform. For example, the URI for the table that matches phone numbers to people and the URI for the table that holds pictures of people (both controlled by the Contacts content provider) are: +</p> <p> -<dl><dd>{@code android.provider.Contacts.Phones.CONTENT_URI} -<br/>{@code android.provider.Contacts.Photos.CONTENT_URI}</dd></dl> +<p style="margin-left: 2em">{@code android.provider.Contacts.Phones.CONTENT_URI} +<br/>{@code android.provider.Contacts.Photos.CONTENT_URI} +</p> <p> Similarly, the URIs for the table of recent phone calls and the table of calendar entries are: +</p> <p> -<dl><dd>{@code android.provider.CallLog.Calls.CONTENT_URI} -<br/>{@code android.provider.Calendar.CONTENT_URI}</dd></dl> +<p style="margin-left: 2em">{@code android.provider.CallLog.Calls.CONTENT_URI} +<br/>{@code android.provider.Calendar.CONTENT_URI} +</p> <p> The URI constant is used in all interactions with the content provider. Every {@link android.content.ContentResolver} method takes the URI as its first argument. It's what identifies which provider the ContentResolver should talk to and which table of the provider is being targeted. +</p> -<h2>Querying a Content Provider<a name="querying"></a></h2> +<h2><a name="querying"></a>Querying a Content Provider</h2> <p> You need three pieces of information to query a content provider: +</p> + <ul> -<li>The URI that identifies the provider -<li>The names of the data fields you want to receive -<li>The data types for those fields +<li>The URI that identifies the provider</li> +<li>The names of the data fields you want to receive</li> +<li>The data types for those fields</li> </ul> <p> If you're querying a particular record, you also need the ID for that record. +</p> <h3>Making the query</h3> @@ -193,20 +228,23 @@ and requerying itself when the activity restarts. You can ask an Activity to begin managing an unmanaged Cursor object for you by calling <code>{@link android.app.Activity#startManagingCursor Activity.startManagingCursor()}</code>. +</p> <p> The first argument to either <code>{@link android.content.ContentResolver#query query()}</code> or <code>{@link android.app.Activity#managedQuery managedQuery()}</code> is the provider URI — the {@code CONTENT_URI} constant that identifies a particular ContentProvider and data set (see <a href="#uri">URIs</a> earlier). +</p> <p> To restrict a query to just one record, you can append the {@code _ID} value for that record to the URI — that is, place a string matching the ID as the last segment of the path part of the URI. For example, if the ID is 23, the URI would be: +</p> -<dl><dd>{@code content://. . . ./23}</dd></dl> +<p style="margin-left: 2em">{@code content://. . . ./23}</p> <p> There are some helper methods, particularly @@ -216,6 +254,7 @@ android.net.Uri#withAppendedPath Uri.withAppendedPath()}</code>, that make it easy to append an ID to a URI. Both are static methods that return a Uri object with the ID added. So, for example, if you were looking for record 23 in the database of people contacts, you might construct a query as follows: +</p> <pre> import android.provider.Contacts.People; @@ -238,32 +277,34 @@ Cursor cur = managedQuery(myPerson, null, null, null, null); The other arguments to the <code>{@link android.content.ContentResolver#query query()}</code> and <code>{@link android.app.Activity#managedQuery managedQuery()}</code> methods delimit the query in more detail. They are: +</p> <ul> -<p><li>The names of the data columns that should be returned. A {@code null} +<li>The names of the data columns that should be returned. A {@code null} value returns all columns. Otherwise, only columns that are listed by name are returned. All the content providers that come with the platform define constants for their columns. For example, the {@link android.provider.Contacts.Phones android.provider.Contacts.Phones} class defines constants for the names of the columns in the phone table illustrated earlier &mdash {@code _ID}, {@code NUMBER}, {@code NUMBER_KEY}, {@code NAME}, -and so on. +and so on.</li> -<p><li>A filter detailing which rows to return, formatted as an SQL {@code WHERE} +<li><p>A filter detailing which rows to return, formatted as an SQL {@code WHERE} clause (excluding the {@code WHERE} itself). A {@code null} value returns -all rows (unless the URI limits the query to a single record). +all rows (unless the URI limits the query to a single record).</p></li> -<p><li>Selection arguments. +<li><p>Selection arguments.</p></li> -<p><li>A sorting order for the rows that are returned, formatted as an SQL -{@code ORDER BY} clause (excluding the {@code ORDER BY} itself). A {@code null} value -returns the records in the default order for the table, which may be -unordered. +<li><p>A sorting order for the rows that are returned, formatted as an SQL +{@code ORDER BY} clause (excluding the {@code ORDER BY} itself). A {@code null} +value returns the records in the default order for the table, which may be +unordered.</p></li> </ul> <p> Let's look at an example query to retrieve a list of contact names and their primary phone numbers: +</p> <pre> import android.provider.Contacts.People; @@ -294,6 +335,7 @@ This query retrieves data from the People table of the Contacts content provider. It gets the name, primary phone number, and unique record ID for each contact. It also reports the number of records that are returned as the {@code _COUNT} field of each record. +</p> <p> The constants for the names of the columns are defined in various interfaces @@ -303,6 +345,7 @@ in {@link android.provider.Contacts.PhonesColumns PhoneColumns}. The {@link android.provider.Contacts.People Contacts.People} class implements each of these interfaces, which is why the code example above could refer to them using just the class name. +</p> <h3>What a query returns</h3> @@ -315,9 +358,11 @@ But every provider has an {@code _ID} column, which holds a unique numeric ID for each record. Every provider can also report the number of records returned as the {@code _COUNT} column; its value is the same for all rows. +</p> <p> Here is an example result set for the query in the previous section: +</p> <table border="1"> <tbody> @@ -353,6 +398,7 @@ The retrieved data is exposed by a {@link android.database.Cursor Cursor} object that can be used to iterate backward or forward through the result set. You can use this object only to read the data. To add, modify, or delete data, you must use a ContentResolver object. +</p> <h3>Reading retrieved data</h3> @@ -372,10 +418,12 @@ android.database.Cursor#getFloat getFloat()}</code>. the Cursor object will give you the String representation of the data.) The Cursor lets you request the column name from the index of the column, or the index number from the column name. +</p> <p> The following snippet demonstrates reading names and phone numbers from the query illustrated earlier: +</p> <pre> import android.provider.Contacts.People; @@ -411,7 +459,8 @@ In general, smaller amounts of data (say, from 20 to 50K or less) are most often directly entered in the table and can be read by calling <code>{@link android.database.Cursor#getBlob Cursor.getBlob()}</code>. It returns a byte array. - +</p> + <p> If the table entry is a {@code content:} URI, you should never try to open and read the file directly (for one thing, permissions problems can make this @@ -419,18 +468,20 @@ fail). Instead, you should call <code>{@link android.content.ContentResolver#openInputStream ContentResolver.openInputStream()}</code> to get an {@link java.io.InputStream} object that you can use to read the data. +</p> -<h2>Modifying Data<a name="modifying"></a></h2> +<h2><a name="modifying"></a>Modifying Data</h2> <p> Data kept by a content provider can be modified by: +</p> <ul> -<p><li>Adding new records -<li>Adding new values to existing records -<li>Batch updating existing records -<li>Deleting records +<p><li>Adding new records</li> +<li>Adding new values to existing records</li> +<li>Batch updating existing records</li> +<li>Deleting records</li> </ul> <p> @@ -438,6 +489,7 @@ All data modification is accomplished using {@link android.content.ContentResolv methods. Some content providers require a more restrictive permission for writing data than they do for reading it. If you don't have permission to write to a content provider, the ContentResolver methods will fail. +</p> <h3>Adding records</h3> @@ -453,6 +505,7 @@ the full URI of the new record — that is, the provider's URI with the appended ID for the new record. You can then use this URI to query and get a Cursor over the new record, and to further modify the record. Here's an example: +</p> <pre> import android.provider.Contacts.People; @@ -478,6 +531,7 @@ Once a record exists, you can add new information to it or modify existing information. For example, the next step in the example above would be to add contact information — like a phone number or an IM or e-mail address — to the new entry. +</p> <p> The best way to add to a record in the Contacts database is to append @@ -487,6 +541,7 @@ Contacts table exposes a name for this purpose as a {@code CONTENT_DIRECTORY} constant. The following code continues the previous example by adding a phone number and e-mail address for the record just created: +</p> <pre> Uri phoneUri = null; @@ -527,6 +582,7 @@ or a complete song, put a {@code content:} URI for the data in the table and cal ContentResolver.openOutputStream()}</code> with the file's URI. (That causes the content provider to store the data in a file and record the file path in a hidden field of the record.) +</p> <p> In this regard, the {@link android.provider.MediaStore} content @@ -539,6 +595,7 @@ to get the data itself. Similarly, the same URI that is used with {@code insert()} to put meta-information into a MediaStore record is used with {@code openOutputStream()} to place the binary data there. The following code snippet illustrates this convention: +</p> <pre> import android.provider.MediaStore.Images.Media; @@ -574,14 +631,16 @@ To batch update a group of records (for example, to change "NY" to "New York" in all fields), call the <code>{@link android.content.ContentResolver#update ContentResolver.update()}</code> method with the columns and values to change. +</p> -<h3>Deleting a record <a name="deletingrecord"></a></h3> +<h3><a name="deletingrecord"></a>Deleting a record</h3> <p> To delete a single record, call {<code>{@link android.content.ContentResolver#delete ContentResolver.delete()}</code> with the URI of a specific row. +</p> <p> To delete multiple rows, call <code>{@link @@ -590,30 +649,33 @@ with the URI of the type of record to delete (for example, {@code android.provid clause defining which rows to delete. (<i><b>Caution</b>: Be sure to include a valid {@code WHERE} clause if you're deleting a general type, or you risk deleting more records than you intended!</i>). +</p> -<h2>Creating a Content Provider<a name="creating"></a></h2> +<h2><a name="creating"></a>Creating a Content Provider</h2> <p> To create a content provider, you must: +</p> <ul> -<p><li>Set up a system for storing the data. Most content providers +<li>Set up a system for storing the data. Most content providers store their data using Android's file storage methods or SQLite databases, but you can store your data any way you want. Android provides the {@link android.database.sqlite.SQLiteOpenHelper SQLiteOpenHelper} class to help you create a database and {@link -android.database.sqlite.SQLiteDatabase SQLiteDatabase} to manage it. +android.database.sqlite.SQLiteDatabase SQLiteDatabase} to manage it.</li> -<p><li>Extend the {@link android.content.ContentProvider} class to provide -access to the data. +<li><p>Extend the {@link android.content.ContentProvider} class to provide +access to the data.</p></li> -<p><li>Declare the content provider in the manifest file for your -application (AndroidManifest.xml). +<li><p>Declare the content provider in the manifest file for your +application (AndroidManifest.xml).</p></li> </ul> <p> The following sections have notes on the last two of these tasks. +</p> <h3>Extending the ContentProvider class</h3> @@ -623,13 +685,14 @@ You define a {@link android.content.ContentProvider} subclass to expose your data to others using the conventions expected by ContentResolver and Cursor objects. Principally, this means implementing six abstract methods declared in the ContentProvider class: +</p> -<dl><dd>{@code query()} +<p style="margin-left: 2em">{@code query()} <br/>{@code insert()} <br/>{@code update()} <br/>{@code delete()} <br/>{@code getType()} -<br/>{@code onCreate()}</dd></dl> +<br/>{@code onCreate()}</p> <p> The {@code query()} method must return a {@link android.database.Cursor} object @@ -639,19 +702,27 @@ Android provides some ready-made Cursor objects that you can use. For example, an SQLite database. You get the Cursor object by calling any of the {@link android.database.sqlite.SQLiteDatabase SQLiteDatabase} class's {@code query()} methods. There are other Cursor implementations — such as {@link -android.database.MatrixCursor} — for data not stored in a database. +android.database.MatrixCursor} — for data not stored in a database. +</p> + +<p> +Because these ContentProvider methods can be called from +various ContentResolver objects in different processes and threads, +they must be implemented in a thread-safe manner. +</p> <p> As a courtesy, you might also want to call <code>{@link android.content.ContentResolver#notifyChange(android.net.Uri,android.database.ContentObserver) ContentResolver.notifyChange()}</code> to notify listeners when there are modifications to the data. +</p> <p> Beyond defining the subclass itself, there are other steps you should take to simplify the work of clients and make the class more accessible: +</p> <ul> -<p> <li>Define a {@code public static final} {@link android.net.Uri} named {@code CONTENT_URI}. This is the string that represents the full {@code content:} URI that your content provider handles. You must define a @@ -667,21 +738,23 @@ If the provider has subtables, also define {@code CONTENT_URI} constants for each of the subtables. These URIs should all have the same authority (since that identifies the content provider), and be distinguished only by their paths. For example: +</p> -<dl><dd>{@code content://com.example.codelab.transporationprovider/train} +<p style="margin-left: 2em">{@code content://com.example.codelab.transporationprovider/train} <br/>{@code content://com.example.codelab.transporationprovider/air/domestic} -<br/>{@code content://com.example.codelab.transporationprovider/air/international}</dd></dl> +<br/>{@code content://com.example.codelab.transporationprovider/air/international}</p> <p> For an overview of {@code content:} URIs, see the <a href="#urisum">Content URI Summary</a> at the end of this document. +</p></li> -<p> -<li>Define the column names that the content provider will return to clients. +<li><p>Define the column names that the content provider will return to clients. If you are using an underlying database, these column names are typically identical to the SQL database column names they represent. Also define {@code public static} String constants that clients can use to specify the columns in queries and other instructions. +</p> <p> Be sure to include an integer column named "{@code _id}" @@ -690,8 +763,9 @@ the IDs of the records. You should have this field whether or not you have another field (such as a URL) that is also unique among all records. If you're using the SQLite database, the {@code _ID} field should be the following type: +</p> -<dl><dd>{@code INTEGER PRIMARY KEY AUTOINCREMENT}</dd></dl> +<p style="margin-left: 2em">{@code INTEGER PRIMARY KEY AUTOINCREMENT}</p> <p> The {@code AUTOINCREMENT} descriptor is optional. But without it, SQLite @@ -699,50 +773,42 @@ increments an ID counter field to the next number above the largest existing number in the column. If you delete the last row, the next row added will have the same ID as the deleted row. {@code AUTOINCREMENT} avoids this by having SQLite increment to the next largest value whether deleted or not. +</p> +</li> -<p> -<li>Carefully document the data type of each column. Clients need this -information to read the data. +<li><p>Carefully document the data type of each column. Clients need this +information to read the data.</p></li> -<p> -<li>If you are handling a new data type, you must define a new MIME type +<li><p>If you are handling a new data type, you must define a new MIME type to return in your implementation of <code>{@link android.content.ContentProvider#getType ContentProvider.getType()}</code>. The type depends in part on whether or not the {@code content:} URI submitted to {@code getType()} limits the request to a specific record. There's one form of the MIME type for a single record and another for multiple records. Use the {@link android.net.Uri Uri} methods to help determine what is being -requested. Here is the general format for each type: +requested. Here is the general format for each type:</p></li> <ul> -<p><li>For a single record: - -<dl><dd>{@code vnd.android.cursor.item/vnd.<em>yourcompanyname.contenttype</em}</dd></dl> - -<p>For example, a request for train record 122 such as the following URI, - -<dl><dd>{@code content://com.example.transportationprovider/trains/122}</dd></dl> +<li><p>For a single record: {@code vnd.android.cursor.item/vnd.<em>yourcompanyname.contenttype</em}</p> -<p>might return this MIME type: +<p>For example, a request for train record 122, like this URI,</p> +<p style="margin-left: 2em">{@code content://com.example.transportationprovider/trains/122}</p> -<dl><dd>{@code vnd.android.cursor.item/vnd.example.rail}</dd></dl>. +<p>might return this MIME type:</p> +<p style="margin-left: 2em">{@code vnd.android.cursor.item/vnd.example.rail}</p> +</li> -<p> -<li>For multiple records: - -<dl><dd>{@code vnd.android.cursor.dir/vnd.<em>yourcompanyname.contenttype</em>}</dd></dl> - -<p>For example, a request for all train records like the following URI, +<li><p>For multiple records: {@code vnd.android.cursor.dir/vnd.<em>yourcompanyname.contenttype</em>}</p> -<dl><dd>{@code content://com.example.transportationprovider/trains}</dd></dl> +<p>For example, a request for all train records, like the following URI,</p> +<p style="margin-left: 2em">{@code content://com.example.transportationprovider/trains}</p> -<p>might return this MIME type - -<dl><dd>{@code vnd.android.cursor.dir/vnd.example.rail}</dd></dl> +<p>might return this MIME type:</p> +<p style="margin-left: 2em">{@code vnd.android.cursor.dir/vnd.example.rail}</p> +</li> </ul> -<p> -<li>If you are exposing byte data that's too big to put in the table itself +<li><p>If you are exposing byte data that's too big to put in the table itself — such as a large bitmap file — the field that exposes the data to clients should actually contain a {@code content:} URI string. This is the field that gives clients access to the data file. The record @@ -753,13 +819,14 @@ android.content.ContentResolver#openInputStream ContentResolver.openInputStream( on the user-facing field holding the URI for the item. The ContentResolver will request the "{@code _data}" field for that record, and because it has higher permissions than a client, it should be able to access -that file directly and return a read wrapper for the file to the client. +that file directly and return a read wrapper for the file to the client.</p></li> </ul> <p> For an example of a private content provider implementation, see the -NodePadProvider class in the notepad sample application that ships with the SDK. +NodePadProvider class in the Notepad sample application that ships with the SDK. +</p> <h3>Declaring the content provider</h3> @@ -769,6 +836,7 @@ To let the Android system know about the content provider you've developed, declare it with a {@code <provider>} element in the application's AndroidManifest.xml file. Content providers that are not declared in the manifest are not visible to the Android system +</p> <p> The {@code name} attribute is the fully qualified name of the ContentProvider @@ -776,6 +844,7 @@ subclass. The {@code authorities} attribute is the authority part of the {@code content:} URI that identifies the provider. For example if the ContentProvider subclass is AutoInfoProvider, the {@code <provider>} element might look like this: +</p> <pre> <provider name="com.example.autos.AutoInfoProvider" @@ -788,15 +857,17 @@ For example if the ContentProvider subclass is AutoInfoProvider, the Note that the {@code authorities} attribute omits the path part of a {@code content:} URI. For example, if AutoInfoProvider controlled subtables for different types of autos or different manufacturers, +</p> -<dl><dd>{@code content://com.example.autos.autoinfoprovider/honda} +<p style="margin-left: 2em">{@code content://com.example.autos.autoinfoprovider/honda} <br/>{@code content://com.example.autos.autoinfoprovider/gm/compact} -<br/>{@code content://com.example.autos.autoinfoprovider/gm/suv}</dd></dl> +<br/>{@code content://com.example.autos.autoinfoprovider/gm/suv}</p> <p> -those paths would not be declared in the manifest. The authority -identifies the provider; your provider can interpret the path part of the -URI in any way you choose. +those paths would not be declared in the manifest. The authority is what +identifies the provider, not the path; your provider can interpret the path +part of the URI in any way you choose. +</p> <p> Other {@code <provider>} attributes can set permissions to read and @@ -806,42 +877,46 @@ attribute to "{@code true}" if data does not need to be synchronized between multiple running versions of the content provider. This permits an instance of the provider to be created in each client process, eliminating the need to perform IPC. +</p> -<h2>Content URI Summary</h2><a name="urisum"></a> +<h2><a name="urisum"></a>Content URI Summary</h2> <p> Here is a recap of the important parts of a content URI: +</p> <p> -<img src="../../images/content_uri.png" alt="Elements of a content URI" +<img src="{@docRoot}images/content_uri.png" alt="Elements of a content URI" height="80" width="528"> +</p> <ol type="A"> -<p><li>Standard prefix indicating that the data is controlled by a -content provider. It's never modified. </li> +<li>Standard prefix indicating that the data is controlled by a +content provider. It's never modified.</li> -<p><li>The authority part of the URI; it identifies the content provider. +<li><p>The authority part of the URI; it identifies the content provider. For third-party applications, this should be a fully-qualified class name (reduced to lowercase) to ensure uniqueness. The authority is declared in -the {@code <provider>} element's {@code authorities} attribute: +the {@code <provider>} element's {@code authorities} attribute:</p> <pre><provider name=".TransportationProvider" authorities="com.example.transportationprovider" - . . . ></pre> + . . . ></pre></li> -<p><li>The path that the content provider uses to determine what kind of data is +<li><p>The path that the content provider uses to determine what kind of data is being requested. This can be zero or more segments long. If the content provider exposes only one type of data (only trains, for example), it can be absent. If the provider exposes several types, including subtypes, it can be several segments long — for example, "{@code land/bus}", "{@code land/train}", -"{@code sea/ship}", and "{@code sea/submarine}" to give four possibilities. +"{@code sea/ship}", and "{@code sea/submarine}" to give four possibilities.</p></li> -<p><li>The ID of the specific record being requested, if any. This is the +<li><p>The ID of the specific record being requested, if any. This is the {@code _ID} value of the requested record. If the request is not limited to -a single record, this segment and the trailing slash are omitted: +a single record, this segment and the trailing slash are omitted:</p> -<dl><dd>{@code content://com.example.transportationprovider/trains}</dd></dl> +<p style="margin-left: 2em">{@code content://com.example.transportationprovider/trains}</p> +</li> </ol> diff --git a/docs/html/guide/topics/resources/available-resources.jd b/docs/html/guide/topics/resources/available-resources.jd index bfe360e..c59d3a8 100644 --- a/docs/html/guide/topics/resources/available-resources.jd +++ b/docs/html/guide/topics/resources/available-resources.jd @@ -1,45 +1,71 @@ page.title=Available Resource Types +parent.title=Resources and Assets +parent.link=index.html @jd:body -<p>This page describes the different types of resources that you can -externalize from your code and package with your application. They fall into -the following groups:</p> -<ul> - <li><a href="#simplevalues">Simple Values</a></li> - <li><a href="#drawables">Drawables</a></li> +<div id="qv-wrapper"> +<div id="qv"> + + <h2>Key classes</h2> + <ol> + <li>{@link android.content.res.Resources}</li> + <li>{@link android.content.res.AssetManager}</li> + </ol> + + <h2>In this document</h2> + <ol> + <li><a href="#simplevalues">Simple Values</a> + <ol> + <li><a href="#colorvals">Color Values</a></li> + <li><a href="#stringresources">Strings and Styled Text</a></li> + <li><a href="#dimension">Dimension Values</a></li> + </ol> + </li> + <li><a href="#drawables">Drawables</a> + <ol> + <li><a href="#imagefileresources">Bitmap Files</a></li> + <li><a href="#colordrawableresources">Color Drawables</a></li> + <li><a href="#ninepatch">Nine-Patch (Stretchable) Images</a></li> + </ol> + </li> <li><a href="#animation">Animation</a></li> - <li><a href="#layoutresources">Layout</a></li> + <li><a href="#layoutresources">Layout</a> + <ol> + <li><a href="#customresources">Custom Layout Resources</a> + </ol> + </li> <li><a href="#stylesandthemes">Styles and Themes</a></li> -</ul> + </ol> + +</div> +</div> + +<p>This page describes the different types of resources that you can +externalize from your code and package with your application. </p> + <p>For more details on how to use resources in your application, please see the - <a href="{@docRoot}devel/resources-i18n.html">Resources and i18n</a> + <a href="resources-i18n.html">Resources and Internationalization</a> documentation.</p> -<a name="simplevalues" id="simplevalues"></a> -<h2>Simple Values</h2> + +<h2 id="simplevalues">Simple Values</h2> <p>All simple resource values can be expressed as a string, using various formats to unambiguously indicate the type of resource being created. For this reason, these values can be defined both as standard resources -(under res/values), as well as direct values supplied for +(under res/values/), as well as direct values supplied for mappings in <a href="#stylesandthemes">styles and themes</a>, and attributes in XML files such as <a href="#layoutresources">layouts</a>.</p> -<ul> - <li><a href="#colorvals">Colors</a></li> - <li><a href="#stringresources">Strings and Styled Text</a></li> - <li><a href="#dimension">Dimensions</a></li> -</ul> -<a name="colorvals" id="colorvals"></a> -<h3>Color Values</h3> +<h3 id="colorvals">Color Values</h3> <p> A color value specifies an RGB value with an alpha channel, which can - be used in various places such as specifying a solid color for a Drawable + be used in various places such as specifying a solid color for a {@link android.graphics.drawable.Drawable} or the color to use for text. A color value always begins with - a '#' character and then is followed by the alpha-red-green-blue information + a pound (#) character and then followed by the Alpha-Red-Green-Blue information in one of the following formats: </p> <ul> @@ -128,8 +154,9 @@ int color = getResources.getColor(R.color.opaque_red); android:text="Some Text"/> </pre> -<a name="stringresources" id="stringresources"></a> -<h3>Strings and Styled Text</h3> + + +<h3 id="stringresources">Strings and Styled Text</h3> <p> Strings, with optional <a href="#styledtext">simple formatting</a>, can be stored and retrieved as resources. You can add formatting to your string by @@ -227,8 +254,8 @@ tv.setText(str); android:text="@string/simple_welcome_message"/> </pre> -<a name="styledtext" id="styledtext"></a> -<h4>Using Styled Text as a Format String</h4> + +<h4 id="styledtext">Using Styled Text as a Format String</h4> <p> Sometimes you may want to create a styled text resource that is also used as a format string. This cannot be done directly because there is no way of passing @@ -268,8 +295,8 @@ CharSequence styledResults = Html.fromHtml(resultsText); </li> </ol> -<a name="dimension" id="dimension"></a> -<h3>Dimension Values</h3> + +<h3 id="dimension"Dimension Values</h3> <p>You can create common dimensions to use for various screen elements by defining dimension values in XML. A dimension resource is a number followed by a unit of measurement. For example: 10px, 2in, 5sp. Here are the units of @@ -376,22 +403,17 @@ float dimen = Resources.getDimen(R.dimen.one_pixel); android:textSize="@dimen/sixteen_sp"/> </pre> -<a name="drawables" id="drawables"></a> -<h2>Drawables</h2> + +<h2 id="drawables">Drawables</h2> <p>A {@link android.graphics.drawable.Drawable} is a type of resource that you retrieve with {@link android.content.res.Resources#getDrawable Resources.getDrawable()} and use to draw to the screen. There are a number of drawable resources that can be created.</p> -<ul> - <li><a href="#imagefileresources">Bitmap Drawables</a></li> - <li><a href="#colordrawableresources">Color Drawables</a></li> - <li><a href="#ninepatch">Nine Patch (Stretchable) Drawables</a></li> -</ul> -<a name="imagefileresources" id="imagefileresources"></a> -<h3>Bitmap files</h3> + +<h3 id="imagefileresources">Bitmap Files</h3> <p>Android supports bitmap resource files in a few different formats: png (preferred), jpg (acceptable), gif (discouraged). The bitmap file itself is compiled and referenced by the file name without the extension (so @@ -417,46 +439,11 @@ res/drawable/my_picture.png would be referenced as R.drawable.my_picture).</p> <strong>XML</strong> <code>@[<em>package</em>:]drawable/<em>some_file</em></code> </li> </ul> -<p> - <strong>Example Code Use</strong> -</p> -<p> - The following Java snippet demonstrates loading an {@link android.widget.ImageView ImageView} object with a single bitmap from a list of bitmap resources. ImageView is a basic display rectangle for graphics (animations or still images). -</p> -<pre> -// Load an array with BitmapDrawable resources. -private Integer[] mThumbIds = { - R.drawable.sample_thumb_0, - R.drawable.sample_thumb_1, - R.drawable.sample_thumb_2, - R.drawable.sample_thumb_3, - R.drawable.sample_thumb_4 -}; - -// Load and return a view with an image. -public View getView(int position, ViewGroup parent) -{ - ImageView i = new ImageView(mContext); - i.setImageResource(mThumbIds[position]); - i.setAdjustViewBounds(true); - i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); - i.setBackground(android.R.drawable.picture_frame); - return i; -} -</pre> -<p> - This XML example demonstrates loading a bitmap file (chat_icon.png) in an ImageView. -</p> -<pre> -<ImageView id="@+id/icon" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:tint="#FF000000" - android:src="@drawable/chat_icon"/> -</pre> -<a name="colordrawableresources" id="colordrawableresources"></a> -<h3>Color Drawables</h3> +<p>For more discussion and examples using drawable resources, see the discussion in <a href="{@docRoot}guide/topics/graphics/2d-graphics.html#drawable-resource#drawables">2D Graphics</a>.</p> + + +<h3 id="colordrawableresources">Color Drawables</h3> <p>You can create a {@link android.graphics.drawable.PaintDrawable} object that is a rectangle of color, with optionally rounded corners. This element can be defined in any of the files inside res/values/.</p> @@ -465,7 +452,7 @@ version="1.0" encoding="utf-8"?></code> declaration, and a root <code><resources></code> element containing one or more <code><drawable></code> tags.</p> <p> - <strong>Resource source file location</strong>: res/values/colors.xml (File name is arbitrary; standard practice is to put the PaintDrawable items in the file along with the <a href="{@docRoot}devel/resources-i18n.html#numericcolorresources">numeric color values</a>.) + <strong>Resource source file location</strong>: res/values/colors.xml (File name is arbitrary; standard practice is to put the PaintDrawable items in the file along with the <a href="resources-i18n.html#numericcolorresources">numeric color values</a>.) </p> <p> <strong>Compiled resource datatype:</strong> Resource pointer to a {@link android.graphics.drawable.PaintDrawable}. @@ -536,8 +523,8 @@ tv.setBackground(redDrawable); android:background="@drawable/solid_red"/> </pre> -<a name="ninepatch" id="ninepatch"></a> -<h3>Nine-Patch Stretchable Image</h3> + +<h3 id="ninepatch">Nine-Patch (stretchable) Images</h3> <p> Android supports a stretchable bitmap image, called a {@link android.graphics.NinePatch} graphic. This is a PNG image in which @@ -547,40 +534,7 @@ tv.setBackground(redDrawable); of a stretchable image is the button backgrounds that Android uses; buttons must stretch to accommodate strings of various lengths. </p> -<p> - A NinePatch drawing is a standard PNG image that includes a 1 pixel wide - border. This border is used to define the stretchable and static areas of - the screen. You indicate a stretchable section by drawing one or more 1 pixel - wide black lines in the left or top part of this border. You can have as - many stretchable sections as you want. The relative size of the stretchable - sections stays the same, so the largest sections always remain the largest. -</p> -<p> - You can also define an optional drawable section of the image (effectively, - the padding lines) by drawing a line on the right and bottom lines. If you - do not draw these lines, the first top and left lines will be used. -</p> -<p> - If a View object sets this graphic as a background and then specifies the - View object's text, it will stretch itself so that all the text fits inside - the area designated by the right and bottom lines (if included). If the - padding lines are not included, Android uses the left and top lines to - define the writeable area. -</p> -<p>The <a href="{@docRoot}reference/draw9patch.html">Draw 9-patch</a> tool offers - an extremely handy way to create your NinePatch images, using a - WYSIWYG graphics editor. -</p> -<p> - Here is a sample NinePatch file used to define a button. -</p> -<p> - <img src="{@docRoot}images/ninepatch_raw.png" alt="Raw ninepatch file - showing the definition lines"> -</p> -<p> - This ninepatch uses one single stretchable area, and it also defines a drawable area. -</p> + <p> <strong>Source file format:</strong> PNG — one resource per file </p> @@ -601,44 +555,16 @@ tv.setBackground(redDrawable); <strong>XML</strong> <code>@[<em>package</em>:]drawable.<em>some_file</em></code> </li> </ul> -<p> - <strong>Example XML Code</strong> -</p> -<p> - Note that the width and height are set to "wrap_content" to make the button fit neatly around the text. -</p> -<pre> -<Button id="@+id/tiny" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:layout_alignParentTop="true" - android:layout_centerInParent="true" - android:text="Tiny" - android:textSize="8sp" - android:background="@drawable/my_button_background"/> - -<Button id="@+id/big" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:layout_alignParentBottom="true" - android:layout_centerInParent="true" - android:text="Biiiiiiig text!" - android:textSize="30sp" - android:background="@drawable/my_button_background"/> -</pre> -<p> - Here are the two buttons based on this XML and the NinePatch graphic shown above. Notice how the width and height of the button varies with the text, and the background image stretches to accommodate it. -</p> -<p> - <img src="{@docRoot}images/ninepatch_examples.png" alt="Two buttons based on the NinePatch button background"> -</p> -<a name="animation" id="animation"></a> -<h2>Animation</h2> -<a name="tweenedanimation" id="tweenedanimation"></a> -<h3> - Tweened Animation -</h3> + +<p>For more information and examples using NinePatch drawables, see the discussion +in <a href="{@docRoot}guide/topics/graphics/2d-graphics.html#nine-patch">2D Graphics</a>.</p> + + + +<h2 id="animation">Animation</h2> + +<h3 id="tweenedanimation">Tweened Animation</h3> <p> Android can perform simple animation on a graphic, or a series of graphics. These include rotations, fading, moving, and stretching. </p> @@ -666,7 +592,7 @@ tv.setBackground(redDrawable); <strong>Syntax</strong> </p> <p> - The file must have a single root element: this will be either a single <code><alpha></code>, <code><scale></code>, <code><translate></code>, <code><rotate></code>, interpolator element, or <code><set></code> element that holds groups of these elements (which may include another <code><set></code>). By default, all elements are applied simultaneously. To have them occur sequentially, you must specify the <code>startOffset</code> attribute, as shown in the example code. + The file must have a single root element: this will be either a single <code><alpha></code>, <code><scale></code>, <code><translate></code>, <code><rotate></code>, interpolator element, or <code><set></code> element that holds groups of these elements (which may include another <code><set></code>). By default, all elements are applied simultaneously. To have them occur sequentially, you must specify the <code>startOffset</code> attribute. </p> <pre> <set android:shareInterpolator=boolean> // Only required if multiple tags are used. @@ -677,15 +603,15 @@ tv.setBackground(redDrawable); android:fromYScale=float android:toYScale=float android:pivotX=string - android:pivotY=string> | + android:pivotY=string > | <translate android:fromX=string android:toX=string android:fromY=string - android:toY=string> | + android:toY=string > | <rotate android:fromDegrees=float android:toDegrees=float android:pivotX=string - android:pivotY=string /> | + android:pivotY=string > | <<em>interpolator tag</em>> <set> </set> @@ -828,71 +754,41 @@ Supports the following attributes in any of the following three formats: values You can optionally set an interpolator for each element to determine how quickly or slowly it performs its effect over time. For example, slow at the beginning and faster at the end for EaseInInterpolator, and the reverse for EaseOutInterpolator. A list of interpolators is given in {@link android.R.anim}. To specify these, use the syntax @android:anim/<em>interpolatorName</em>. </dd> </dl> -<p> - <strong>Example XML Declaration</strong> -</p> -<p> - The following XML from the ApiDemos application is used to stretch, then simultaneously spin and rotate a block of text. -</p> -<pre> -<set android:shareInterpolator="false"> - <scale - android:interpolator="@android:anim/ease_in_out_interpolator" - android:fromXScale="1.0" - android:toXScale="1.4" - android:fromYScale="1.0" - android:toYScale="0.6" - android:pivotX="50%" - android:pivotY="50%" - android:fillAfter="false" - android:duration="700" /> - <set android:interpolator="@android:anim/ease_in_interpolator"> - <scale - android:fromXScale="1.4" - android:toXScale="0.0" - android:fromYScale="0.6" - android:toYScale="0.0" - android:pivotX="50%" - android:pivotY="50%" - android:startOffset="700" - android:duration="400" - android:fillBefore="false" /> - <rotate - android:fromDegrees="0" - android:toDegrees="-45" - android:toYScale="0.0" - android:pivotX="50%" - android:pivotY="50%" - android:startOffset="700" - android:duration="400" /> - </set> -</set> -</pre> -<p> - The following Java code loads animations called res/anim/hyperspace_in.xml and res/anim/hyperspace_out.xml into a {@link android.widget.ViewFlipper}. -</p> -<pre> -mFlipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.hyperspace_in)); -mFlipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.hyperspace_out)); -</pre> -<a name="layoutresources" id="layoutresources"></a> -<h2>Layout</h2> -<p> - Android lets you specify screen layouts using XML elements inside an XML file, similar to designing screen layout for a webpage in an HTML file. Each file contains a whole screen or a part of a screen, and is compiled into a View resource that can be passed in to {@link android.app.Activity#setContentView(int) Activity.setContentView} or used as a reference by other layout resource elements. Files are saved in the res/layout/ folder of your project, and compiled by the Android resource compiler aapt. -</p> -<p> - Every layout XML file must evaluate to a single root element. First we'll describe how to use the standard XML tags understood by Android as it is shipped, and then we'll give a little information on how you can define your own custom XML elements for custom View objects. See <a href="{@docRoot}devel/implementing-ui.html">Implementing a User Interface</a> for details about the visual elements that make up a screen. -</p> -<p> - The root element must have the Android namespace "http://schemas.android.com/apk/res/android" defined in the root element -</p> -<p> - <strong>Source file format:</strong> XML file requiring a <code><?xml version="1.0" encoding="utf-8"?></code> declaration, and a root element of one of the supported XML layout elements. -</p> -<p> - <strong>Resource file location</strong>: res/layout/<em>some_file</em>.xml. -</p> +<p>For animation code samples, see the discussion in the +<a href="{@docRoot}guide/topics/graphics/2d-graphics.html">2D Graphics</a> topic.</p> + + +<h2 id="layoutresources">Layout</h2> +<p>Android lets you specify screen layouts using XML elements inside an XML +file, similar to designing screen layout for a webpage in an HTML file. Each +file contains a whole screen or a part of a screen, and is compiled into a +View resource that can be passed in to +{@link android.app.Activity#setContentView(int) Activity.setContentView} or used as a +reference by other layout resource elements. Files are saved in the +<code>res/layout/</code> folder of your project, and compiled by the Android resource +compiler, aapt. </p> + +<p> Every layout XML file must evaluate to a single root +element. First we'll describe how to use the standard XML tags understood by +Android as it is shipped, and then we'll give a little information on how you +can define your own custom XML elements for custom View objects. + +<p> The root element must have +the Android namespace "http://schemas.android.com/apk/res/android" defined in +the root element.</p> + +<p>For a complete discussion on creating layouts, see the +<a href="{@docRoot}guide/topics/views/index.html">Views and Layout</a> topic.</p> + +<p> <strong>Source file format:</strong> XML file +requiring a <code><?xml version="1.0" encoding="utf-8"?></code> +declaration, and a root element of one of the supported XML layout elements. +</p> + + +<p><strong>Resource file location</strong>: +res/layout/<em>some_file</em>.xml.</p> <p> <strong>Compiled resource datatype:</strong> Resource pointer to a {@link android.view.View} (or subclass) resource. </p> @@ -977,7 +873,7 @@ mFlipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.hyperspace_ou <strong>Attributes exposed by all the superclasses of that element.</strong> For example, the TextView class extends the View class, so the <code><TextView></code> element supports all the attributes that the <code><View></code> element exposes — a long list, including <code>View_paddingBottom</code> and <code>View_scrollbars</code>. These too are used without the class name: <code><TextView android:paddingBottom="20" android:scrollbars="horizontal" /></code>. </li> <li> - <strong>Attributes of the object's {@link android.view.ViewGroup.LayoutParams} subclass.</strong> All View objects support a LayoutParams member (see <a href="{@docRoot}devel/ui/layout.html">LayoutParams in Implementing a UI</a>). To set properties on an element's LayoutParams member, the attribute to use is "android:layout_<em>layoutParamsProperty</em>". For example: <code>android:layout_gravity</code> for an object wrapped by a <code><LinearLayout></code> element. Remember that each LayoutParams subclass also supports inherited attributes. Attributes exposed by each subclass are given in the format <em>someLayoutParamsSubclass</em>_Layout_layout_<em>someproperty</em>. This defines an attribute "android:layout_<em>someproperty</em>". Here is an example of how Android documentation lists the properties of the {@link android.widget.LinearLayout.LayoutParams LinearLayout.LayoutParams} class: + <strong>Attributes of the object's {@link android.view.ViewGroup.LayoutParams} subclass.</strong> All View objects support a LayoutParams member (see <a href="{@docRoot}guide/topics/views/layout.html">LayoutParams in Implementing a UI</a>). To set properties on an element's LayoutParams member, the attribute to use is "android:layout_<em>layoutParamsProperty</em>". For example: <code>android:layout_gravity</code> for an object wrapped by a <code><LinearLayout></code> element. Remember that each LayoutParams subclass also supports inherited attributes. Attributes exposed by each subclass are given in the format <em>someLayoutParamsSubclass</em>_Layout_layout_<em>someproperty</em>. This defines an attribute "android:layout_<em>someproperty</em>". Here is an example of how Android documentation lists the properties of the {@link android.widget.LinearLayout.LayoutParams LinearLayout.LayoutParams} class: </li> </ul> <ul> @@ -1037,8 +933,12 @@ setContentView(R.layout.main_screen); <p> However, layout elements can also represent repeating elements used as templates. </p> -<a name="customresources" id="customresources"></a> -<h3>Custom Layout Resources</h3> + +<p>Also see <a href="{@docRoot}guide/topics/views/index.html">Views and Layout</a> for more information on layouts.</p> + + + +<h3 id="customresources">Custom Layout Resources</h3> <p> You can define custom elements to use in layout resources. These custom elements can then be used the same as any Android layout elements: that is, you can use them and specify their attributes in other resources. The ApiDemos sample application has an example of creating a custom layout XML tag, LabelView. To create a custom element, you will need the following files: </p> @@ -1066,8 +966,9 @@ setContentView(R.layout.main_screen); <strong>Resource reference name:</strong> R.styleable.<em>some_file</em> (Java). </p> -<a name="stylesandthemes" id="stylesandthemes"></a> -<h2>Styles and Themes</h2> + + +<h2 id="stylesandthemes">Styles and Themes</h2> <p> A <em>style</em> is one or more attributes applied to a single element (for example, 10 point red Arial font, applied to a TextView). A style is applied as an attribute to an element in a layout XML file. </p> @@ -1075,8 +976,12 @@ setContentView(R.layout.main_screen); A <em>theme</em> is one or more attributes applied to a whole screen — for example, you might apply the stock Android Theme.dialog theme to an activity designed to be a floating dialog box. A theme is assigned as an attribute to an Activity in the manifest file. </p> <p> - Both styles and themes are defined in a <style> block containing one or more string or numerical values (typically color values), or references to other resources (drawables and so on). These elements support inheritance, so you could have MyBaseTheme, MyBaseTheme.Fancy, MyBaseTheme.Small, and so on. + Both styles and themes are defined in a <code><style></code> block containing one or more string or numerical values (typically color values), or references to other resources (drawables and so on). These elements support inheritance, so you could have MyBaseTheme, MyBaseTheme.Fancy, MyBaseTheme.Small, and so on. </p> + +<p>For a complete discussion on styles and themes, read +<a href="{@docRoot}guide/topics/views/themes.html">Applying Styles and Themes</a>.</p> + <p> <strong>Source file format:</strong> XML file requiring a <code><?xml version="1.0" encoding="utf-8"?></code> declaration, and a root <code><resources></code> element containing one or more <code><style></code> tags. </p> @@ -1127,85 +1032,6 @@ setContentView(R.layout.main_screen); A value to use in this theme. It can be a standard string, a hex color value, or a reference to any other resource type. </dd> </dl> -<p> - <strong>Example: Declaring a Style in XML</strong> -</p> -<pre> -<?xml version="1.0" encoding="utf-8"?> -<resources> - <style name="SpecialText"> - <item name="android:textSize">18sp</item> - <item name="android:textColor">#008</item> - </style> -</resources> -</pre> -<p> - <strong>Example: Referencing a Declared Style from an XML Resource</strong> -</p> -<p> - The following layout XML file applies the previously defined style to a single text box. -</p> -<pre> -<!-- MainPageLayout.xml --> -<?xml version="1.0" encoding="utf-8"?> -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" - android:layout_height="fill_parent" - android:layout_width="fill_parent" - android:orientation="vertical" - android:scrollbars="vertical" - id="main_frame"> - <EditText id="@+id/text1" - style="@style/SpecialText" - android:layout_width="fill_parent" - android:layout_height="wrap_content" - android:text="Hello, World!" /> -</LinearLayout> -</pre> - -<p> - <strong>Example XML Declaration of a Theme</strong> -</p> -<p> - The following example defines a theme, "ThemeNew," which creates new theme items, - refers to some previously defined theme items (values beginning with '@'), - and refers to package resources (values beginning with '?'). -</p> -<pre> -<style name="ThemeNew"> - <item name="windowFrame">@drawable/screen_frame</item> - <item name="windowBackground">@drawable/screen_background_white</item> - <item name="panelForegroundColor">#FF000000</item> - <item name="panelBackgroundColor">#FFFFFFFF</item> - <item name="panelTextColor">?panelForegroundColor</item> - <item name="panelTextSize">14</item> - <item name="menuItemTextColor">?panelTextColor</item> - <item name="menuItemTextSize">?panelTextSize</item> -</style> -</pre> -<p> - Notice that, to reference a value from the currently loaded theme, we use - a question-mark (?) instead of the at-symbol (@), in the reference string. - You must refer to such a specific <code><item></code> by its name in - the currently loaded theme. This can be used in XML resources only. -</p> - -<p> - <strong>Example Code Use of a Theme</strong> -</p> -<p> - The following Java snippet demonstrates loading a style set (i.e., a theme). -</p> -<pre> -setTheme(R.style.ThemeNew); -</pre> -<p> - The following XML applies an Android theme to a whole file (in this case, the Android dialog theme, to make the screen a floating dialog screen). -</p> -<pre> -<!-- AndroidManifest.xml --> -<manifest xmlns:android="http://schemas.android.com/apk/res/android" - package="com.example.codelab.rssexample"> - <activity class="AddRssItem" android:label="@string/add_item_label" android:theme="@android:style/Theme.Dialog"/> -</manifest> -</pre> +<p>For examples of how to declare and apply styles and themes, read +<a href="{@docRoot}guide/topics/views/themes.html">Applying Styles and Themes</a>.</p> diff --git a/docs/html/guide/topics/resources/index.jd b/docs/html/guide/topics/resources/index.jd new file mode 100644 index 0000000..7e3bce42 --- /dev/null +++ b/docs/html/guide/topics/resources/index.jd @@ -0,0 +1,40 @@ +page.title=Resources and Assets +@jd:body + +<div id="qv-wrapper"> +<div id="qv"> + + <h2>Key classes</h2> + <ol> + <li>{@link android.content.res.Resources}</li> + <li>{@link android.content.res.AssetManager}</li> + </ol> + +</div> +</div> + +<p>Resources are an integral part of an Android application. +In general, these are external elements that you want to include and reference within your application, +like images, audio, video, text strings, layouts, themes, etc. Every Android application contains +a directory for resources (<code>res/</code>) and a directory for assets (<code>assets/</code>). +Assets are used less often, because their applications are far fewer. You only need to save data +as an asset when you need to read the raw bites. +The directories for resources and assets both reside at the top of your project directory, alongside your source code directory +(<code>src/</code>).</p> + +<p>The difference between "resources" and "assets" isn't much on the surface, but in general, +you'll use resources to store your external content much more often than you'll use assets. +The real difference is that anything +placed in the resources directory will be easily accessible from your application from the +<code>R</code> class, which is compiled by Android. Whereas, anything placed in the assets +directory will maintain its raw file format and, in order to read it, you must use the +{@link android.content.res.AssetManager} to read the file as a stream of bytes. So keeping +files and data in resources (<code>res/</code>) makes them easily accessible.</p> + +<p>Within the documents of this topic, you'll find information on the kinds of standard resources +that are typically used in an Android application and how to reference them from you code. +<a href="{@docRoot}guide/topics/resources/resources-i18n.html">Resources and Internationalization</a> +is where you should start, to learn more about how Android utilizes project resources. Then, the +<a href="{@docRoot}guide/topics/resources/available-resources.html">Available Resource Types</a> +document offers a summary of various resource types and a reference to their specifications. +</p> diff --git a/docs/html/guide/topics/resources/resources-i18n.jd b/docs/html/guide/topics/resources/resources-i18n.jd index d3ddd23..8a9bd43 100755..100644 --- a/docs/html/guide/topics/resources/resources-i18n.jd +++ b/docs/html/guide/topics/resources/resources-i18n.jd @@ -1,6 +1,34 @@ -page.title=Resources and i18n +page.title=Resources and Internationalization +parent.title=Resources and Assets +parent.link=index.html @jd:body -<h1>Resources and Internationalization</h1> + +<div id="qv-wrapper"> +<div id="qv"> + + <h2>Key classes</h2> + <ol> + <li>{@link android.content.res.Resources}</li> + </ol> + + <h2>In this document</h2> + <ol> + <li><a href="#intro">Introduction</a></li> + <li><a href="#CreatingResources">Creating Resources</a></li> + <li><a href="#UsingResources">Using Resources</a> + <ol> + <li><a href="#ResourcesInCode">Using Resources in Code</a></li> + <li><a href="#ReferencesToResources">References to Resources</a></li> + <li><a href="#ReferencesToThemeAttributes">References to Theme Attributes</a></li> + <li><a href="#UsingSystemResources">Using System Resources</a></li> + </ol> + </li> + <li><a href="#AlternateResources">Alternate Resources</a></li> + <li><a href="#ResourcesTerminology">Terminology</a></li> + <li><a href="#i18n">Internationalization (I18N)</a></li> + </ol> +</div> +</div> <p>Resources are external files (that is, non-code files) that are used by your code and compiled into your application at build time. Android @@ -13,41 +41,19 @@ a binary, fast loading format for efficiency reasons. Strings, likewise are comp into a more efficient storage form. It is for these reasons that we have these different resource types in the Android platform.</p> -<p>This document contains the following sections:</p> - -<ul> - <li> <a href="#Resources">Resources</a> - <ul> - <li> <a href="#CreatingResources">Creating Resources</a></li> - <li> <a href="#UsingResources">Using Resources</a> - <ul> - <li><a href="#ResourcesInCode">Using Resources in Code</a></li> - <li> <a href="#ReferencesToResources">References to Resources</a></li> - <li> <a href="#ReferencesToThemeAttributes">References to Theme Attributes</a></li> - <li> <a href="#UsingSystemResources">Using System Resources</a></li> - </ul> - </li> - <li><a href="#AlternateResources">Alternate Resources</a></li> - <li><a href="{@docRoot}reference/available-resources.html"> - Resource Reference</a></li> - <li> <a href="#ResourcesTerminology">Terminology</a></li> - </ul> - </li> - <li><a href="#i18n">Internationalization (I18N)</a></li> -</ul> <p>This is a fairly technically dense document, and together with the -<a href="{@docRoot}reference/available-resources.html">Resource Reference</a> +<a href="available-resources.html">Available Resources</a> document, they cover a lot of information about resources. It is not necessary to know this document by heart to use Android, but rather to know that the information is here when you need it.</p> -<a name="Resources"></a> -<h2>Resources</h2> +<a name="intro"></a> +<h2>Introduction</h2> <p>This topic includes a terminology list associated with resources, and a series of examples of using resources in code. For a complete guide to the supported Android resource types, see - <a href="{@docRoot}reference/available-resources.html">Resources</a>. + <a href="available-resources.html">Available Resources</a>. </p> <p>The Android resource system keeps track of all non-code assets associated with an application. You use the @@ -84,7 +90,7 @@ subdirectory under the <code>res/</code> directory in your project. Android has a resource compiler (aapt) that compiles resources according to which subfolder they are in, and the format of the file. Here is a list of the file types for each resource. See the -<a href="{@docRoot}reference/available-resources.html">resource reference</a> for +<a href="available-resources.html">Available Resources</a> for descriptions of each type of object, the syntax, and the format or syntax of the containing file.</p> @@ -96,9 +102,9 @@ the containing file.</p> <tr> <td><code>res/anim/</code></td> <td>XML files that are compiled into - <a href="{@docRoot}reference/available-resources.html#animationdrawable">frame by + <a href="available-resources.html#animationdrawable">frame by frame animation</a> or - <a href="{@docRoot}reference/available-resources.html#tweenedanimation">tweened + <a href="available-resources.html#tweenedanimation">tweened animation</a> objects </td> </tr> <tr> @@ -107,14 +113,14 @@ the containing file.</p> Drawable resource subtypes:</p> <p>To get a resource of this type, use <code>Resource.getDrawable(<em>id</em>)</code> <ul> - <li><a href="{@docRoot}reference/available-resources.html#imagefileresources">bitmap files</a></li> - <li><a href="{@docRoot}reference/available-resources.html#ninepatch">9-patches (resizable bitmaps)</a></li> + <li><a href="available-resources.html#imagefileresources">bitmap files</a></li> + <li><a href="available-resources.html#ninepatch">9-patches (resizable bitmaps)</a></li> </ul></td> </tr> <tr> <td><code>res/layout/</code></td> <td>XML files that are compiled into screen layouts (or part of a screen). - See <a href="{@docRoot}devel/ui/xml.html">layouts</a></td> + See <a href="{@docRoot}guide/topics/views/declaring-layout.html">Declaring Layout</a></td> </tr> <tr> <td><code>res/values/</code></td> @@ -129,19 +135,19 @@ the containing file.</p> <ul> <li><strong>arrays.xml</strong> to define arrays </li> <!-- TODO: add section on arrays --> - <li><strong>colors.xml</strong> to define <a href="{@docRoot}reference/available-resources.html#colordrawableresources">color + <li><strong>colors.xml</strong> to define <a href="available-resources.html#colordrawableresources">color drawables</a> and <a href="#colorvals">color string values</a>. Use <code>Resources.getDrawable()</code> and <code>Resources.getColor(), respectively,</code> to get these resources.</li> - <li><strong>dimens.xml</strong> to define <a href="{@docRoot}reference/available-resources.html#dimension">dimension value</a>. Use <code>Resources.getDimension()</code> to get + <li><strong>dimens.xml</strong> to define <a href="available-resources.html#dimension">dimension value</a>. Use <code>Resources.getDimension()</code> to get these resources.</li> - <li><strong>strings.xml</strong> to define <a href="{@docRoot}reference/available-resources.html#stringresources">string</a> values (use either + <li><strong>strings.xml</strong> to define <a href="available-resources.html#stringresources">string</a> values (use either <code>Resources.getString</code> or preferably <code>Resources.getText()</code> to get these resources. <code>getText()</code> will retain any rich text styling which is usually desirable for UI strings.</li> - <li><strong>styles.xml</strong> to define <a href="{@docRoot}reference/available-resources.html#stylesandthemes">style</a> objects.</li> + <li><strong>styles.xml</strong> to define <a href="available-resources.html#stylesandthemes">style</a> objects.</li> </ul></td> </tr> <tr> @@ -233,8 +239,7 @@ defined in XML files, or the file name (without the extension) for resources defined by other file types. Each type of resource will be added to a specific R subclass, depending on the type of resource it is; to learn which R subclass hosts your compiled resource type, consult the -<a href="{@docRoot}reference/available-resources.html">resource -reference</a> document. Resources compiled by your own application can +<a href="available-resources.html">Available Resources</a> document. Resources compiled by your own application can be referred to without a package name (simply as <code>R.<em>resource_type</em>.<em>resource_name</em></code>). Android contains a number of standard resources, such as screen styles and button backgrounds. To @@ -273,7 +278,7 @@ can be localized) and images (which exist in another file), though a reference can be any resource type including colors and integers.</p> <p>For example, if we have -<a href="{@docRoot}reference/available-resources.html#colordrawableresources">color +<a href="available-resources.html#colordrawableresources">color resources</a>, we can write a layout file that sets the text color size to be the value contained in one of those resources:</p> @@ -394,7 +399,7 @@ public class MyActivity extends Activity </pre> <a name="AlternateResources" id="AlternateResources"></a> -<h2>Supporting Alternate Resources for Alternate Languages and Configurations</h2> +<h2>Alternate Resources (for alternate languages and configurations)</h2> <p>You can supply different resources for your product according to the UI language or hardware configuration on the device. Note that although you can @@ -485,7 +490,7 @@ MyApp/ <tr> <td>Primary non-touchscreen<br /> navigation method</td> - <td><code>notouch</code>, <code>dpad</code>, <code>trackball</code>, <code>wheel</code> </td> + <td><code>nonav</code>, <code>dpad</code>, <code>trackball</code>, <code>wheel</code> </td> </tr> <tr> <td>Screen dimensions</td> @@ -684,7 +689,7 @@ user to select between different global appearances of their device, or download files with new appearances.</p> <h2>Resource Reference</h2> -<p>The <a href="{@docRoot}reference/available-resources.html">Resource Reference</a> +<p>The <a href="available-resources.html">Available Resources</a> document provides a detailed list of the various types of resource and how to use them from within the Java source code, or from other references.</p> diff --git a/docs/html/guide/topics/security/security.jd b/docs/html/guide/topics/security/security.jd index 4b258e0..da201c4 100644 --- a/docs/html/guide/topics/security/security.jd +++ b/docs/html/guide/topics/security/security.jd @@ -1,31 +1,34 @@ page.title=Security and Permissions @jd:body -<p>Android is a multi-process system, where each application (and parts of the -system) runs in its own process. Most security between applications and -the system is enforced at the process level through standard Linux facilities, -such as user and group IDs that are assigned to applications. -Additional finer-grained security features are provided -through a "permission" mechanism that enforces restrictions on the specific -operations that a particular process can perform, and per-URI permissions -for granting ad-hoc access to specific pieces of data.</p> +<div id="qv-wrapper"> +<div id="qv"> -<p>This document covers these topics: </p> - -<ul> +<h2>In this document</h2> +<ol> <li><a href="#arch">Security Architecture</a></li> <li><a href="#signing">Application Signing</a></li> <li><a href="#userid">User IDs and File Access</a></li> <li><a href="#permissions">Using Permissions</a></li> <li><a href="#declaring">Declaring and Enforcing Permissions</a> - <ul> - <li><a href="#manifest">Enforcing Permissions in AndroidManifest.xml</a></li> - <li><a href="#broadcasts">Enforcing Permissions when Sending Broadcasts</a></li> + <ol> + <li><a href="#manifest">...in AndroidManifest.xml</a></li> + <li><a href="#broadcasts">...when Sending Broadcasts</a></li> <li><a href="#enforcement">Other Permission Enforcement</a></li> - </ul></li> -<li>><a href="#uri">URI Permissions</a></li> -</ul> + </ol></li> +<li><a href="#uri">URI Permissions</a></li> +</ol> +</div> +</div> +<p>Android is a multi-process system, in which each application (and parts of the +system) runs in its own process. Most security between applications and +the system is enforced at the process level through standard Linux facilities, +such as user and group IDs that are assigned to applications. +Additional finer-grained security features are provided +through a "permission" mechanism that enforces restrictions on the specific +operations that a particular process can perform, and per-URI permissions +for granting ad-hoc access to specific pieces of data.</p> <a name="arch"></a> <h2>Security Architecture</h2> diff --git a/docs/html/guide/topics/sensors/accelerometer.jd b/docs/html/guide/topics/sensors/accelerometer.jd new file mode 100644 index 0000000..da760bc --- /dev/null +++ b/docs/html/guide/topics/sensors/accelerometer.jd @@ -0,0 +1,18 @@ +page.title=Accelerometer +parent.title=Sensors +parent.link=index.html +@jd:body + +<div id="qv-wrapper"> +<div id="qv"> + + <h2>In this document</h2> + <ol> + + </ol> + +</div> +</div> + + +TODO
\ No newline at end of file diff --git a/docs/html/guide/topics/sensors/camera.jd b/docs/html/guide/topics/sensors/camera.jd new file mode 100644 index 0000000..821333e --- /dev/null +++ b/docs/html/guide/topics/sensors/camera.jd @@ -0,0 +1,18 @@ +page.title=Camera +parent.title=Sensors +parent.link=index.html +@jd:body + +<div id="qv-wrapper"> +<div id="qv"> + + <h2>Key class</h2> + <ol> + <li>{@link android.hardware.Camera android.hardware.Camera}</li> + </ol> + <h2>In this document</h2> + <ol> + <li>TODO</li> + </ol> +</div> +</div>
\ No newline at end of file diff --git a/docs/html/guide/topics/sensors/compass.jd b/docs/html/guide/topics/sensors/compass.jd new file mode 100644 index 0000000..1e45d2d --- /dev/null +++ b/docs/html/guide/topics/sensors/compass.jd @@ -0,0 +1,18 @@ +page.title=Compass +parent.title=Sensors +parent.link=index.html +@jd:body + +<div id="qv-wrapper"> +<div id="qv"> + + <h2>In this document</h2> + <ol> + + </ol> + +</div> +</div> + + +TODO
\ No newline at end of file diff --git a/docs/html/guide/topics/sensors/index.jd b/docs/html/guide/topics/sensors/index.jd new file mode 100644 index 0000000..54a0814 --- /dev/null +++ b/docs/html/guide/topics/sensors/index.jd @@ -0,0 +1,13 @@ +page.title=Sensors +@jd:body + +<div id="qv-wrapper"> +<div id="qv"> + + + +<h2>Accelerometer</h2> +<p>The accelerometer sensors allow you to detect the various movements of the device.</p> + +<h2>Compass</h2> +<p>The compass provides data on the devices current polar orientation.</p>
\ No newline at end of file diff --git a/docs/html/guide/topics/views/binding.jd b/docs/html/guide/topics/views/binding.jd index e6fa3ea..ce57ac4 100644 --- a/docs/html/guide/topics/views/binding.jd +++ b/docs/html/guide/topics/views/binding.jd @@ -1,7 +1,27 @@ page.title=Binding to Data with AdapterView +parent.title=Views and Layout +parent.link=index.html @jd:body -<p>Some types of ViewGroup objects have a UI that is visible on the screen — {@link android.widget.AdapterView AdapterView} is one such object. AdapterView is a ViewGroup subclass whose child Views are determined by an {@link android.widget.Adapter Adapter} that binds to data of some type. AdapterView is useful whenever you need to display stored data (versus resource strings or drawables) in your layout.</p> +<div id="qv-wrapper"> +<div id="qv"> + <h2>In this document</h2> + <ol> + <li><a href="#FillingTheLayout">Filling the Layout with Data</a></li> + <li><a href="#HandlingUserSelections">Handling User Selections</a></li> + </ol> + + <h2>See also</h2> + <ol> + <li><a href="{@docRoot}guide/tutorials/views/hello-spinner.html">Hello Spinner tutorial</a></li> + <li><a href="{@docRoot}guide/tutorials/views/hello-listview.html">Hello ListView tutorial</a></li> + <li><a href="{@docRoot}guide/tutorials/views/hello-gridview.html">Hello GridView tutorial</a></li> + </ol> +</div> +</div> + +<p>The {@link android.widget.AdapterView} is a ViewGroup subclass whose child Views are determined by an {@link android.widget.Adapter Adapter} that +binds to data of some type. AdapterView is useful whenever you need to display stored data (as opposed to resource strings or drawables) in your layout.</p> <p>{@link android.widget.Gallery Gallery}, {@link android.widget.ListView ListView}, and {@link android.widget.Spinner Spinner} are examples of AdapterView subclasses that you can use to bind to a specific type of data and display it in a certain way. </p> @@ -14,15 +34,18 @@ page.title=Binding to Data with AdapterView </li> </ul> -<p>The sections below describe how the AdapterView fulfills those responsibilities.</p> - -<h3> - Filling the layout with data -</h3> -<p>This is typically done by binding the class to an {@link -android.widget.Adapter} that gets its data from somewhere — either a list that -the code supplies, or query results from the device's database. </p> +<h2 id="FillingTheLayout">Filling the Layout with Data</h2> +<p>Inserting data into the layout is typically done by binding the AdapterView class to an {@link +android.widget.Adapter}, which retireves data from an external source (perhaps a list that +the code supplies or query results from the device's database). </p> +<p>The following code sample does the following:</p> +<ol> + <li>Creates a {@link android.widget.Spinner Spinner} with an existing View and binds it to a new ArrayAdapter +that reads an array of colors from the local resources.</li> + <li>Creates another Spinner object from a View and binds it to a new SimpleCursorAdapter that will read +people's names from the device contacts (see {@link android.provider.Contacts.People}).</li> +</ol> <pre> // Get a Spinner and bind it to an ArrayAdapter that @@ -57,10 +80,10 @@ s2.setAdapter(adapter2); <p>Note that it is necessary to have the People._ID column in projection used with CursorAdapter or else you will get an exception.</p> -<h3> - Handling user selections -</h3> -<p> This is done by setting the class's {@link + + +<h2 id="HandlingUserSelections">Handling User Selections</h2> +<p>You handle the user's selecction by setting the class's {@link android.widget.AdapterView.OnItemClickListener} member to a listener and catching the selection changes. </p> <pre> @@ -78,3 +101,10 @@ private OnItemClickListener mMessageClickedHandler = new OnItemClickListener() { mHistoryView = (ListView)findViewById(R.id.history); mHistoryView.setOnItemClickListener(mMessageClickedHandler); </pre> + +<div class="special"> +<p>For more discussion on how to create different AdapterViews, read the following tutorials: +<a href="{@docRoot}guide/tutorials/views/hello-spinner.html">Hello Spinner</a>, +<a href="{@docRoot}guide/tutorials/views/hello-listview.html">Hello ListView</a>, and +<a href="{@docRoot}guide/tutorials/views/hello-gridview.html">Hello GridView</a>. +</div> diff --git a/docs/html/guide/topics/views/custom-components.jd b/docs/html/guide/topics/views/custom-components.jd new file mode 100644 index 0000000..9e7943b --- /dev/null +++ b/docs/html/guide/topics/views/custom-components.jd @@ -0,0 +1,563 @@ +page.title=Building Custom Components +parent.title=Views and Layout +parent.link=index.html +@jd:body + +<div id="qv-wrapper"> +<div id="qv"> + <h2>In this document</h2> + <ol> + <li><a href="#basic">The Basic Approach</a></li> + <li><a href="#custom">Fully Customized Components</a></li> + <li><a href="#compound">Compound Controls</a></li> + <li><a href="#modifying">Modifying an Existing View Type</a></li> + </ol> +</div> +</div> + +<p>Android offers a sophisticated and powerful componentized model for building your UI, +based on the fundamental layout classes: {@link android.view.View} and +{@link android.view.ViewGroup}. To start with, the platform includes a variety of prebuilt +View and ViewGroup subclasses — called widgets and layouts, respectively — +that you can use to construct your UI.</p> + +<p>A partial list of available widgets includes {@link android.widget.Button Button}, +{@link android.widget.TextView TextView}, +{@link android.widget.EditText EditText}, +{@link android.widget.ListView ListView}, +{@link android.widget.CheckBox CheckBox}, +{@link android.widget.RadioButton RadioButton}, +{@link android.widget.Gallery Gallery}, +{@link android.widget.Spinner Spinner}, and the more special-purpose +{@link android.widget.AutoCompleteTextView AutoCompleteTextView}, +{@link android.widget.ImageSwitcher ImageSwitcher}, and +{@link android.widget.TextSwitcher TextSwitcher}. </p> + +<p>Among the layouts available are {@link android.widget.LinearLayout LinearLayout}, +{@link android.widget.FrameLayout FrameLayout}, {@link android.widget.AbsoluteLayout AbsoluteLayout}, +and others. For more examples, see <a href="layout.html">Common Layout Objects</a>.</p> + +<p>If none of the prebuilt widgets or layouts meets your needs, you can create your own View subclass. +If you only need to make small adjustments to an existing widget or layout, you can simply subclass +the widget or layout and override its methods. +</p> + +<p>Creating your own View subclasses gives you precise control over the appearance and function +of a screen element. To give an idea of the control you get with custom views, here are some +examples of what you could do with them:</p> + +<ul> + <li> + You could create a completely custom-rendered View type, for example a "volume + control" knob rendered using 2D graphics, and which resembles an + analog electronic control. + </li> + <li> + You could combine a group of View components into a new single component, perhaps + to make something like a ComboBox (a combination of popup list and free + entry text field), a dual-pane selector control (a left and right pane + with a list in each where you can re-assign which item is in which + list), and so on. + </li> + <li> + You could override the way that an EditText component is rendered on the screen + (the <a href="{@docRoot}guide/samples/NotePad/index.html">Notepad Tutorial</a> uses this to good effect, + to create a lined-notepad page). + </li> + <li> + You could capture other events like key presses and handle them in some custom + way (such as for a game). + </li> +</ul> +<p> +The sections below explain how to create custom Views and use them in your application. +For detailed reference information, see the {@link android.view.View} class. </p> + + +<h2 id="basic">The Basic Approach</h2> + +<p>Here is a high level overview of what you need to know to get started in creating your own +View components:</p> + +<ol> + <li> + Extend an existing {@link android.view.View View} class or subclass + with your own class. + </li> + <li> + Override some of the methods from the superclass. The superclass methods + to override start with '<code>on</code>', for + example, {@link android.view.View#onDraw onDraw()}, + {@link android.view.View#onMeasure onMeasure()}, and + {@link android.view.View#onKeyDown onKeyDown()}. + This is similar to the <code>on...</code> events in {@link android.app.Activity Activity} + or {@link android.app.ListActivity ListActivity} + that you override for lifecycle and other functionality hooks. + <li> + Use your new extension class. Once completed, your new extension class + can be used in place of the view upon which it was based. + </li> +</ol> +<p class="note"><strong>Tip:</strong> + Extension classes can be defined as inner classes inside the activities + that use them. This is useful because it controls access to them but + isn't necessary (perhaps you want to create a new public View for + wider use in your application). +</p> + + + +<h2 id="custom">Fully Customized Components</h2> +<p> +Fully customized components can be used to create graphical components that +appear however you wish. Perhaps a graphical VU +meter that looks like an old analog gauge, or a sing-a-long text view where +a bouncing ball moves along the words so you can sing along with a karaoke +machine. Either way, you want something that the built-in components just +won't do, no matter how you combine them.</p> +<p>Fortunately, you can easily create components that look and behave in any +way you like, limited perhaps only by your imagination, the size of the +screen, and the available processing power (remember that ultimately your +application might have to run on something with significantly less power +than your desktop workstation).</p> +<p>To create a fully customized component:</p> +<ol> + <li> + The most generic view you can extend is, unsurprisingly, {@link + android.view.View View}, so you will usually start by extending this to + create your new super component. + </li> + <li> + You can supply a constructor which can + take attributes and parameters from the XML, and you can also consume + your own such attributes and parameters (perhaps the color and range of + the VU meter, or the width and damping of the needle, etc.) + </li> + <li> + You will probably want to create your own event listeners, + property accessors and modifiers, and possibly more sophisticated + behavior in your component class as well. + </li> + <li> + You will almost certainly want to override <code>onMeasure()</code> and + are also likely to need to override <code>onDraw()</code> if you want + the component to show something. While both have default behavior, + the default <code>onDraw()</code> will do nothing, and the default + <code>onMeasure()</code> will always set a size of 100x100 — which is + probably not what you want. + </li> + <li> + Other <code>on...</code> methods may also be overridden as required. + </li> +</ol> + +<h3>Extend <code>onDraw()</code> and <code>onMeasure()</code></h3> +<p>The <code>onDraw()</code> method delivers you a {@link android.graphics.Canvas Canvas} +upon which you can implement anything you want: 2D graphics, other standard or +custom components, styled text, or anything else you can think of.</p> + +<p class="note"><strong>Note:</strong> +This does not apply to 3D graphics. If you want to +use 3D graphics, you must extend {@link android.view.SurfaceView SurfaceView} +instead of View, and draw from a seperate thread. See the +GLSurfaceViewActivity sample +for details.</p> + +<p><code>onMeasure()</code> is a little more involved. <code>onMeasure()</code> +is a critical piece of the rendering contract between your component and its +container. <code>onMeasure()</code> should be overridden to efficiently and +accurately report the measurements of its contained parts. This is made +slightly more complex by the requirements of limits from the parent +(which are passed in to the <code>onMeasure()</code> method) and by the +requirement to call the <code>setMeasuredDimension()</code> method with the +measured width and height once they have been calculated. If you fail to +call this method from an overridden <code>onMeasure()</code> method, the +result will be an exception at measurement time.</p> +<p>At a high level, implementing <code>onMeasure()</code> looks something + like this:</p> + +<ol> + <li> + The overridden <code>onMeasure()</code> method is called with width and + height measure specifications (<code>widthMeasureSpec</code> and + <code>heightMeasureSpec</code> parameters, both are integer codes + representing dimensions) which should be treated as requirements for + the restrictions on the width and height measurements you should produce. A + full reference to the kind of restrictions these specifications can require + can be found in the reference documentation under {@link + android.view.View#onMeasure View.onMeasure(int, int)} (this reference + documentation does a pretty good job of explaining the whole measurement + operation as well). + </li> + <li> + Your component's <code>onMeasure()</code> method should calculate a + measurement width and height which will be required to render the + component. It should try to stay within the specifications passed in, + although it can choose to exceed them (in this case, the parent can + choose what to do, including clipping, scrolling, throwing an exception, + or asking the <code>onMeasure()</code> to try again, perhaps with + different measurement specifications). + </li> + <li> + Once the width and height are calculated, the <code>setMeasuredDimension(int + width, int height)</code> method must be called with the calculated + measurements. Failure to do this will result in an exception being + thrown. + </li> +</ol> + +<p> +Here's a summary of some of the other standard methods that the framework calls on views: +</p> +<table border="2" width="85%" align="center" cellpadding="5"> + <thead> + <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> + </thead> + + <tbody> + <tr> + <td rowspan="2">Creation</td> + <td>Constructors</td> + <td>There is a form of the constructor that are called when the view + is created from code and a form that is called when the view is + inflated from a layout file. The second form should parse and apply + any attributes defined in the layout file. + </td> + </tr> + <tr> + <td><code>{@link android.view.View#onFinishInflate()}</code></td> + <td>Called after a view and all of its children has been inflated + from XML.</td> + </tr> + + <tr> + <td rowspan="3">Layout</td> + <td><code>{@link android.view.View#onMeasure}</code></td> + <td>Called to determine the size requirements for this view and all + of its children. + </td> + </tr> + <tr> + <td><code>{@link android.view.View#onLayout}</code></td> + <td>Called when this view should assign a size and position to all + of its children. + </td> + </tr> + <tr> + <td><code>{@link android.view.View#onSizeChanged}</code></td> + <td>Called when the size of this view has changed. + </td> + </tr> + + <tr> + <td>Drawing</td> + <td><code>{@link android.view.View#onDraw}</code></td> + <td>Called when the view should render its content. + </td> + </tr> + + <tr> + <td rowspan="4">Event processing</td> + <td><code>{@link android.view.View#onKeyDown}</code></td> + <td>Called when a new key event occurs. + </td> + </tr> + <tr> + <td><code>{@link android.view.View#onKeyUp}</code></td> + <td>Called when a key up event occurs. + </td> + </tr> + <tr> + <td><code>{@link android.view.View#onTrackballEvent}</code></td> + <td>Called when a trackball motion event occurs. + </td> + </tr> + <tr> + <td><code>{@link android.view.View#onTouchEvent}</code></td> + <td>Called when a touch screen motion event occurs. + </td> + </tr> + + <tr> + <td rowspan="2">Focus</td> + <td><code>{@link android.view.View#onFocusChanged}</code></td> + <td>Called when the view gains or loses focus. + </td> + </tr> + + <tr> + <td><code>{@link android.view.View#onWindowFocusChanged}</code></td> + <td>Called when the window containing the view gains or loses focus. + </td> + </tr> + + <tr> + <td rowspan="3">Attaching</td> + <td><code>{@link android.view.View#onAttachedToWindow()}</code></td> + <td>Called when the view is attached to a window. + </td> + </tr> + + <tr> + <td><code>{@link android.view.View#onDetachedFromWindow}</code></td> + <td>Called when the view is detached from its window. + </td> + </tr> + + <tr> + <td><code>{@link android.view.View#onWindowVisibilityChanged}</code></td> + <td>Called when the visibility of the window containing the view + has changed. + </td> + </tr> + </tbody> + + </table> + + + +<h3 id="customexample">A Custom View Example</h3> +<p>The CustomView sample in the +<a href="{@docRoot}guide/samples/ApiDemos/index.html">API Demos</a> provides an example +of a customized View. The custom View is defined in the +<a href="{@docRoot}guide/samples/ApiDemos/src/com/example/android/apis/view/LabelView.html">LabelView</a> +class.</p> +<p>The LabelView sample demonstrates a number of different aspects of custom components:</p> +<ul> + <li>Extending the View class for a completely custom component.</li> + <li>Parameterized constructor that takes the view inflation parameters + (parameters defined in the XML). Some of these are passed through to the + View superclass, but more importantly, there are some custom attributes defined + and used for LabelView.</li> + <li>Standard public methods of the type you would expect to see for a label + component, for example <code>setText()</code>, <code>setTextSize()</code>, + <code>setTextColor()</code> and so on.</li> + <li>An overridden <code>onMeasure</code> method to determine and set the + rendering size of the component. (Note that in LabelView, the real work is done + by a private <code>measureWidth()</code> method.)</li> + <li>An overridden <code>onDraw()</code> method to draw the label onto the + provided canvas.</li> +</ul> +<p>You can see some sample usages of the LabelView custom View in +<a href="{@docRoot}guide/samples/ApiDemos/res/layout/custom_view_1.html">custom_view_1.xml</a> +from the samples. In particular, you can see a mix of both <code>android:</code> +namespace parameters and custom <code>app:</code> namespace parameters. These +<code>app:</code> parameters are the custom ones that the LabelView recognizes +and works with, and are defined in a styleable inner class inside of the +samples R resources definition class.</p> + + +<h2 id="compound">Compound Controls +</h2> +<p>If you don't want to create a completely customized component, but instead +are looking to put together a reusable component that consists of a group of +existing controls, then creating a Compound Component (or Compound Control) might +fit the bill. In a nutshell, this brings together a number of more atomic +controls (or views) into a logical group of items that can be treated as a +single thing. For example, a Combo Box can be thought of as a +combination of a single line EditText field and an adjacent button with an attached + PopupList. If you press the button and select +something from the list, it populates the EditText field, but the user can +also type something directly into the EditText if they prefer.</p> +<p>In Android, there are actually two other Views readily available to do +this: {@link android.widget.Spinner Spinner} and +{@link android.widget.AutoCompleteTextView AutoCompleteTextView}, but +regardless, the concept of a Combo Box makes an easy-to-understand +example.</p> +<p>To create a compound component:</p> +<ol> + <li> + The usual starting point is a Layout of some kind, so create a class + that extends a Layout. Perhaps in the case of a Combo box we might use + a LinearLayout with horizontal orientation. Remember that other layouts + can be nested inside, so the compound component can be arbitrarily + complex and structured. Note that just like with an Activity, you can + use either the declarative (XML-based) approach to creating the + contained components, or you can nest them programmatically from your + code. + </li> + <li> + In the constructor for the new class, take whatever parameters the + superclass expects, and pass them through to the superclass constructor + first. Then you can set up the other views to use within your new + component; this is where you would create the EditText field and the + PopupList. Note that you also might introduce your own attributes and + parameters into the XML that can be pulled out and used by your + constructor. + </li> + <li> + You can also create listeners for events that your contained views might + generate, for example, a listener method for the List Item Click Listener + to update the contents of the EditText if a list selection is made. + </li> + <li> + You might also create your own properties with accessors and modifiers, + for example, allow the EditText value to be set initially in the + component and query for its contents when needed. + </li> + <li> + In the case of extending a Layout, you don't need to override the + <code>onDraw()</code> and <code>onMeasure()</code> methods since the + layout will have default behavior that will likely work just fine. However, + you can still override them if you need to. + </li> + <li> + You might override other <code>on...</code> methods, like + <code>onKeyDown()</code>, to perhaps choose certain default values from + the popup list of a combo box when a certain key is pressed. + </li> +</ol> +<p> + To summarize, the use of a Layout as the basis for a Custom Control has a +number of advantages, including:</p> + +<ul> + <li> + You can specify the layout using the declarative XML files just like + with an activity screen, or you can create views programmatically and + nest them into the layout from your code. + </li> + <li> + The <code>onDraw()</code> and <code>onMeasure()</code> methods (plus + most of the other <code>on...</code> methods) will likely have suitable behavior so + you don't have to override them. + </li> + <li> + In the end, you can very quickly construct arbitrarily complex compound + views and re-use them as if they were a single component. + </li> +</ul> +<h4>Examples of Compound Controls</h4> +<p>In the API Demos project + that comes with the SDK, there are two List + examples — Example 4 and Example 6 under Views/Lists demonstrate a + SpeechView which extends LinearLayout to make a component for displaying + Speech quotes. The corresponding classes in the sample code are + <code>List4.java</code> and <code>List6.java</code>.</p> + + + +<h2 id="modifying">Modifying an Existing View Type</h2> +<p>There is an even easier option for creating a custom View which is +useful in certain circumstances. If there is a component that is already very +similar to what you want, you can simply extend that component and just +override the behavior that you want to change. You can do all of the things +you would do with a fully customized component, but by starting with a more +specialized class in the View heirarchy, you can also get a lot of behavior for +free that probably does exactly what you want.</p> +<p>For example, the SDK includes a <a +href="{@docRoot}guide/samples/NotePad/index.html">NotePad application</a> in the +samples. This demonstrates many aspects of using the Android platform, among +them is extending an EditText View to make a lined notepad. This is not a +perfect example, and the APIs for doing this might change from this early +preview, but it does demonstrate the principles.</p> +<p>If you haven't done so already, import the +NotePad sample into Eclipse (or +just look at the source using the link provided). In particular look at the definition of +<code>MyEditText</code> in the <a +href="{@docRoot}guide/samples/NotePad/src/com/example/android/notepad/NoteEditor.html">NoteEditor.java</a> +file.</p> +<p>Some points to note here</p> +<ol> + <li> + <strong>The Definition</strong> + <p>The class is defined with the following line:<br/> + <code>public static class MyEditText extends EditText</code></p> + + <ul> + <li> + It is defined as an inner class within the <code>NoteEditor</code> + activity, but it is public so that it could be accessed as + <code>NoteEditor.MyEditText</code> from outside of the <code>NoteEditor</code> + class if desired. + </li> + <li> + It is <code>static</code>, meaning it does not generate the so-called + "synthetic methods" that allow it to access data from the parent + class, which in turn means that it really behaves as a separate + class rather than something strongly related to <code>NoteEditor</code>. + This is a cleaner way to create inner classes if they do not need + access to state from the outer class, keeps the generated class + small, and allows it to be used easily from other classes. + </li> + <li> + It extends <code>EditText</code>, which is the View we have chosen to + customize in this case. When we are finished, the new class will be + able to substitute for a normal <code>EditText</code> view. + </li> + </ul> + </li> + <li> + <strong>Class Initialization</strong> + <p>As always, the super is called first. Furthermore, + this is not a default constructor, but a parameterized one. The + EditText is created with these parameters when it is inflated from an + XML layout file, thus, our constructor needs to both take them and pass them + to the superclass constructor as well.</p> + </li> + <li> + <strong>Overridden Methods</strong> + <p>In this example, there is only one method to be overridden: + <code>onDraw()</code> — but there could easily be others needed when you + create your own custom components.</p> + <p>For the NotePad sample, overriding the <code>onDraw()</code> method allows + us to paint the blue lines on the <code>EditText</code> view canvas (the + canvas is passed into the overridden <code>onDraw()</code> method). The + super.onDraw() method is called before the method ends. The + superclass method should be invoked, but in this case, we do it at the + end after we have painted the lines we want to include.</p> + <li> + <strong>Use the Custom Component</strong> + <p>We now have our custom component, but how can we use it? In the + NotePad example, the custom component is used directly from the + declarative layout, so take a look at <code>note_editor.xml</code> in the + <code>res/layout</code> folder.</p> +<pre> +<view + class="com.android.notepad.NoteEditor$MyEditText" + id="@+id/note" + android:layout_width="fill_parent" + android:layout_height="fill_parent" + android:background="@android:drawable/empty" + android:padding="10dip" + android:scrollbars="vertical" + android:fadingEdge="vertical" /> +</pre> + + <ul> + <li> + The custom component is created as a generic view in the XML, and + the class is specified using the full package. Note also that the + inner class we defined is referenced using the + <code>NoteEditor$MyEditText</code> notation which is a standard way to + refer to inner classes in the Java programming language. + <p>If your custom View component is not defined as an inner class, then you can, + alternatively, declare the View component + with the XML element name, and exclude the <code>class</code> attribute. For example:</p> +<pre> +<com.android.notepad.MyEditText + id="@+id/note" + ... /> +</pre> + <p>Notice that the <code>MyEditText</code> class is now a separate class file. When the class + is nested in the <code>NoteEditor</code> class, this technique will not work.</p> + </li> + <li> + The other attributes and parameters in the definition are the ones + passed into the custom component constructor, and then passed + through to the EditText constructor, so they are the same + parameters that you would use for an EditText view. Note that it is + possible to add your own parameters as well, and we will touch on + this again below. + </li> + </ul> + </li> +</ol> +<p>And that's all there is to it. Admittedly this is a simple case, but +that's the point — creating custom components is only as complicated as you +need it to be.</p> +<p>A more sophisticated component may override even more <code>on...</code> methods and +introduce some of its own helper methods, substantially customizing its properties and +behavior. The only limit is your imagination and what you need the component to +do.</p> + diff --git a/docs/html/guide/topics/views/custom-views.jd b/docs/html/guide/topics/views/custom-views.jd index 9850e17..c5f9346 100644 --- a/docs/html/guide/topics/views/custom-views.jd +++ b/docs/html/guide/topics/views/custom-views.jd @@ -1,10 +1,8 @@ page.title=Building Custom Views +parent.title=Views and Layout +parent.link=index.html @jd:body -<p>Android comes with a solid collection of Views that you can use -to construct your applications, for example:</p> - - <p>Android offers a sophisticated and powerful componentized model for building your UI, based on the fundamental building block classes {@link android.view.View} and {@link android.view.ViewGroup}. To start with, the platform includes a variety of prebuilt View and ViewGroup subclasses — called widgets and layouts, respectively — that you can use to construct your UI. The widgets and layouts are fully implemented and handle all of their own measuring and drawing, so you can use them right away. You can make new types of UI elements simply by nesting and grouping the widgets and layouts. Using widgets and layouts is the recommended approach to building a UI for your applications.</p> <p>A partial list of available widgets includes {@link android.widget.Button Button}, @@ -20,9 +18,9 @@ to construct your applications, for example:</p> {@link android.widget.TextSwitcher TextSwitcher}. </p> <p>Among the layouts available are {@link android.widget.LinearLayout LinearLayout}, -{@link android.widget.FrameLayout FrameLayout}, {@link android.widget.AbsoluteLayout AbsoluteLayout},and others. For more examples, see <a href="layout">Common Layout Objects</a>.</p> +{@link android.widget.FrameLayout FrameLayout}, {@link android.widget.AbsoluteLayout AbsoluteLayout}, and others. For more examples, see <a href="layout">Common Layout Objects</a>.</p> -<p>If none of the prebuilt widgets or layouts meets your needs, you can also create your own View subclass, such as a layout group or compound control. If you only need to make small adjustments to an existing widget or layout, you can simply subclass the widget or layout and override +<p>If none of the prebuilt widgets or layouts meets your needs, you can also create your own View subclass, such as a layout group or compound control. If you only need to make small adjustments to an existing widget or layout, you can simply subclass the widget or layout and override its methods. </p> <p>Creating your own View subclasses gives you precise control over the appearance and function of a screen element. To give an idea of the control you get with custom views, here are some examples of what you could do with them:</p> @@ -42,8 +40,8 @@ to construct your applications, for example:</p> </li> <li> You could override the way that an EditText component is rendered on the screen - (the Notepad tutorial uses this to good effect, to create a lined-notepad - page). + (the <a href="{@docRoot}guide/samples/NotePad/">Notepad sample</a> uses this to good effect, + to create a lined-notepad page). </li> <li> You could capture other events like key presses and handle them in some custom @@ -52,19 +50,16 @@ to construct your applications, for example:</p> </ul> <p> The sections below explain how to create custom Views and use them in your application. -</p> +For detailed reference information, see the {@link android.view.View} class. </p> -<p>For detailed information, see {android.view.View}. </p> - - -<h2 style="clear:right;">Contents</h2> -<dl> -<dt><a href="#basic">The Basic Approach</a></dt> -<dt><a href="#custom">Fully Customized Views</a></dt> -<dt><a href="#customexample">Customized View Example</a></dt> -<dt><a href="#compound">Compound Controls</a></dt> -<dt><a href="#tweaking">Modifying an Existing Component Type</a></dt> -</dl> +<p>This document covers the following:</p> +<ol class="toc"> + <li><a href="#basic">The Basic Approach</a></li> + <li><a href="#custom">Fully Customized Views</a></li> + <li><a href="#customexample">Customized View Example</a></li> + <li><a href="#compound">Compound Controls</a></li> + <li><a href="#tweaking">Modifying an Existing Component Type</a></li> +</ol> <a name="basic"></a> <h2>The Basic Approach @@ -98,7 +93,7 @@ View components:</p> functionality. </li> </ol> -<p class="note"> +<p class="note"><strong>Tip:</strong> Extension classes can be defined as inner classes inside the activities that use them. This is useful because it controls access to them but isn't necessary (perhaps you want to create a new public View for @@ -201,7 +196,116 @@ result will be an exception at measurement time.</p> thrown. </li> </ol> - + +<p> +Here's a summary of some of the other standard methods that the framework calls on views: +</p> +<table border="2" width="85%" align="center" cellpadding="5"> + <thead> + <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> + </thead> + + <tbody> + <tr> + <td rowspan="2">Creation</td> + <td>Constructors</td> + <td>There is a form of the constructor that are called when the view + is created from code and a form that is called when the view is + inflated from a layout file. The second form should parse and apply + any attributes defined in the layout file. + </td> + </tr> + <tr> + <td><code>{@link android.view.View#onFinishInflate()}</code></td> + <td>Called after a view and all of its children has been inflated + from XML.</td> + </tr> + + <tr> + <td rowspan="3">Layout</td> + <td><code>{@link android.view.View#onMeasure}</code></td> + <td>Called to determine the size requirements for this view and all + of its children. + </td> + </tr> + <tr> + <td><code>{@link android.view.View#onLayout}</code></td> + <td>Called when this view should assign a size and position to all + of its children. + </td> + </tr> + <tr> + <td><code>{@link android.view.View#onSizeChanged}</code></td> + <td>Called when the size of this view has changed. + </td> + </tr> + + <tr> + <td>Drawing</td> + <td><code>{@link android.view.View#onDraw}</code></td> + <td>Called when the view should render its content. + </td> + </tr> + + <tr> + <td rowspan="4">Event processing</td> + <td><code>{@link android.view.View#onKeyDown}</code></td> + <td>Called when a new key event occurs. + </td> + </tr> + <tr> + <td><code>{@link android.view.View#onKeyUp}</code></td> + <td>Called when a key up event occurs. + </td> + </tr> + <tr> + <td><code>{@link android.view.View#onTrackballEvent}</code></td> + <td>Called when a trackball motion event occurs. + </td> + </tr> + <tr> + <td><code>{@link android.view.View#onTouchEvent}</code></td> + <td>Called when a touch screen motion event occurs. + </td> + </tr> + + <tr> + <td rowspan="2">Focus</td> + <td><code>{@link android.view.View#onFocusChanged}</code></td> + <td>Called when the view gains or loses focus. + </td> + </tr> + + <tr> + <td><code>{@link android.view.View#onWindowFocusChanged}</code></td> + <td>Called when the window containing the view gains or loses focus. + </td> + </tr> + + <tr> + <td rowspan="3">Attaching</td> + <td><code>{@link android.view.View#onAttachedToWindow()}</code></td> + <td>Called when the view is attached to a window. + </td> + </tr> + + <tr> + <td><code>{@link android.view.View#onDetachedFromWindow}</code></td> + <td>Called when the view is detached from its window. + </td> + </tr> + + <tr> + <td><code>{@link android.view.View#onWindowVisibilityChanged}</code></td> + <td>Called when the visibility of the window containing the view + has changed. + </td> + </tr> + </tbody> + + </table> + + <a name="customexample"></a> <h3>A Custom View Example</h3> <p>The CustomView sample in the diff --git a/docs/html/guide/topics/views/declaring-layout.jd b/docs/html/guide/topics/views/declaring-layout.jd new file mode 100644 index 0000000..43afdf7 --- /dev/null +++ b/docs/html/guide/topics/views/declaring-layout.jd @@ -0,0 +1,228 @@ +page.title=Declaring Layout +parent.title=Views and Layout +parent.link=index.html +@jd:body + +<div id="qv-wrapper"> +<div id="qv"> + <h2>In this document</h2> + <ol> + <li><a href="#LoadingTheResource">Loading the XML Resource</a></li> + <li><a href="#Position">Position</a></li> + <li><a href="#SizePaddingMargin">Size, Padding and Margins</a></li> + </ol> +</div> +</div> + +<p>You can create your application's user interface in two ways: +<ul> +<li><strong>Declare UI elements statically, in XML</strong>. Android provides a straightforward XML +vocabulary that corresponds to the View classes and subclasses, such as those for widgets and layouts. </li> +<li><strong>Instantiate screen elements at runtime</strong>. Your +application can refer to or create View or other class objects and manipulate their properties programmatically. </li> +</ul> + +<p>One advantage of declaring your UI in XML is that it enables you to better separate the presentation of your application from the code that controls it's behavior. Your UI description is external to your application code, which means that you can modify or adapt it without having to modify your source code and recompile. For example, you can create XML layouts for different screen orientations and for a variety of device screen sizes or languages. Additionally, declaring in XML makes it easier to see the elements and structure of your UI, so it's easier to debug problems. </p> + +<div class="sidebox"> + <p>The <a href="{@docRoot}guide/developing/tools/adt.html">Android Development Tools</a> + (ADT) plugin for Eclipse offers a layout preview of your XML — + with the XML file opened, select the <strong>Layout</strong> tab.</p> + <p>You should also try the + <a href="{@docRoot}guide/developing/tools/hierarchy-viewer.html">Hierarchy Viewer</a> tool, + for debugging layouts — it reveals layout property values, + draws wireframes with padding/margin indicators, and full rendered views while + you debug on the emulator or device.</p> +</div> + +<p>The Android framework gives you the flexibility to use either or both of these ways of declaring and managing your application's UI. For example, you could declare your application's default layouts in XML, including the screen elements that will appear in them and their properties. You could then add code in your application that would modify the state of the screen objects, including those declared in XML, at run time. </p> + +<p>You build your application's UI in approximately the same way, whether you are declaring it in XML or programmatically. In both cases, your UI will be a tree structure that may include multiple View or Viewgroup subclasses. </p> + +<p>In general, the XML vocabulary for declaring UI elements closely follows the structure and naming of the framework's UI-related classes and methods, where element names correspond to class names and attribute names correspond to methods. In fact, the correspondence is often so direct that you can guess what XML attribute corresponds to a class method, or guess what class corresponds to a given xml element. </p> + +<p>However, note that the XML vocabulary for defining UI is not entirely identical to the framework's classes and methods. In some cases, there are slight naming differences. For +example, the EditText element has a <code>text</code> attribute that corresponds to +<code>EditText.setText()</code>. </p> + +<div class="sidebox"><p>For your convenience, the API reference documentation for UI related classes lists the available XML attributes that correspond to the class methods, including inherited attributes.</p> + +<p>To learn more about the available XML elements and attributes, as well as the format of the XML file, see <a +href="{@docRoot}guide/topics/resources/available-resources.html#layoutresources">Layout Resources</a>.</p> + </div> + +<p>Using Android's XML vocabulary, you can quickly design UI layouts and the screen elements they contain, in the same way you create HTML files — as a series of nested tags. </p> + +<p>Each layout file must contain exactly one root element, and the root element must be a View or ViewGroup object. Once you've defined the root element, you can add additional layout objects or controls as child elements of the root element, if needed. In the example below, the tree of XML elements evaluates to the outermost LinearLayout object. + +<p>After you've declared your layout in XML, you must save the file, with the <code>.xml</code> extension, +in your application's <code>res/layout/</code> directory, so it will properly compile. </p> + +<p>When you compile your application, each XML layout file is compiled into an +android.view.View resource. You can then load the layout resource from your application code, by calling <code>setContentView(R.layout.<em>layout_file_name</em>)</code> in your {@link android.app.Activity#onCreate(android.os.Bundle) Activity.onCreate()} +implementation.</p> + +<p>When you load a layout resource, the Android system initializes run-time objects corresponding to the elements in your layout. It parses the elements of your layout in-order (depth-first), instantiating the Views and adding them to their parent(s). +See <a href="how-android-draws.html">How Android Draws Views</a> for more information.</p> + +<p>Attributes named <code>layout_<em>something</em></code> apply to that +object's LayoutParams member. <a href="{@docRoot}guide/topics/resources/available-resources.html#layoutresources">Layout +Resources</a> also describes how to learn the syntax for specifying +LayoutParams properties. </p> + +<p>Also note that Android draws elements in the order in which they +appear in the XML. Therefore, if elements overlap, the last one in the XML +file will probably be drawn on top of any previously listed elements in that +same space.</p> + +<p>The following values are supported for dimensions (described in {@link +android.util.TypedValue TypedValue}):</p> + +<ul> + <li>px (pixels) </li> + <li>dip (device independent pixels) </li> + <li>sp (scaled pixels — best for text size) </li> + <li>pt (points) </li> + <li>in (inches) </li> + <li>mm (millimeters) </li> +</ul> + +<p>Example: <code>android:layout_width="25px"</code> </p> + +<p>For more information about these dimensions, see <a href="{@docRoot}guide/topics/resources/available-resources.html#dimension">Dimension Values</a>.</p> + +<p>The example below shows an XML file and the resulting screen in the UI. Note that the text on the +top of the screen was set by calling {@link +android.app.Activity#setTitle(java.lang.CharSequence) Activity.setTitle}. Note +that the attributes that refer to relative elements (i.e., layout_toLeft) +refer to the ID using the syntax of a relative resource +(@id/<em>id_number</em>). </p> + +<table border="1"> + <tr> + <td> + <pre><?xml version="1.0" encoding="utf-8"?> +<!-- Demonstrates using a relative layout to create a form --> +<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android + android:layout_width="fill_parent" + android:layout_height="wrap_content" + android:background="@drawable/blue" + android:padding="10px"> + + <TextView id="@+id/label" + android:layout_width="fill_parent" + android:layout_height="wrap_content" + android:text="Type here:"/> + + <EditText id="@+id/entry" + android:layout_width="fill_parent" + android:layout_height="wrap_content" + android:background="@android:drawable/editbox_background" + android:layout_below="@id/label"/> + + <Button id="@+id/ok" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_below="@id/entry" + android:layout_alignParentRight="true" + android:layout_marginLeft="10px" + android:text="OK" /> + + <Button android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_toLeftOf="@id/ok" + android:layout_alignTop="@id/ok" + android:text="Cancel" /> +</RelativeLayout></pre></td> + <td><img src="{@docRoot}images/designing_ui_layout_example.png" alt="Screen shot showing how this layout XML file is rendered." /></td> + </tr> +</table> + + +<h2 id="LoadingTheResource">Loading the XML Resource</h2> +<p>Loading the compiled layout resource is very easy, and done with a single +call in the activity's <code>onCreate()</code> method, as shown here:</p> + +<pre> +protected void onCreate(Bundle savedInstanceState) +{ + // Be sure to call the super class. + super.onCreate(savedInstanceState); + + // Load the compiled layout resource into the window's + // default ViewGroup. + // The source file is res/layout/hello_activity.xml + setContentView(R.layout.hello_activity); + + // Retrieve any important stored values. + restoreValues(savedInstanceState); +} </pre> + +<h2 id="Position">Position</h2> + <p> + The geometry of a view is that of a rectangle. A view has a location, + expressed as a pair of <em>left</em> and <em>top</em> coordinates, and + two dimensions, expressed as a width and a height. The unit for location + and dimensions is the pixel. + </p> + + <p> + It is possible to retrieve the location of a view by invoking the methods + {@link android.view.View#getLeft()} and {@link android.view.View#getTop()}. The former returns the left, or X, + coordinate of the rectangle representing the view. The latter returns the + top, or Y, coordinate of the rectangle representing the view. These methods + both return the location of the view relative to its parent. For instance, + when getLeft() returns 20, that means the view is located 20 pixels to the + right of the left edge of its direct parent. + </p> + + <p> + In addition, several convenience methods are offered to avoid unnecessary + computations, namely {@link android.view.View#getRight()} and {@link android.view.View#getBottom()}. + These methods return the coordinates of the right and bottom edges of the + rectangle representing the view. For instance, calling {@link android.view.View#getRight()} + is similar to the following computation: <code>getLeft() + getWidth()</code>. + </p> + + +<h2 id="SizePaddingMargins">Size, Padding and Margins</h2> + <p> + The size of a view is expressed with a width and a height. A view actually + possess two pairs of width and height values. + </p> + + <p> + The first pair is known as <em>measured width</em> and + <em>measured height</em>. These dimensions define how big a view wants to be + within its parent. The + measured dimensions can be obtained by calling {@link android.view.View#getMeasuredWidth()} + and {@link android.view.View#getMeasuredHeight()}. + </p> + + <p> + The second pair is simply known as <em>width</em> and <em>height</em>, or + sometimes <em>drawing width</em> and <em>drawing height</em>. These + dimensions define the actual size of the view on screen, at drawing time and + after layout. These values may, but do not have to, be different from the + measured width and height. The width and height can be obtained by calling + {@link android.view.View#getWidth()} and {@link android.view.View#getHeight()}. + </p> + + <p> + To measure its dimensions, a view takes into account its padding. The padding + is expressed in pixels for the left, top, right and bottom parts of the view. + Padding can be used to offset the content of the view by a specific amount of + pixels. For instance, a left padding of 2 will push the view's content by + 2 pixels to the right of the left edge. Padding can be set using the + {@link android.view.View#setPadding(int, int, int, int)} method and queried by calling + {@link android.view.View#getPaddingLeft()}, {@link android.view.View#getPaddingTop()}, + {@link android.view.View#getPaddingRight()} and {@link android.view.View#getPaddingBottom()}. + </p> + + <p> + Even though a view can define a padding, it does not provide any support for + margins. However, view groups provide such a support. Refer to + {@link android.view.ViewGroup} and + {@link android.view.ViewGroup.MarginLayoutParams} for further information. + </p> +
\ No newline at end of file diff --git a/docs/html/guide/topics/views/how-android-draws.jd b/docs/html/guide/topics/views/how-android-draws.jd new file mode 100644 index 0000000..f497db7 --- /dev/null +++ b/docs/html/guide/topics/views/how-android-draws.jd @@ -0,0 +1,90 @@ +page.title=How Android Draws Views +parent.title=Views and Layout +parent.link=index.html +@jd:body + + +<p>As mentioned in the introduction to <a href="index.html">Views and Layout</a>, +drawing begins when the Activity requests the root node of the layout to measure and +draw the layout tree. Drawing is handled by walking the tree and rendering each view that + intersects the invalid region. In turn, each view group is responsible for requesting +each of its children to be drawn and each view is responsible for drawing itself. + Because the tree is traversed in-order, + this means that parents will be drawn before (i.e., behind) their children, with + siblings drawn in the order they appear in the tree. + </p> + +<div class="sidebox"> + <p>The framework will not draw views that are not in the invalid region, and also + will take care of drawing the views background for you.</p> + <p>You can force a view to draw, by calling {@link android.view.View#invalidate()}. + </p> +</div> + +<p> + Drawing the layout is a two pass process: a measure pass and a layout pass. The measuring + pass is implemented in {@link android.view.View#measure(int, int)} and is a top-down traversal + of the view tree. Each view pushes dimension specifications down the tree + during the recursion. At the end of the measure pass, every view has stored + its measurements. The second pass happens in + {@link android.view.View#layout(int,int,int,int)} and is also top-down. During + this pass each parent is responsible for positioning all of its children + using the sizes computed in the measure pass. + </p> + + <p> + When a view's measure() method returns, its {@link android.view.View#getMeasuredWidth()} and + {@link android.view.View#getMeasuredHeight()} values must be set, along with those for all of + that view's descendants. A view's measured width and measured height values + must respect the constraints imposed by the view's parents. This guarantees + that at the end of the measure pass, all parents accept all of their + children's measurements. A parent view may call measure() more than once on + its children. For example, the parent may measure each child once with + unspecified dimensions to find out how big they want to be, then call + measure() on them again with actual numbers if the sum of all the children's + unconstrained sizes is too big or too small (i.e., if the children don't agree among themselves + as to how much space they each get, the parent will intervene and set the rules on the second pass). + </p> + + <div class="sidebox"><p> + To intiate a layout, call {@link android.view.View#requestLayout}. This method is typically + called by a view on itself when it believes that is can no longer fit within + its current bounds.</p> + </div> + + <p> + The measure pass uses two classes to communicate dimensions. The + {@link android.view.View.MeasureSpec} class is used by views to tell their parents how they + want to be measured and positioned. The base LayoutParams class just + describes how big the view wants to be for both width and height. For each + dimension, it can specify one of:</p> + <ul> + <li> an exact number + <li>FILL_PARENT, which means the view wants to be as big as its parent + (minus padding)</li> + <li> WRAP_CONTENT, which means that the view wants to be just big enough to + enclose its content (plus padding).</li> + </ul> + <p>There are subclasses of LayoutParams for different subclasses of ViewGroup. + For example, AbsoluteLayout has its own subclass of LayoutParams which adds + an X and Y value. + </p> + + <p> + MeasureSpecs are used to push requirements down the tree from parent to + child. A MeasureSpec can be in one of three modes:</p> + <ul> + <li>UNSPECIFIED: This is used by a parent to determine the desired dimension + of a child view. For example, a LinearLayout may call measure() on its child + with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how + tall the child view wants to be given a width of 240 pixels.</li> + <li>EXACTLY: This is used by the parent to impose an exact size on the + child. The child must use this size, and guarantee that all of its + descendants will fit within this size.</li> + <li>AT_MOST: This is used by the parent to impose a maximum size on the + child. The child must gurantee that it and all of its descendants will fit + within this size.</li> + </ul> + + + diff --git a/docs/html/guide/topics/views/index.jd b/docs/html/guide/topics/views/index.jd index 9a15921d..a246ba1 100644 --- a/docs/html/guide/topics/views/index.jd +++ b/docs/html/guide/topics/views/index.jd @@ -1,45 +1,216 @@ page.title=Views and Layout @jd:body -<p>To build a user interface fors your Android application, you work with <em>views</em> and <em>viewgroups</em> -- basic units of user interface expression on the Android platform. All views and viewgroups are descendants of the class {@link android.view.View}. To help you build your UI more quickly, Android provides a set of fully implemented views and viewgroups — called widgets and layouts — that you can use. +<div id="qv-wrapper"> +<div id="qv"> -The topics below describe the basics of how you use views to implement a user interface. including the types of screen elements available, the ways that you can declare them in your application, how you can bind a screen elements to local data, and how views can catch and handle screen or keypad events. </p> + <h2>Key classes and packages</h2> + <ol> + <li>{@link android.view.View}</li> + <li>{@link android.view.ViewGroup}</li> + <li>{@link android.widget}</li> + </ol> -<p>For a quick start on how to create the Views you need for your UI, check out the <a href="{@docRoot}guide/tutorials/views/hello-views-index.html">Hello Views tutorials</a>. You can look at a variety of available layouts and screen elements as they would be rendered on a device, then look at the code for declaring and invoking each one. </p> + <h2>In this document</h2> + <ol> + <li><a href="#ViewHierarchy">View Hierarchy</a></li> + <li><a href="#Layout">Layout</a></li> + <li><a href="#Widgets">Widgets</a></li> + <li><a href="#Events">Events</a></li> + <li><a href="#Adapters">Adapters</a></li> + <li><a href="#StylesAndThemes">Styles and Themes</a></li> + </ol> +</div> +</div> + +<p>In an Android application, a user interface is built using {@link android.view.View} and +{@link android.view.ViewGroup} objects. There are many types of views and view groups, each of which +is a descendant of the {@link android.view.View} class.</p> + +<p>View objects are the basic units of user interface expression on the Android platform. +The View class serves as the base for subclasses called "widgets," which offer fully implemented +UI objects, like text fields and buttons. The ViewGroup class serves as the base for subclasses called "layouts," +which offer different kinds of layout architecture, like linear, tabular and relative.</p> + +<p>A View object is a data structure whose properties store the layout properties and content for a specific +rectangular area of the screen. A View object handles its own measurement, layout, drawing, focus change, +scrolling, and key/gesture interactions for the rectangular screen area it represents. </p> + + +<h2 id="ViewHierarchy">View Hierarchy</h2> + +<p>On the Android platform, you will define an Activity's UI using a hierarchy of view and view group nodes, +as shown in the diagram below. This hierarchy tree can be as simple or complex as you need it to be, and you +can build it up using Android's set of predefined widgets and layouts, or with custom view types that you +create yourself.</p> + +<img src="{@docRoot}images/viewgroup.png" alt="" width="312" height="211" align="center"/> + +<p>The Android system will notify your Activity when it becomes active and receives focus. +In order to attach the view hierarchy tree to the screen for rendering, your Activity must call its +<code>setContentView()</code> method and pass a reference to the root node object. The Android system +receives this reference so that it can invalidate, measure, and draw the tree. The root node requests +that its child nodes draw themselves — in turn, each view group node is responsible for +calling <code>Draw()</code> on each of its own child views, so that each child view can render itself. +The children may request a size and location within the parent, but the parent object has the final +decision on where how big each child can be. To learn more about how a view group and its children are measured +and drawn, read <a href="how-android-draws.html">How Android Draws Views</a>.</p> -<p>You can find additional sample code in the API Demos application, included in the SDK's samples directory. </p> +<h2 id="Layout">Layout</h2> + +<p>The most common way to define your layout and express the view hierarchy is with an XML layout file. +XML offers a human-readable structure for the layout, much like HTML. Each element in XML is +(usually a descendant of) either a View or ViewGroup object. View objects are leaves in the tree, +ViewGroup objects are branches in the tree. The name of an XML element +is the respective class object name. So a <code><TextView></code> element creates +a {@link android.widget.TextView} widget in your UI, and a <code><LinearLayout></code> element creates +a {@link android.widget.LinearLayout} layout branch in the tree. To learn more about how to write your layout in XML, +read <a href="declaring-layout.html">Declaring and Querying Layout</a>. + +<div class="sidebox-wrapper"> <div class="sidebox"> -<p>Using Android resources is an important part of building your application's user interface. For information about what resources are available to you and how you use them, see the <a href="{@docRoot}guide/topics/resources/index.html">Resources</a> topics area.</p> + <p><b>Tip:</b> You can also draw new views and view groups from within your code, + by adding new View and ViewGroup objects to an + existing ViewGroup (specifically, you'll use the <code>addView()</code> methods to dynamically insert new views). + To see how to add views in your code, see the {@link android.view.ViewGroup} reference.</p> +</div> </div> +<p>There are a variety of ways in which you can layout your views, using different view groups. +Some pre-defined view groups offered by Android (called layouts) include LinearLayout, RelativeLayout, AbsoluteLayout, +TableLayout, GridLayout and others. Each offers a different mechanisms for arranging child views +among each other. +To learn more about how to use some of these view groups for your layout, +read <a href="layout.html">Common Layout Objects</a>. + +<h3 id="IDs">IDs</h3> + +<p>Views may have an integer ID associated with them. The ID is written as a string, but once the application is +compiled, it will be referenced as an integer. +These IDs are typically assigned in the layout XML file as an attribute of the view, +and are used to uniquely identify a view within the tree. The usual syntax for an ID, inside an XML tag is:</p> +<pre>id="@+id/my_button"</pre> +<p>The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and expand the rest +of the ID string and identify it as an ID resource. The plus-symbol (+) means that this is a new resource name that must +be created and added to our resources (in the <code>R.java</code> file). There are a number of other ID resources that +are offered by the Android framework. When referencing an Android resource ID, you do not need the plus-symbol, +but must add the <code>android</code> package namespace, like so:</p> +<pre>id="@android:id/empty"</pre> +<p>With the <code>android</code> package namespace in place, we're now referencing an ID from the <code>android.R</code> +resources class, rather than the local resources class.</p> + +<p>In order to create views and reference them from the application, a common pattern is to:</p> +<ol> + <li>Define a view/widget in the layout file and assign it a unique ID. E.g.: +<pre> +<Button id="@+id/my_button" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/my_button_text"/> +</pre> + </li> + <li>Then create an instance of the view object and capture it from the layout +(typically in the <code>onCreate()</code> method). +<pre> +Button myButton = (Button) findViewById(R.id.my_button); +</pre> + </li> +</ol> +<p>Defining IDs for view objects is important when creating a {@link android.widget.RelativeLayout}. +In a relative layout, sibling views can define their layout relative to another sibling view, +which is referenced by the unique ID.</p> +<p>An ID need not be unique throughout the entire tree, but it should be +unique within the part of the tree you are searching (which may often be the entire tree, so it's best +to be completely unique when possible).</p> + + +<h3>Layout Parameters</h3> + +<p>Every ViewGroup class implements a nested class that extends {@link +android.view.ViewGroup.LayoutParams}. This subclass +contains property types that define each child view's size and position, as +appropriate for that type of view group. As you can see in the figure below, the parent +view group defines layout parameters for each child view (including the child view group).</p> + +<img src="{@docRoot}images/layoutparams.png" alt="" height="300" align="center"/> + +<p>Note that every LayoutParams subclass has its own syntax for setting +values. Each child element must define LayoutParams that are appropriate for its parent, +though it may also define different LayoutParams for its own children. </p> + +<p>All view groups include a width and height, and each view is required to define them. +Many LayoutParams also include optional margins and +borders. You can specify width and height with exact measurements, though you probably won't want +to do this often. More often, you will tell your view to size itself either to +the dimensions required by its content, or to become as big as its parent view group +will allow (with the <var>wrap_content</var> and <var>fill_parent</var> values, respectively). +The accepted measurement types are defined in the +<a href="{@docRoot}guide/topics/resources/available-resources.html#dimension">Available Resources</a> document.</p> + +<h2 id="Widgets">Widgets</h2> + + +<p>The View class also serves as a base class for <em>widgets</em> — a set of fully implemented +View subclasses that draw interactive screen elements, so you can quickly build your UI. +Android provides a vast collection of widgets for special actions. +Some of them are basic interaction elements like buttons and text fields, while others are more complex, +like a date picker or zoom controls.</p> +<p>For a list of all built-in widgets, see the {@link android.widget widget}.</p> + +<p>You're not limited to the kinds of views, layouts and widgets provided by the Android platform. If you'd +like to do something more customized, create your own widget or layout, you can. +Read more in <a href="custom-components.html">Building Custom Components</a>. + + +<h2 id="Events">Events</h2> + +<p>Once you've designed and built your UI layout, you need to handle the user interaction with it. +Obviously, the views that you've implemented in the layout are the +receptors for such interaction events. Because the View class is built to listen for most interaction events, +receiving and handling them is pretty straigh-forward. When you want to perform an action upon an event, +you need to do one of two things:</p> <ul> - <li> - <a href="hierarchy.html">Hierarchy of Screen Elements</a> - </li> - <li> - <a href="layout.html">Common Layout Objects</a> - </li> - <li> - <a href="ui-xml.html">Declaring a UI in XML</a> - </li> - <li> - <a href="binding.html">Binding to Data with AdapterView</a> - </li> - <li> - <a href="ui-events.html">Handling UI Events</a> - </li> - <li> - <a href="themes.html">Applying Styles and Themes to Your Application</a> - </li> - <li> - <a href="custom-views.html">Building Custom Views</a> - </li> - <li> - <a href="glossary.html">UI Elements and Concepts Glossary</a> - </li> - <li> - <a href="{@docRoot}guide/tutorials/views/hello-views-index.html">Hello Views</a> - </li> + <li>Override an existing callback method for the view you've implemented, which will be called when something +like a touch or focus event occurs.</li> + <li>Define a listener interface, like {@link android.view.View.OnClickListener} (for handling "clicks" on a View). +You must then define the listener for your view with the respective <code>set...Listener()</code> +method (such as {@link android.view.View#setOnClickListener(android.view.View.OnClickListener) setOnCLickListener()}).</li> +</ul> +<p>To learn more about handling events and writing your own listeners, +read <a href="ui-events.html">Handling UI Events</a>.</p> + + +<h2 id="Adapters">Adapters</h2> + +<p>Sometimes you'll want to populate a view group with some information that can't be hard-coded, instead, +you want to bind your view to an external source of data. To do this, you use an AdapterView as +your view group and each child View is initialized and populated with data from the Adapter.</p> +<p>The AdapterView object is an implementation of ViewGroup that determines its child views +based on a given Adapter object. The Adapter acts like a courier between your data source (perhaps an +array of external strings) and the AdapterView, which displays it. There are several implementations +of the Adapter class, for specific tasks, such as the CursorAdapter for reading database data from a Cursor, +or an ArrayAdapter for reading from an arbitrary array.</p> +<p>To learn more about using an Adapter to populate your views, read +<a href="binding.html">Binding to Data with AdapterView</a>.</p> + + +<h2 id="StylesAndThemes">Styles and Themes</h2> + +<p>Perhaps you're not satisfied with the look of the standard widgets. To revise them, you can create some +of your own styles and themes.</p> + +<ul> + <li>A style is a set of one or more formatting attributes that you can apply as a unit to individual elements +in your layout. For example, you could define a style that specifies a certain text size and color, then +apply it to only specific View elements.</li> + <li>A theme is a set of one or more formatting attributes that you can apply as a unit to all activities in +an application, or just a single activity. For example, you could define a theme that sets specific colors for +the window frame and the panel background, and sets text sizes and colors for menus. This theme can then be +applied to specific activities or the entire application.</li> </ul> + +<p>Styles and themes are resources. Android provides some default style and theme resources that you can use, +or you can declare your own custom style and theme resources. Learn more about using styles and themes in the +<a href="themes.html">Applying Styles and Themes</a> document.</p> diff --git a/docs/html/guide/topics/views/hierarchy.jd b/docs/html/guide/topics/views/intro.jd index 17a13c1..f49f547 100644 --- a/docs/html/guide/topics/views/hierarchy.jd +++ b/docs/html/guide/topics/views/intro.jd @@ -1,4 +1,6 @@ -page.title=Hierarchy of Screen Elements +page.title=Introduction to Views +parent.title=Views and Layout +parent.link=index.html @jd:body <p>The basic functional unit of an Android application is the <em>activity</em> — an object of the class {@link android.app.Activity android.app.Activity}. An activity can do many things, but by itself it does not have a presence on the screen. To give your activity a screen presence and design its UI, you work with <em>views</em> and <em>viewgroups</em> -- basic units of user interface expression on the Android platform.</p> diff --git a/docs/html/guide/topics/views/layout.jd b/docs/html/guide/topics/views/layout.jd index f6eedbb..a6fec35 100644 --- a/docs/html/guide/topics/views/layout.jd +++ b/docs/html/guide/topics/views/layout.jd @@ -1,60 +1,78 @@ page.title=Common Layout Objects +parent.title=Views and Layout +parent.link=index.html @jd:body -<p>The sections below describe some of the more common types of layout objects you'll be likely to use in your applications. Like other layouts, they are subclasses of {@link android.view.ViewGroup ViewGroup}.</p> +<div id="qv-wrapper"> +<div id="qv"> + <h2>In this document</h2> + <ol> + <li><a href="#framelayout">FrameLayout</a></li> + <li><a href="#linearlayout">LinearLayout</a></li> + <li><a href="#tablelayout">TableLayout</a></li> + <li><a href="#absolutelayout">AbsoluteLayout</a></li> + <li><a href="#relativelayout">RelativeLayout</a></li> + <li><a href="#viewgroupsummary">Summary of Important View Groups</a></li> + </ol> +</div> +</div> + +<p>This section describes some of the more common types of layout objects +to use in your applications. Like all layouts, they are subclasses of {@link android.view.ViewGroup ViewGroup}.</p> -<h2>FrameLayout<a name="framelayout" id="framelayout"></a></h2> -<p>{@link android.widget.FrameLayout FrameLayout} is the simplest layout -object. It is intended as a blank reserved space on your screen that you can -later fill with a single object — for example, a picture that you'll swap out. -All child elements are pinned to the top left corner of the screen; you cannot -specify a location for a child of a {@link android.widget.FrameLayout -FrameLayout}. Later children will simply be drawn over earlier objects, +<h2 id="framelayout">FrameLayout</h2> +<p>{@link android.widget.FrameLayout FrameLayout} is the simplest type of layout +object. It's basically a blank space on your screen that you can +later fill with a single object — for example, a picture that you'll swap in and out. +All child elements of the FrameLayout are pinned to the top left corner of the screen; you cannot +specify a different location for a child view. Subsequent child views will simply be drawn over previous ones, partially or totally obscuring them (unless the newer object is transparent). </p> -<h2>LinearLayout<a name="linearlayout" id="linearlayout"></a></h2> -<p>A {@link android.widget.LinearLayout LinearLayout} aligns all children in a -single direction — vertically or horizontally, depending on what property you -set on the {@link android.widget.LinearLayout LinearLayout}. All children are +<h2 id="linearlayout">LinearLayout</h2> +<p>{@link android.widget.LinearLayout LinearLayout} aligns all children in a +single direction — vertically or horizontally, depending on how you +define the <code>orientation</code> attribute. All children are stacked one after the other, so a vertical list will only have one child per row, no matter how wide they are, and a horizontal list will only be one row -high (the height of the tallest child, plus padding). {@link -android.widget.LinearLayout LinearLayout} respects margins between children, -and also <em>gravity</em> (right, center, or left alignment of a child). </p> +high (the height of the tallest child, plus padding). A {@link +android.widget.LinearLayout LinearLayout} respects <em>margin</em>s between children +and the <em>gravity</em> (right, center, or left alignment) of each child. </p> <p>{@link android.widget.LinearLayout LinearLayout} also supports assigning a -<em>weight</em> to individual children. This value allows children to expand -to fill any remaining space on a screen. This prevents a list of small objects -from being bunched to one end of a large screen, allowing them to expand to -fill the space. Children specify a weight value, and any remaining space is +<em>weight</em> to individual children. This attribute assigns an "importance" value to a view, +and allows it to expand to fill any remaining space in the parent view. +Child views can specify an integer weight value, and then any remaining space in the view group is assigned to children in the proportion of their declared weight. Default -weight is zero. So, for example, if there are three text boxes, and two of -them declare a weight of 1, two of them will expand equally to fill the -remaining space, and the third will not grow any additional amount.</p> +weight is zero. For example, if there are three text boxes and two of +them declare a weight of 1, while the other is given no weight (0), the third text box without weight +will not grow and will only occupy the area required by its content. +The other two will expand equally to fill the space remaining after all three boxes are measured. +If the third box is then given a weight of 2 (instead of 0), then it is now declared +"more important" than both the others, so it gets half the total remaining space, while the first two +share the rest equally.</p> <div class="sidebox"> <p><strong>Tip</strong>: To create a proportionate size -layout on the screen, create a container object that is fill_parent, assign -the children heights or widths of zero, and then assign relative weight values +layout on the screen, create a container view group object with the +<code>layout_width</code> and <code>layout_height</code> attributes set to <var>fill_parent</var>; assign +the children <code>height</code> or <code>width</code> to <code>0</code> (zero); then assign relative +<code>weight</code> values to each child, depending on what proportion of the screen each should -take.</p> +have.</p> </div> <p>The following two forms represent a {@link android.widget.LinearLayout LinearLayout} with a set of elements: a -button, some labels, some text boxes. Both have padding values to adjust the -padding nicely. The text boxes have their width set to <code>FILL_PARENT</code>; other -elements are set to <code>WRAP_CONTENT</code>. The gravity, by default, is left. The form -on the left has weight values unset (0 by default); the form on the right has +button, some labels and text boxes. The text boxes have their width set to <var>fill_parent</var>; other +elements are set to <var>wrap_content</var>. The gravity, by default, is left. +The difference between the two versions of the form is that the form +on the left has weight values unset (0 by default), while the form on the right has the comments text box weight set to 1. If the Name textbox had also been set to 1, the Name and Comments text boxes would be the same height. </p> -<p> - <img src="{@docRoot}images/linearlayout.png" alt="Linear layout with -weight attribute." width="421" height="348" /> -</p> +<img src="{@docRoot}images/linearlayout.png" alt="" /> <p>Within a horizontal {@link android.widget.LinearLayout LinearLayout}, items are aligned by the position of their text base line (the first line of the first list element — topmost or @@ -63,52 +81,75 @@ elements in a form shouldn't have to jump up and down to read element text in neighboring elements. This can be turned off by setting <code>android:baselineAligned="false"</code> in the layout XML. </p> -<h2>TableLayout<a name="tablelayout" id="tablelayout"></a></h2> - -<p>{@link android.widget.TableLayout TableLayout} positions its children into rows - and columns. A TableLayout consists of a number of TableRow objects, - each defining a row (actually, you can have other children, which will be explained - below). TableLayout containers do not display border lines for their rows, columns, - or cells. Each row has zero or more cells; each cell can hold one View object. - The table has as many columns as the row with the most cells. A table can leave -cells empty. Cells cannot span columns, as they can in HTML. The following image - shows a table layout, with the invisible cell borders displayed as dotted lines. </p> -<p><img src="{@docRoot}images/table_layout.png" alt="TableLayout example" width="499" height="348" /></p> -<p>Columns can be hidden, can be marked to stretch to fill available screen space, +<p>To view other sample code, see the +<a href="{@docRoot}guide/tutorials/views/hello-linearlayout.html">Hello LinearLayout</a> tutorial.</p> + + +<h2 id="tablelayout">TableLayout</h2> +<p>{@link android.widget.TableLayout} positions its children into rows + and columns. TableLayout containers do not display border lines for their rows, columns, + or cells. The table will have as many columns as the row with the most cells. A table can leave +cells empty, but cells cannot span columns, as they can in HTML.</p> +<p>{@link android.widget.TableRow} objects are the child views of a TableLayout +(each TableRow defines a single row in the table). +Each row has zero or more cells, each of which is defined by any kind of other View. So, the cells of a row may be +composed of a variety of View objects, like ImageView or TextView objects. +A cell may also be a ViewGroup object (for example, you can nest another TableLayout as a cell).</p> +<p>The following image shows a table layout, with the invisible cell borders displayed as dotted lines. </p> + +<img src="{@docRoot}images/table_layout.png" alt="" /> + +<p>Columns can be hidden, marked to stretch and fill the available screen space, or can be marked as shrinkable to force the column to shrink until the table - fits the screen. See the reference documentation for this class for more details. </p> -<h2>AbsoluteLayout<a name="absolutelayout" id="absolutelayout"></a></h2> -<p>{@link android.widget.AbsoluteLayout AbsoluteLayout} enables children to specify - exact x/y coordinates to display on the screen, where (0,0) is the upper left - corner, and values increase as you move down or to the right. Margins are not + fits the screen. See the {@link android.widget.TableLayout TableLayout reference} +documentation for more details. </p> + +<p>To view sample code, see the <a href="{@docRoot}guide/tutorials/views/hello-tablelayout.html">Hello +TableLayout</a> tutorial.</p> + + +<h2 id="absolutelayout">AbsoluteLayout</h2> +<p>{@link android.widget.AbsoluteLayout} enables child views to specify + their own exact x/y coordinates on the screen. Coordinates <em>(0,0)</em> is the upper left + corner, and values increase as you move down and to the right. Margins are not supported, and overlapping elements are allowed (although not recommended). We generally recommend against using AbsoluteLayout unless you have good reasons - to use it, because it is fairly rigid and does not work well with different device + to use it, because it is fairly rigid and does not adjust to different types of displays. </p> -<h2>RelativeLayout<a name="relativelayout" id="relativelayout"></a></h2> -<p>{@link android.widget.RelativeLayout RelativeLayout} lets children specify their - position relative to each other (specified by ID), or to the parent. So you can - align two elements by right border, or make one below another, or centered in - the screen. Elements are rendered in the order given, so if the first element + + +<h2 id="relativelayout">RelativeLayout</h2> +<p>{@link android.widget.RelativeLayout} lets child views specify their + position relative to the parent view or to each other (specified by ID). So you can + align two elements by right border, or make one below another, centered in + the screen, centered left, and so on. Elements are rendered in the order given, so if the first element is centered in the screen, other elements aligning themselves to that element - will be aligned relative to screen center. If using XML to specify this layout - (as described later), a referenced element must be listed before you refer to - it. </p> + will be aligned relative to screen center. Also, because of this ordering, if using XML to specify this layout, + the element that you will reference (in order to position other view objects) must be listed in the XML +file before you refer to it from the other views via its reference ID. </p> <p>Here is an example relative layout with the visible and invisible elements outlined. The root screen layout object is a RelativeLayout object. </p> -<p><img src="{@docRoot}images/designing_ui_relative_layout.png" alt="RelativeLayout screen with elements highlighted." width="692" height="440" /></p> + +<img src="{@docRoot}images/designing_ui_relative_layout.png" alt="" /> + <p>This diagram shows the class names of the screen elements, followed by a list of the properties of each. Some of these properties are supported directly by the element, and some are supported by its LayoutParams member (subclass RelativeLayout for all the elements in this screen, because all elements are children of a RelativeLayout - parent object). The RelativeLayout parameters are width, height, below, alignTop, - toLeft, padding, and marginLeft. Note that some of these parameters support values - relative to other children — hence the name RelativeLayout. These include the - toLeft, alignTop, and below properties, which indicate the object to the left, - top, and below respectively. </p> -<h2>Summary of Important View Groups<a name="viewgroupsummary" id="viewgroupsummary"></a></h2> -<p>These objects all hold child UI elements. Some provide visible UI, and others - only handle child layout. </p> + parent object). The defined RelativeLayout parameters are: <code>width</code>, <code>height</code>, + <code>below</code>, <code>alignTop</code>, <code>toLeft</code>, <code>padding[Bottom|Left|Right|Top]</code>, + and <code>margin[Bottom|Left|Right|Top]</code>. Note that some of these parameters specifically support + relative layout positions — their values must be the ID of the element to which you'd like this view laid relative. + For example, assigning the parameter <code>toLeft="my_button"</code> to a TextView would place the TextView to + the left of the View with the ID <var>my_button</var> (which must be written in the XML <em>before</em> the TextView). </p> + +<p>To view this sample code, see the <a href="{@docRoot}guide/tutorials/views/hello-relativelayout.html">Hello +RelativeLayout</a> tutorial.</p> + + +<h2 id="viewgroupsummary">Summary of Important View Groups</h2> +<p>These objects all hold child UI elements. Some provide their own form of a visible UI, while others + are invisible structures that only manage the layout of their child views. </p> <table width="100%" border="1"> <tr> <th scope="col">Class</th> diff --git a/docs/html/guide/topics/views/themes.jd b/docs/html/guide/topics/views/themes.jd index 7c2e973..a206a4b 100644 --- a/docs/html/guide/topics/views/themes.jd +++ b/docs/html/guide/topics/views/themes.jd @@ -1,16 +1,39 @@ -page.title=Applying Styles and Themes to Your Application +page.title=Applying Styles and Themes +parent.title=Views and Layout +parent.link=index.html @jd:body +<div id="qv-wrapper"> +<div id="qv"> + + <h2>See also</h2> + <ol> + <li><a href="{@docRoot}guide/topics/resources/available-resources.html#stylesandthemes">Style and Theme Resources</a></li> + </ol> +</div> +</div> + <p>When designing your application, you can use <em>styles</em> and <em>themes</em> to apply uniform formatting to its various screens and UI elements. <ul> -<li>A style is a set of one or more formatting attributes that you can apply as a unit to single elements in your layout XML file(s). For example, you could define a style that specifies a certain text size and color, then apply it to instances of a certain type of View element. </li> -<li>A theme is a set of one or more formatting attributes that you can apply as a unit to all Activities in an application or to a single Activity. For example, you could define a theme that sets specific colors for the window frame and the panel foreground and background, and sets text sizes and colors for menus, then apply it to the Activities of your application.</li> + <li>A style is a set of one or more formatting attributes that you can apply as a unit to single elements in your layout XML file(s). For example, you could define a style that specifies a certain text size and color, then apply it to instances of a certain type of View element.</li> + <li>A theme is a set of one or more formatting attributes that you can apply as a unit to all activities in an application or just a single activity. For example, you could define a theme that sets specific colors for the window frame and the panel foreground and background, and sets text sizes and colors for menus, then apply it to the activities of your application.</li> </ul> -<p>Styles and themes are resources — Android provides a variety default style and theme resources that you can use, or you can declare your own custom style and theme resources. +<p>Styles and themes are resources. Android provides some default style and theme resources that you can use, or you can declare your own custom style and theme resources.</p> + +<p>To create custom styles and themes:</p> +<ol> + <li>Create a file named <code>styles.xml</code> in the your application's <code>res/values</code> directory. Add a root <code><resources></code> node.</li> + <li>For each style or theme, add a <code><style></code> element with a unique <code>name</code> and, optionally, a <code>parent</code> attribute. + The name is used for referencing these styles later, and the parent indicates what style resource to inherit from.</li> + <li>Inside the <code>style</code> element, declare format values in one or more <code><item></code> element. + Each <code>item</code> identifies its style property with a <code>name</code> attribute and defines its style value inside the element.</li> + <li>You can then reference the custom resources from other XML resources, your manifest or application code.</li> +</ol> -<p>To create custom styles and themes, you declare new resources in an XML file, stored in the your application's <code>res/values</code> directory. You can then reference the custom resources from your other XML resources or manifest or from application code. When declaring styles and themes, in an XML file, you use the same container element — a <code><style></code> element. Inside, you declare format values in one or more <code><item></code> elements.</p> + +<h2>Styles</h2> <p>Here's an example declaration of a style: </p> @@ -24,37 +47,99 @@ page.title=Applying Styles and Themes to Your Application </resources> </pre> -<p>As shown, you can use <code><item></code> elements to set formatting values for the style. The <code>name</code> attribute can refer to a standard string, a hex color value, or a reference to any other resource type.</p> +<p>As shown, you can use <code><item></code> elements to set specific formatting values for the style. +The <code>name</code> attribute in the <code>item</code> can refer to a standard string, a hex color value, +or a reference to any other resource type.</p> + +<p>Note the <code>parent</code> attribute in the <code>style</code> element. This attribute lets you specify a resource from which the current style will inherit values. The style can inherit from any type of resource that contains the style(s) you want. In general, your styles should always inherit (directly or indirectly) from a standard Android style resource. This way, you only have to define the values that you want to change.</p> -<p>Note the <code>parent</code> attribute in the <code>style</code> element. This attribute lets you specify a resource from which the current style will inherit values. The style can inherit from any type of resource that holds the style(s) you want. In general, your styles should always inherit (directly or indirectly) from a standard Android style resource, so that you only have to define the values that you want to change.</p> +<p>Here's how you would reference the custom style from an XML layout, in this case, for an EditText element:</p> + +<pre> +<EditText id="@+id/text1" + style="@style/SpecialText" + android:layout_width="fill_parent" + android:layout_height="wrap_content" + android:text="Hello, World!" /> +</pre> -<p>Here's how you would reference the custom style from a resource delared in XML, in this case, an EditText element:</p> +<p>Now this EditText widget will be styled as defined by the <code>style</code> example above.</p> -<pre><EditText id="@+id/text1" - style="@style/SpecialText" - android:layout_width="fill_parent" - android:layout_height="wrap_content" - android:text="Hello, World!" /></pre> -<p>Themes are declared in <code><style></code> elements also, and are referenced in the same manner, except that you can add a <code>style</code> attribute only to <code><application></code> and <code><activity></code> elements. If you do not explicitly specify a theme, the Android system applies default theme defined by {@link android.R.style#Theme}.</p> +<h2>Themes</h2> -<p>Here's an example of how you would set a theme for all the activites of your application. The example applies a default system theme <code>Theme.Translucent</code>.</p> +<p>Just like styles, themes are also declared in XML <code><style></code> elements, and are referenced in the same manner. +The difference is that you can add a theme style only to <code><application></code> and <code><activity></code> elements — +they cannot be applied to individual views in the layout.</p> + +<p>Here's an example declaration of a theme:</p> + +<pre> +<?xml version="1.0" encoding="utf-8"?> +<resources> + <style name="CustomTheme"> + <item name="android:windowNoTitle">true</item> + <item name="windowFrame">@drawable/screen_frame</item> + <item name="windowBackground">@drawable/screen_background_white</item> + <item name="panelForegroundColor">#FF000000</item> + <item name="panelBackgroundColor">#FFFFFFFF</item> + <item name="panelTextColor">?panelForegroundColor</item> + <item name="panelTextSize">14</item> + <item name="menuItemTextColor">?panelTextColor</item> + <item name="menuItemTextSize">?panelTextSize</item> + </style> +</resources> +</pre> +<p>Notice the use of the at-symbol (@) and the question-mark (?) to reference resources. +The at-symbol indicates that we're referencing a resource previously defined elsewhere (which may be from +this project or from the Android framework). +The question-mark indicates that we're referencing a resource value in the currently loaded theme. This +is done by referring to a specific <code><item></code> by its <code>name</code> value. (E.g., +<em>panelTextColor</em> uses the same color assigned to <em>panelForegroundColor</em>, defined beforehand.) +This technique can be used only in XML resources. +</p> + +<h3>Set the theme in the Manifest</h3> +<p>To set this theme for all the activites of your application, open the Manifest file and +edit the <code><application></code> tag to include the <code>android:theme</code> attribute with the +theme name:</p> + +<pre> +<application android:theme="@style/CustomTheme"> +</pre> + +<p>If you want the theme applied to just one Activity in your application, then add the theme +attribute to the <code><activity></code> tag, instead.</p> + +<p>Just as Android provides other built-in resources, there are several themes that you swap in +without having to write one yourself. For example, you can use the Dialog theme to make your Activity +appear like a dialog box. In the manifest, reference an Android theme like so:</p> + +<pre> +<activity android:theme="@android:style/Theme.Dialog"> +</pre> + +<p>If you like a theme, but want to slightly tweak it, just add the theme as the <code>parent</code> of your custom theme. +For example, we'll modify the <code>Theme.Dialog</code> theme. First, we need to import the parent of the +<code>Dialog</code> theme: <code>Theme</code>. At the top of the <code>resources</code>, add:</p> +<pre> +<style name="Theme" parent="@android:Theme"> + <!-- no modification --> +</style> +</pre> +<p>Now create a a new theme with <code>Theme.Dialog</code> as the parent:</p> <pre> -<!-- AndroidManifest.xml--> -<manifest xmlns:android="http://schemas.android.com/apk/res/android" - package="com.android.home"> - <application android:theme="@android:style/Theme.Translucent" > - <activity class=".Home" - ... - </activity> - </application> -</manifest> +<style name="CustomDialogTheme" parent="@android:style/Theme.Dialog"> </pre> +<p>There it is. We've inherited the Dialog theme, so we can adjust its styles as we like. +So, for each item in the Dialog theme that we want to override, we re-define the value under this style and +then use <var>CustomDialogTheme</var> instead of the <var>Theme.Dialog</var>.</p> +<h3>Set the theme from the application</h3> <p>You can also load a theme for an Activity programmatically, if needed. To do so, use the {@link android.app.Activity#setTheme(int) setTheme()} -method. Note that, when doing so, be sure to set the theme <em>before</em> +method. Note that, when doing so, you must be sure to set the theme <em>before</em> instantiating any Views in the context, for example, before calling setContentView(View) or inflate(int, ViewGroup). This ensures that the system applies the same theme for all of your UI screens. Here's an example:</p> @@ -76,7 +161,7 @@ you want to apply a theme to your main screen, doing so in XML is a better approach. </p> <p>For detailed information about custom styles and themes and referencing them from your application, see -<a href="{@docRoot}reference/available-resources.html#stylesandthemes">Style +<a href="{@docRoot}guide/topics/resources/available-resources.html#stylesandthemes">Style and Theme Resources</a>.</p> <p>For information about default themes and styles available, see {@link android.R.style}.</p> diff --git a/docs/html/guide/topics/views/ui-events.jd b/docs/html/guide/topics/views/ui-events.jd index 4230314..96136f8 100644 --- a/docs/html/guide/topics/views/ui-events.jd +++ b/docs/html/guide/topics/views/ui-events.jd @@ -1,13 +1,37 @@ page.title=Handling UI Events +parent.title=Views and Layout +parent.link=index.html @jd:body -<p>Many Android classes declare callback methods for handling relevant UI events such as keypresses, touch events, focus changes, and so on. For example, {@link android.app.Activity Activity} provides the methods onKeyDown() and onKeyUp() and {@link android.widget.TextView TextView} provides onFocusChanged(). </p> +<div id="qv-wrapper"> +<div id="qv"> + <h2>In this document</h2> + <ol> + <li><a href="#TouchMode">Touch Mode</a></li> + <li><a href="#Scrolling">Scrolling</a></li> + <li><a href="#EventCycle">Event Cycle</a></li> + </ol> -<p>In most cases, you can handle events just by overriding the appropriate handler methods. When an event is received, the Android system calls your handler method with the event data.</p> + <h2>See also</h2> + <ol> + <li><a href="{@docRoot}guide/tutorials/views/hello-formstuff.html">Hello Form Stuff tutorial</a></li> + </ol> +</div> +</div> -<p>However, some classes do not declare handler methods for specific events. For example, {@link android.widget.Button Button} does not declare an onClick() handler method. To handle such events, you need to create an anonymous class to act as a listener for the event, then register the listener with the target class object. The example below shows how to set up a handler for click events in a Button object. </p> +<p>Many Android classes declare callback methods for handling relevant UI events such as keypresses, +touch events, focus changes, and so on. For example, {@link android.app.Activity Activity} provides +the methods <code>onKeyDown()</code> and <code>onKeyUp()</code> and {@link android.widget.TextView TextView} +provides <code>onFocusChanged()</code>. </p> +<p>In most cases, you can handle events just by overriding the appropriate handler methods. +When an event is received, the Android system calls your handler method with the event data.</p> +<p>However, some classes do not declare handler methods for specific events. For example, +{@link android.widget.Button} does not declare an <code>onClick()</code> handler method. So, to handle a click event, +you need to create an anonymous class to act as a listener for the event, then register the listener with the +target class object (via the appropriate <code>set...Listener()</code> method). The example below shows how to set +up a handler for click events in a Button object. </p> </p> <pre>public class ExampleSendResult extends Activity @@ -16,7 +40,7 @@ page.title=Handling UI Events { ... - // Listen for button clicks. + // Capture our button from layout and listen for clicks. Button button = (Button)findViewById(R.id.corky); button.setOnClickListener(mCorkyListener); } @@ -26,6 +50,64 @@ page.title=Handling UI Events { public void onClick(View v) { - //handle click event... + //do something when the button is clicked } - };</pre> + }; +} +</pre> + + +<h2 id="TouchMode">Touch Mode</h2> + <p> + When a user is navigating a user interface via directional keys such as a D-pad, it is + necessary to give focus to actionable items such as buttons so the user can see + what will take input. If the device has touch capabilities, however, and the user + begins interacting with the interface by touching it, it is no longer necessary to + always highlight, or give focus to, a particular view. Thus, there is a mode + for interaction named "touch mode." + </p> + <p> + For a touch-capable device, once the user touches the screen, the device + will enter touch mode. From this point onward, only views for which + {@link android.view.View#isFocusableInTouchMode} is true will be focusable, such as text editing widgets. + Other views that are touchable, like buttons, will not take focus when touched; they will + simply fire their on-click listeners when pressed. + </p> + <p> + Any time a user hits a directional key, such as a D-pad direction, the view device will + exit touch mode, and find a view to take focus, so that the user may resume interacting + with the user interface without touching the screen. + </p> + <p> + The touch mode state is maintained across {@link android.app.Activity}s. To query the current state, you can call + {@link android.view.View#isInTouchMode} to see whether the device is currently in touch mode. + </p> + + +<h2 id="Scrolling">Scrolling</h2> + <p> + The framework provides basic support for views that wish to internally + scroll their content. This includes keeping track of the X and Y scroll + offset as well as mechanisms for drawing scrollbars. See + {@link android.view.View#scrollBy(int, int)}, {@link android.view.View#scrollTo(int, int)} for more details. + </p> + +<h2 is="EventCycle">Event Cycle</h2> + <p>The basic cycle of a view is as follows:</p> + <ol> + <li>An event comes in and is dispatched to the appropriate view. The view + handles the event and notifies any listeners.</li> + <li>If, in the course of processing the event, the view's bounds may need + to be changed, the view will call {@link android.view.View#requestLayout()}.</li> + <li>Similarly, if in the course of processing the event the view's appearance + may need to be changed, the view will call {@link android.view.View#invalidate()}.</li> + <li>If either {@link android.view.View#requestLayout()} or {@link android.view.View#invalidate()} were called, + the framework will take care of measuring, laying out, and drawing the tree + as appropriate.</li> + </ol> + + <p class="note"><strong>Note:</strong> The entire view tree is single threaded. You must always be on + the UI thread when calling any method on any view. + If you are doing work on other threads and want to update the state of a view + from that thread, you should use a {@link android.os.Handler}. + </p>
\ No newline at end of file diff --git a/docs/html/guide/topics/views/ui-xml.jd b/docs/html/guide/topics/views/ui-xml.jd index f0a23c9..8ae599c 100644 --- a/docs/html/guide/topics/views/ui-xml.jd +++ b/docs/html/guide/topics/views/ui-xml.jd @@ -1,4 +1,6 @@ page.title=Declaring a UI in XML +parent.title=Views and Layout +parent.link=index.html @jd:body <p>You can create your application's user interface in two ways: diff --git a/docs/html/guide/topics/wireless/bluetooth.jd b/docs/html/guide/topics/wireless/bluetooth.jd new file mode 100644 index 0000000..710cd4c --- /dev/null +++ b/docs/html/guide/topics/wireless/bluetooth.jd @@ -0,0 +1,18 @@ +page.title=Bluetooth +parent.title=Wireless Controls +parent.link=index.html +@jd:body + +<div id="qv-wrapper"> +<div id="qv"> + + <h2>In this document</h2> + <ol> + + </ol> + +</div> +</div> + + +TODO
\ No newline at end of file diff --git a/docs/html/guide/topics/wireless/index.jd b/docs/html/guide/topics/wireless/index.jd new file mode 100644 index 0000000..a3a2b36 --- /dev/null +++ b/docs/html/guide/topics/wireless/index.jd @@ -0,0 +1,19 @@ +page.title=Wireless Controls +@jd:body + + + +<h2>Wi-Fi</h2> +<p>The Wi-Fi APIs provide a means by which application can communicate with the lower-level +wireless stack that provides Wi-Fi network access. Almost all information from the device supplicant +is available, including the connected network's link speed, IP address, negotiation state, and more. +It also provides information about all non-connected available networks. Some of the available network +interactions include the ability to scan, add, dave, terminate and initiate connections.</p> + + +<h2>Bluetooth</h2> +<p>The Bluetooth APIs allow applications to scan, connect and pair with other Bluetooth devices. +THESE APIS ARE NOT YET AVAILABLE.</p> + + + diff --git a/docs/html/guide/topics/wireless/wifi.jd b/docs/html/guide/topics/wireless/wifi.jd new file mode 100644 index 0000000..520feaf --- /dev/null +++ b/docs/html/guide/topics/wireless/wifi.jd @@ -0,0 +1,18 @@ +page.title=Wi-Fi +parent.title=Wireless Controls +parent.link=index.html +@jd:body + +<div id="qv-wrapper"> +<div id="qv"> + + <h2>In this document</h2> + <ol> + + </ol> + +</div> +</div> + + +TODO
\ No newline at end of file |