diff options
Diffstat (limited to 'docs/html/guide/topics')
21 files changed, 3109 insertions, 573 deletions
diff --git a/docs/html/guide/topics/appwidgets/index.jd b/docs/html/guide/topics/appwidgets/index.jd new file mode 100644 index 0000000..01a9648 --- /dev/null +++ b/docs/html/guide/topics/appwidgets/index.jd @@ -0,0 +1,463 @@ +page.title=App Widgets +@jd:body + +<div id="qv-wrapper"> + <div id="qv"> + <h2>Key classes</h2> + <ol> + <li>{@link android.appwidget.AppWidgetProvider}</li> + <li>{@link android.appwidget.AppWidgetProviderInfo}</li> + <li>{@link android.appwidget.AppWidgetManager}</li> + </ol> + <h2>In this document</h2> + <ol> + <li><a href="#Basics">The Basics</a></li> + <li><a href="#Manifest">Declaring an App Widget in the Manifest</a></li> + <li><a href="#MetaData">Adding the AppWidgetProviderInfo Metadata</a></li> + <li><a href="#CreatingLayout">Creating the App Widget Layout</a></li> + <li><a href="#AppWidgetProvider">Using the AppWidgetProvider Class</a> + <ol> + <li><a href="#ProviderBroadcasts">Receiving App Widget broadcast Intents</a></li> + </ol> + </li> + <li><a href="#Configuring">Creating an App Widget Configuration Activity</a> + <ol> + <li><a href="#UpdatingFromTheConfiguration">Updating the App Widget from + the configuration Activity</a></li> + </ol> + </li> + </ol> + + <h2>See also</h2> + <ol> + <li><a href="{@docRoot}guide/practices/ui_guidelines/widget_design.html">App Widget Design + Guidelines</a></li> + <li><a href="http://android-developers.blogspot.com/2009/04/introducing-home-screen-widgets-and.html">Introducing + home screen widgets and the AppWidget framework »</a></li> + </ol> + </div> +</div> + + +<p>App Widgets are miniature application views that can be embedded in other applications +(such as the Home screen) and receive periodic updates. These views are referred +to as Widgets in the user interface, +and you can publish one with an App Widget provider. An application component that is +able to hold other App Widgets is called an App Widget host. The screenshot below shows +the Music App Widget.</p> + +<img src="{@docRoot}images/appwidget.png" alt="" /> + +<p>This document describes how to publish an App Widget using an App Widget provider.</p> + + +<h2 id="Basics">The Basics</h2> + +<p>To create an App Widget, you need the following:</p> + +<dl> + <dt>{@link android.appwidget.AppWidgetProviderInfo} object</dt> + <dd>Describes the metadata for an App Widget, such as the App Widget's layout, update frequency, + and the AppWidgetProvider class. This should be defined in XML.</dd> + <dt>{@link android.appwidget.AppWidgetProvider} class implementation</dt> + <dd>Defines the basic methods that allow you to programmatically interface with the App Widget, + based on broadcast events. Through it, you will receive broadcasts when the App Widget is updated, + enabled, disabled and deleted.</dd> + <dt>View layout</dt> + <dd>Defines the initial layout for the App Widget, defined in XML.</dd> +</dl> + +<p>Additionally, you can implement an App Widget configuration Activity. This is an optional +{@link android.app.Activity} that launches when the user adds your App Widget and allows him or her +to modify App Widget settings at create-time.</p> + +<p>The following sections describe how to setup each of these components.</p> + + +<h2 id="Manifest">Declaring an App Widget in the Manifest</h2> + +<p>First, declare the {@link android.appwidget.AppWidgetProvider} class in your application's +<code>AndroidManifest.xml</code> file. For example:</p> + +<pre> +<receiver android:name="ExampleAppWidgetProvider" > + <intent-filter> + <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> + </intent-filter> + <meta-data android:name="android.appwidget.provider" + android:resource="@xml/example_appwidget_info" /> +</receiver> +</pre> + +<p>The <code><receiver></code> element requires the <code>android:name</code> +attribute, which specifies the {@link android.appwidget.AppWidgetProvider} used +by the App Widget.</p> + +<p>The <code><intent-filter></code> element must include an <code><action></code> +element with the <code>android:name</code> attribute. This attribute specifies +that the {@link android.appwidget.AppWidgetProvider} accepts the {@link +android.appwidget.AppWidgetManager#ACTION_APPWIDGET_UPDATE ACTION_APPWIDGET_UPDATE} broadcast. +This is the only broadcast that you must explicitly declare. The {@link android.appwidget.AppWidgetManager} +automatically sends all other App Widget broadcasts to the AppWidgetProvider as necessary.</p> + +<p>The <code><meta-data></code> element specifies the +{@link android.appwidget.AppWidgetProviderInfo} resource and requires the +following attributes:</p> +<ul> + <li><code>android:name</code> - Specifies the metadata name. Use <code>android.appwidget.provider</code> + to identify the data as the {@link android.appwidget.AppWidgetProviderInfo} descriptor.</li> + <li><code>android:resource</code> - Specifies the {@link android.appwidget.AppWidgetProviderInfo} + resource location.</li> +</ul> + + +<h2 id="MetaData">Adding the AppWidgetProviderInfo Metadata</h2> + +<p>The {@link android.appwidget.AppWidgetProviderInfo} defines the essential +qualities of an App Widget, such as its minimum layout dimensions, its initial layout resource, +how often to update the App Widget, and (optionally) a configuration Activity to launch at create-time. +Define the AppWidgetProviderInfo object in an XML resource using a single +<code><appwidget-provider></code> element and save it in the project's <code>res/xml/</code> +folder.</p> + +<p>For example:</p> + +<pre> +<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" + android:minWidth="294dp" <!-- density-independent pixels --> + android:minHeight="72dp" + android:updatePeriodMillis="86400000" <!-- once per day --> + android:initialLayout="@layout/example_appwidget" + android:configure="com.example.android.ExampleAppWidgetConfigure" > +</appwidget-provider> +</pre> + +<p>Here's a summary of the <code><appwidget-provider></code> attributes:</p> +<ul> + <li>The values for the <code>minWidth</code> and <code>minHeight</code> attributes specify the minimum + area required by the App Widget's layout. + <p>The default Home screen positions App Widgets in its window based on a grid of + cells that have a defined height and width. If the values for an App Widget's minimum width + or height don't match the dimensions of the cells, + then the App Widget dimensions round <em>up</em> to the nearest cell size. + (See the <a href="{@docRoot}guide/practices/ui_guidelines/widget_design.html">App Widget Design + Guidelines</a> for more information on the Home screen cell sizes.)</p> + <p>Because the Home screen's layout orientation (and thus, the cell sizes) can change, + as a rule of thumb, you should assume the worst-case cell size of 74 pixels for the height + <em>and</em> width of a cell. However, you must subtract 2 from the final dimension to account + for any integer rounding errors that occur in the pixel count. To find your minimum width + and height in density-independent pixels (dp), use this formula:<br/> + <code>(number of cells * 74) - 2</code><br/> + Following this formula, you should use 72 dp for a height of one cell, 294 dp and for a width of four cells.</p> + </li> + <li>The <code>updatePerdiodMillis</code> attribute defines how often the App Widget framework should + request an update from the {@link android.appwidget.AppWidgetProvider} by calling the + {@link android.appwidget.AppWidgetProvider#onUpdate(Context,AppWidgetManager,int[]) + onUpdate()} method. The actual update is not guaranteed to occur exactly on time with this value + and we suggest updating as infrequently as possible—perhaps no more than once an hour to + conserve the battery. You might also allow the user to adjust the frequency in a + configuration—some people might want a stock ticker to update every 15 minutes, or maybe + only four times a day.</li> + <li>The <code>initialLayout</code> attribute points to the layout resource that defines the + App Widget layout.</li> + <li>The <code>configure</code> attribute defines the {@link android.app.Activity} to launch when + the user adds the App Widget, in order for him or her to configure App Widget properties. This is optional + (read <a href="#Configuring">Creating an App Widget Configuration Activity</a> below).</li> +</ul> + +<p>See the {@link android.appwidget.AppWidgetProviderInfo} class for more information on the +attributes accepted by the <code><appwidget-provider></code> element.</p> + + +<h2 id="CreatingLayout">Creating the App Widget Layout</h2> + +<p>You must define an initial layout for your App Widget in XML and save it in the project's +<code>res/layout/</code> directory. You can design your App Widget using the View objects listed +below, but before you begin designing your App Widget, please read and understand the +<a href="{@docRoot}guide/practices/ui_guidelines/widget_design.html">App Widget Design +Guidelines</a>.</p> + +<p>Creating the App Widget layout is simple if you're +familiar with <a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout in XML</a>. +However, you must be aware that App Widget layouts are based on {@link android.widget.RemoteViews}, +which do not support every kind of layout or view widget.</p> + +<p>A RemoteViews object (and, consequently, an App Widget) can support the +following layout classes:</p> + +<ul class="nolist"> + <li>{@link android.widget.FrameLayout}</li> + <li>{@link android.widget.LinearLayout}</li> + <li>{@link android.widget.RelativeLayout}</li> +</ul> + +<p>And the following widget classes:</p> +<ul class="nolist"> + <li>{@link android.widget.AnalogClock}</li> + <li>{@link android.widget.Button}</li> + <li>{@link android.widget.Chronometer}</li> + <li>{@link android.widget.ImageButton}</li> + <li>{@link android.widget.ImageView}</li> + <li>{@link android.widget.ProgressBar}</li> + <li>{@link android.widget.TextView}</li> +</ul> + +<p>Descendants of these classes are not supported.</p> + + +<h2 id="AppWidgetProvider">Using the AppWidgetProvider Class</h2> + +<div class="sidebox-wrapper"> + <div class="sidebox-inner"> + <p>You must declare your AppWidgetProvider class implementation as a broadcast receiver + using the <code><receiver></code> element in the AndroidManifest (see + <a href="#Manifest">Declaring an App Widget in the Manifest</a> above).</p> + </div> +</div> + +<p>The {@link android.appwidget.AppWidgetProvider} class extends BroadcastReceiver as a convenience +class to handle the App Widget broadcasts. The AppWidgetProvider receives only the event broadcasts that +are relevant to the App Widget, such as when the App Widget is updated, deleted, enabled, and disabled. +When these broadcast events occur, the AppWidgetProvider receives the following method calls:</p> + +<dl> + <dt>{@link android.appwidget.AppWidgetProvider#onUpdate(Context,AppWidgetManager,int[])}</dt> + <dd>This is called to update the App Widget at intervals defined by the <code>updatePeriodMillis</code> + attribute in the AppWidgetProviderInfo (see <a href="#MetaData">Adding the + AppWidgetProviderInfo Metadata</a> above). This method is also called + when the user adds the App Widget, so it should perform the essential setup, + such as define event handlers for Views and start a temporary + {@link android.app.Service}, if necessary. However, if you have declared a configuration + Activity, <strong>this method is not called</strong> when the user adds the App Widget, + but is called for the subsequent updates. It is the responsibility of the + configuration Activity to perform the first update when configuration is done. + (See <a href="#Configuring">Creating an App Widget Configuration Activity</a> below.)</dd> + <dt>{@link android.appwidget.AppWidgetProvider#onDeleted(Context,int[])}</dt> + <dd>This is called every time an App Widget is deleted from the App Widget host.</dd> + <dt>{@link android.appwidget.AppWidgetProvider#onEnabled(Context)}</dt> + <dd>This is called when an instance the App Widget is created for the first time. For example, if the user + adds two instances of your App Widget, this is only called the first time. + If you need to open a new database or perform other setup that only needs to occur once + for all App Widget instances, then this is a good place to do it.</dd> + <dt>{@link android.appwidget.AppWidgetProvider#onDisabled(Context)}</dt> + <dd>This is called when the last instance of your App Widget is deleted from the App Widget host. + This is where you should clean up any work done in + {@link android.appwidget.AppWidgetProvider#onEnabled(Context)}, + such as delete a temporary database.</dd> + <dt>{@link android.appwidget.AppWidgetProvider#onReceive(Context,Intent)}</dt> + <dd>This is called for every broadcast and before each of the above callback methods. + You normally don't need to implement this method because the default AppWidgetProvider + implementation filters all App Widget broadcasts and calls the above + methods as appropriate.</dd> +</dl> + +<p class="warning"><strong>Note:</strong> In Android 1.5, there is a known issue in which the +<code>onDeleted()</code> method will not be called when it should be. To work around this issue, +you can implement {@link android.appwidget.AppWidgetProvider#onReceive(Context,Intent) +onReceive()} as described in this +<a href="http://groups.google.com/group/android-developers/msg/e405ca19df2170e2">Group post</a> +to receive the <code>onDeleted()</code> callback. +</p> + +<p>The most important AppWidgetProvider callback is +{@link android.appwidget.AppWidgetProvider#onUpdate(Context,AppWidgetManager,int[]) +onUpdated()} because it is called when each App Widget is added to a host (unless you use +a configuration Activity). If your App Widget accepts any +user interaction events, then you need to register the event handlers in this callback. +If your App Widget doesn't create temporary +files or databases, or perform other work that requires clean-up, then +{@link android.appwidget.AppWidgetProvider#onUpdate(Context,AppWidgetManager,int[]) +onUpdated()} may be the only callback method you need to define. For example, if you want an App Widget +with a button that launches an Activity when clicked, you could use the following +implementation of AppWidgetProvider:</p> + +<pre> +public class ExampleAppWidgetProvider extends AppWidgetProvider { + + public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + final int N = appWidgetIds.length; + + // Perform this loop procedure for each App Widget that belongs to this provider + for (int i=0; i<N; i++) { + int appWidgetId = appWidgetIds[i]; + + // Create an Intent to launch ExampleActivity + Intent intent = new Intent(context, ExampleActivity.class); + PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); + + // Get the layout for the App Widget and attach an on-click listener to the button + RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.appwidget_provider_layout); + views.setOnClickPendingIntent(R.id.button, pendingIntent); + + // Tell the AppWidgetManager to perform an update on the current App Widget + appWidgetManager.updateAppWidget(appWidgetId, views); + } + } +} +</pre> + +<p>This AppWidgetProvider defines only the +{@link android.appwidget.AppWidgetProvider#onUpdate(Context,AppWidgetManager,int[]) +onUpdated()} method for the purpose +of defining a {@link android.app.PendingIntent} that launches an {@link android.app.Activity} +and attaching it to the App Widget's button +with {@link android.widget.RemoteViews#setOnClickPendingIntent(int,PendingIntent)}. +Notice that it includes a loop that iterates through each entry in <code>appWidgetIds</code>, which +is an array of IDs that identify each App Widget created by this provider. +In this way, if the user creates more than one instance of the App Widget, then they are +all updated simultaneously. However, only one <code>updatePeriodMillis</code> schedule will be +managed for all instances of the App Widget. For example, if the update schedule is defined +to be every two hours, and a second instance +of the App Widget is added one hour after the first one, then they will both be updated +on the period defined by the first one and the second update period will be ignored +(they'll both be updated every two hours, not every hour).</p> + +<p class="note"><strong>Note:</strong> Because the AppWidgetProvider is a BroadcastReceiver, +your process is not guaranteed to keep running after the callback methods return (see +<a href="{@docRoot}guide/topics/fundamentals.html#broadlife">Application Fundamentals > +Broadcast Receiver Lifecycle</a> for more information). If your App Widget setup process can take several +seconds (perhaps while performing web requests) and you require that your process continues, +consider starting a {@link android.app.Service} +in the {@link android.appwidget.AppWidgetProvider#onUpdate(Context,AppWidgetManager,int[]) +onUpdated()} method. From within the Service, you can perform your own updates to the App Widget +without worrying about the AppWidgetProvider closing down due to an +<a href="{@docRoot}guide/practices/design/responsiveness.html">Application Not Responding</a> +(ANR) error. See the +<a href="http://code.google.com/p/wiktionary-android/source/browse/trunk/Wiktionary/src/com/example/android/wiktionary/WordWidget.java">Wiktionary +sample's AppWidgetProvider</a> for an example of an App Widget running a {@link android.app.Service}.</p> + +<p>Also see the <a +href="{@docRoot}guide/samples/ApiDemos/src/com/example/android/apis/appwidget/ExampleAppWidgetProvider.html"> +ExampleAppWidgetProvider.java</a> sample class.</p> + + +<h3 id="ProviderBroadcasts">Receiving App Widget broadcast Intents</h3> + +<p>{@link android.appwidget.AppWidgetProvider} is just a convenience class. If you would like +to receive the App Widget broadcasts directly, you can implement your own +{@link android.content.BroadcastReceiver} or override the +{@link android.appwidget.AppWidgetProvider#onReceive(Context,Intent)} callback. +The four Intents you need to care about are:</p> +<ul> + <li>{@link android.appwidget.AppWidgetManager#ACTION_APPWIDGET_UPDATE}</li> + <li>{@link android.appwidget.AppWidgetManager#ACTION_APPWIDGET_DELETED}</li> + <li>{@link android.appwidget.AppWidgetManager#ACTION_APPWIDGET_ENABLED}</li> + <li>{@link android.appwidget.AppWidgetManager#ACTION_APPWIDGET_DISABLED}</li> +</ul> + + + +<h2 id="Configuring">Creating an App Widget Configuration Activity</h2> + +<p>If you would like the user to configure settings when he or she adds a new App Widget, +you can create an App Widget configuration Activity. This {@link android.app.Activity} +will be automatically launched by the App Widget host and allows the user to configure +available settings for the App Widget at create-time, such as the App Widget color, size, +update period or other functionality settings.</p> + +<p>The configuration Activity should be declared as a normal Activity in the Android manifest file. +However, it will be launched by the App Widget host with the {@link +android.appwidget.AppWidgetManager#ACTION_APPWIDGET_CONFIGURE ACTION_APPWIDGET_CONFIGURE} action, +so the Activity needs to accept this Intent. For example:</p> + +<pre> +<activity android:name=".ExampleAppWidgetConfigure"> + <intent-filter> + <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" /> + </intent-filter> +</activity> +</pre> + +<p>Also, the Activity must be declared in the AppWidgetProviderInfo XML file, with the +<code>android:configure</code> attribute (see <a href="#MetaData">Adding +the AppWidgetProvierInfo Metadata</a> above). For example, the configuration Activity +can be declared like this:</p> + +<pre> +<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" + ... + android:configure="com.example.android.ExampleAppWidgetConfigure" + ... > +</appwidget-provider> +</pre> + +<p>Notice that the Activity is declared with a fully-qualified namespace, because +it will be referenced from outside your package scope.</p> + +<p>That's all you need to get started with a configuration Activity. Now all you need is the actual +Activity. There are, however, two important things to remember when you implement the Activity:</p> +<ul> + <li>The App Widget host calls the configuration Activity and the configuration Activity should always + return a result. The result should include the App Widget ID + passed by the Intent that launched the Activity (saved in the Intent extras as + {@link android.appwidget.AppWidgetManager#EXTRA_APPWIDGET_ID}).</li> + <li>The {@link android.appwidget.AppWidgetProvider#onUpdate(Context,AppWidgetManager,int[]) + onUpdate()} method <strong>will not be called</strong> when the App Widget is created + (the system will not send the ACTION_APPWIDGET_UPDATE broadcast when a configuration Activity + is launched). It is the responsibility of the configuration Activity to request an update from the + AppWidgetManager when the App Widget is first created. However, + {@link android.appwidget.AppWidgetProvider#onUpdate(Context,AppWidgetManager,int[]) + onUpdate()} will be called for subsequent updates—it is only skipped the first time.</li> +</ul> + +<p>See the code snippets in the following section for an example of how to return a result +from the configuration and update the App Widget.</p> + + +<h3 id="UpdatingFromTheConfiguration">Updating the App Widget from the configuration Activity</h3> + +<p>When an App Widget uses a configuration Activity, it is the responsibility of the Activity +to update the App Widget when configuration is complete. +You can do so by requesting an update directly from the +{@link android.appwidget.AppWidgetManager}.</p> + +<p>Here's a summary of the procedure to properly update the App Widget and close +the configuration Activity:</p> + +<ol> + <li>First, get the App Widget ID from the Intent that launched the Activity: +<pre> +Intent intent = getIntent(); +Bundle extras = intent.getExtras(); +if (extras != null) { + mAppWidgetId = extras.getInt( + AppWidgetManager.EXTRA_APPWIDGET_ID, + AppWidgetManager.INVALID_APPWIDGET_ID); +} +</pre> + </li> + <li>Perform your App Widget configuration.</li> + <li>When the configuration is complete, get an instance of the AppWidgetManager by calling + {@link android.appwidget.AppWidgetManager#getInstance(Context)}: +<pre> +AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); +</pre> + </li> + <li>Update the App Widget with a {@link android.widget.RemoteViews} layout by calling + {@link android.appwidget.AppWidgetManager#updateAppWidget(int,RemoteViews)}: +<pre> +RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.example_appwidget); +appWidgetManager.updateAppWidget(mAppWidgetId, views); +</pre> + </li> + <li>Finally, create the return Intent, set it with the Activity result, and finish the Activity:</li> +<pre> +Intent resultValue = new Intent(); +resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId); +setResult(RESULT_OK, resultValue); +finish(); +</pre> + </li> +</ol> + +<p class="note"><strong>Tip:</strong> When your configuration Activity first opens, set +the Activity result to RESULT_CANCELED. This way, if the user backs-out of the Activity before +reaching the end, the App Widget host is notified that the configuration was cancelled and the +App Widget will not be added.</p> + +<p>See the <a +href="{@docRoot}guide/samples/ApiDemos/src/com/example/android/apis/appwidget/ExampleAppWidgetConfigure.html"> +ExampleAppWidgetConfigure.java</a> sample class in ApiDemos for an example.</p> + + + diff --git a/docs/html/guide/topics/fundamentals.jd b/docs/html/guide/topics/fundamentals.jd index 3c7f419..71705d3 100644 --- a/docs/html/guide/topics/fundamentals.jd +++ b/docs/html/guide/topics/fundamentals.jd @@ -464,7 +464,7 @@ two intent filters to the activity: </intent-filter> <intent-filter . . . > <action android:name="com.example.project.BOUNCE" /> - <data android:type="image/jpeg" /> + <data android:mimeType="image/jpeg" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> diff --git a/docs/html/guide/topics/geo/lbs.jd b/docs/html/guide/topics/geo/lbs.jd deleted file mode 100644 index 981f6fe..0000000 --- a/docs/html/guide/topics/geo/lbs.jd +++ /dev/null @@ -1,73 +0,0 @@ -page.title=Location-based Service APIs -@jd:body - -<p>The Android SDK includes two packages that provide Android's primary support -for building location-based services: -{@link android.location} and com.google.android.maps. -Please read on below for a brief introduction to each package.</p> - -<h2>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}reference/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> - diff --git a/docs/html/guide/topics/geo/mapkey.jd b/docs/html/guide/topics/geo/mapkey.jd deleted file mode 100644 index 6442940..0000000 --- a/docs/html/guide/topics/geo/mapkey.jd +++ /dev/null @@ -1,28 +0,0 @@ -page.title=Obtaining a MapView API Key -@jd:body - -<p>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/graphics/2d-graphics.jd b/docs/html/guide/topics/graphics/2d-graphics.jd index 1f62f3d..af584a2 100644 --- a/docs/html/guide/topics/graphics/2d-graphics.jd +++ b/docs/html/guide/topics/graphics/2d-graphics.jd @@ -10,8 +10,8 @@ parent.link=index.html <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> + <li><a href="#drawables-from-images">Creating from resource images</a></li> + <li><a href="#drawables-from-xml">Creating from resource XML</a></li> </ol> </li> <li><a href="#shape-drawable">ShapeDrawable</a></li> @@ -59,6 +59,15 @@ 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> +<p class="note"><strong>Note:</strong> Image resources placed in <code>res/drawable/</code> may be +automatically optimized with lossless image compression by the +<a href="{@docRoot}guide/developing/tools/aapt.html">aapt</a> tool. For example, a true-color PNG that does +not require more than 256 colors may be converted to an 8-bit PNG with a color palette. This +will result in an image of equal quality but which requires less memory. So be aware that the +image binaries placed in this directory can change during the build. If you plan on reading +an image as a bit stream in order to convert it to a bitmap, put your images in the <code>res/raw/</code> +folder instead, where they will not be optimized.</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> @@ -90,7 +99,7 @@ Resources res = mContext.getResources(); Drawable myImage = res.getDrawable(R.drawable.my_image); </pre> -<p class="caution"><strong>Caution:</strong> Each unique resource in your project can maintain only one +<p class="warning"><strong>Note:</strong> Each unique resource in your project can maintain only one state, no matter how many different objects you may instantiate for it. For example, if you instantiate two Drawable objects from the same image resource, then change a property (such as the alpha) for one of the Drawables, then it will also affect the other. So when dealing with multiple instances of an image resource, diff --git a/docs/html/guide/topics/graphics/opengl.jd b/docs/html/guide/topics/graphics/opengl.jd index eb2932d..901980d 100644 --- a/docs/html/guide/topics/graphics/opengl.jd +++ b/docs/html/guide/topics/graphics/opengl.jd @@ -26,10 +26,7 @@ ES API. However, it may not be identical, so watch out for deviations.</p> <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 +<p>For an example of this usage model (based on the classic GL ColorCube), 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> diff --git a/docs/html/guide/topics/location/geo/mapkey.jd b/docs/html/guide/topics/location/geo/mapkey.jd deleted file mode 100644 index 9aa824c..0000000 --- a/docs/html/guide/topics/location/geo/mapkey.jd +++ /dev/null @@ -1,210 +0,0 @@ -page.title=Obtaining a Maps API Key -@jd:body - -<div class="sidebox"><p>To register for a Maps API Key, read this document and then go to the <a href="http://code.google.com/android/maps-api-signup.html">Android Maps API Key Signup</a> page.</p> - -</div> - -<p>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 of Maps tiles, 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 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 for a Maps API Key is simple, free, and has two parts: </p> - -<ol> -<li>Registering the MD5 fingerprint of the certificate that you will use to sign your application. The Maps registration service then provides you a Maps API Key that is associated with your application's signer certificate. </li> -<li>Adding a reference to the Maps API Key in each MapView, whether declared in XML or instantiated directly from code. You can use the same Maps API Key for any MapView in any Android application, provided that the application is signed with the certificate whose fingerprint you registered with the service. </li> -</ol> - -<p>During registration, you also need to agree to the Maps API Terms of Service, which describe how your application can use the Maps data. In general, the terms of service are permissive and place few restrictions on how you can use the data. For example, the terms allow you to build "friend finder" type applications. </p> - -<p>The sections below describe how to obtain your Maps API Key and how to reference it from your MapView elements. </p> - -<ul> -<li><a href="#overview">Overview</a></li> -<li><a href="#getfingerprint">Getting the MD5 Fingerprint of Your Signing Certificate</a></li> -<li><a href="#getdebugfingerprint">Getting the MD5 Fingerprint of the SDK Debug Certificate</a></li> -<li><a href="#registering">Registering the Certificate Fingerprint with the Google Maps Service</a></li> -<li><a href="#addingkey">Adding the Maps API Key to your Application</a></li> -<li><a href="#finalsteps">Final Steps to Enable MapView Elements</a></li> -</ul> - -<h2 id="overview">Overview</h2> - -<p>MapView objects are views that display Maps tiles downloaded from the Google Maps service. To ensure that applications use Maps data in an appropriate manner, the Google Maps service requires application developers to register with the service, agreeing to the Terms of Service and supplying an MD5 fingerprint of the certificate(s) that they will use to sign applications. For each registered certificate fingerprint, the service then provides the developer with a Maps API Key — an alphanumeric string that uniquely identifies the certificate and developer registered with the service. </p> - -<p>The Google Maps service also requires that each MapView identify itself to the service using a Maps API Key. Before providing Maps tiles to a MapView, the service checks the Maps API Key supplied by the MapView to ensure that it:</p> -<ul> -<li>References a certificate/developer registered with the service, and </li> -<li>References a certificate that matches the certificate with which the application (containing the MapView) was signed. </li> -</ul> - -<p>Unless both conditions are met, the service does not provide Maps tiles to the MapView. </p> - -<p>Each MapView object in your application must reference a Maps API Key. Since the Key is associated with a certificate, all Mapview elements in an application should reference the same Key. Going a step further, all MapView elements in all applications that you sign with the same certificate should reference the same Key. </p> - -<p>On the other hand, you can register for multiple Maps API Keys, each being associated with a specific certificate. You would want to do this if, for example, you were developing several independent applications that you will sign using different certificates. In this case, note that all MapView elements in a given application can reference the same Maps API Key, but <em>must</em> reference the Key that is associated with the certificate used to sign the application. </p> - -<p>Because MapView elements must refer to a Maps API Key, you need to register your certificate and receive a Key before you can make use of MapView elements in your application. To make it easier for you to get started using MapView elements, you are welcome to register the debug certificate generated by the SDK tools and receive a temporary Maps API Key. The details of how to do that are given below. </p> - -<p>When you are preparing to release your application, however, note that you <em>must</em> sign your application with a suitable cryptographic key, rather than the SDK debug key. That means that you will also need to register your application's release certificate with the Google Maps service. After you've done so, you will receive a new Maps API Key that is uniquely associated with your release certificate. To enable the MapView elements in your application to work after release, you must remember to change the Maps API Key for all MapViews in your application so that they refer to the Key associated with your release certificate (rather than your debug certificate). </p> - -<p>To summarize, the important points to understand about MapViews and the Maps API Key are: </p> - -<ul> -<li>To display Maps data in a MapView, you need to register for a Maps API Key</li> -<li>Each Maps API Key is uniquely associated with a specific certificate, based on an MD5 fingerprint of the certificate </li> -<li>Each MapView must reference a Maps API Key, and the Key referenced must be registered to the certificate used to sign the application</li> -<li>All MapView elements in an application can reference the same Maps API Key</li> -<li>You can register multiple certificates under your developer identity</li> -<li>You can get a temporary Maps API Key based on your debug certificate, but before you publish your application, you must register for a new Key based on your release certificate and update references in your MapViews accordingly</li> -</ul> - -<h2 id="getfingerprint">Getting the MD5 Fingerprint of Your Signing Certificate</h2> - -<div class="sidebox"> -For more information about using Keytool and Jarsigner to sign your application, see <a href="{@docRoot}guide/publishing/app-signing.html">Signing Your Applications</a>. -</div> - -<p>To register for a Maps API Key, you need to provide an MD5 fingerprint of the certificate that you will use to sign your application. </p> - -<p>Before you visit the registration page, use Keytool to generate the fingerprint of the appropriate certificate. - -<p>First, determine which key you will use to sign your application at release and make sure of the path to the keystore that contains it.</p> - -<p>Next, run Keytool with the <code>-list</code> option, against the target keystore and key alias. The table below lists the options you should use.</p> - -<table> -<tr> -<th>Keytool Option</th> -<th>Description</th> -</tr> -<tr> -<td><code>-list</code></td><td>Print an MD5 fingerprint of a certificate.</td> -</tr> -<tr> -<td><code>-keystore <keystore-name>.keystore</code></td><td>The name of the keystore containing the target key.</td> -</tr> -<tr> -<td><code>-storepass <password></code></td><td><p>A password for the -keystore.</p><p>As a security precaution, do not include this option -in your command line unless you are working at a secure computer. -If not supplied, Keytool prompts you to enter the password. In this -way, your password is not stored in your shell history.</p></td> -</tr> -<tr> -<td><code>-alias <alias_name></code></td><td>The alias for the key for which to generate the MD5 certificate fingerprint.</td> -</tr> -<tr> -<td><code>-keypass <password></code></td><td><p>The password for the key.</p> -<p>As a security precaution, do not include this option -in your command line unless you are working at a secure computer. -If not supplied, Keytool prompts you to enter the password. In this -way, your password is not stored in your shell history.</p></td> -</tr> -</table> - -<p>Here's an example of a Keytool command that generates an MD5 certificate fingerprint for the key <code>alias_name</code> in the keystore <code>my-release-key.keystore</code>:</p> - -<pre>$ keytool -list -alias alias_name -keystore my-release-key.keystore</pre> - -<p>Keytool will prompt you to enter passwords for the keystore and key. As output of the command, Keytool prints the fingerprint to the shell. For example:</p> - -<pre>Certificate fingerprint (MD5): 94:1E:43:49:87:73:BB:E6:A6:88:D7:20:F1:8E:B5:98</pre> - -<p>Note that, if you happen to forget your Maps API Key, you can repeat the process described above and register the fingerprint again. The server will give you the same key for the specified certificate fingerprint.</p> - -<p>Once you have the fingerprint, you can go to the Maps API registration site, described next.</p> - -<h2 id="getdebugfingerprint">Getting the MD5 Fingerprint of the SDK Debug Certificate</h2> - -<p>While you are developing and debugging your application, you will likely be -sigining your application in debug mode — that is, the SDK build tools -will automatically sign your application using the debug certificate. To let -your MapView elements properly display Maps data during this period, you should -obtain a temporary Maps API Key registered to the debug certificate. To do so, -you first need to get the MD5 fingerprint of the debug certificate. When -you are ready to release your application, you must register your release -certificate with the Google Maps service and obtain a new Maps API Key. You must -then change the MapView elements in your application to reference the new API -key. </p> - -<p>To generate an MD5 fingerprint of the debug certificate, first locate the debug keystore. The location at which the SDK tools create the default debug keystore varies by platform: </p> - -<ul> -<li>Windows Vista: <code>C:\Users\<user>\AppData\Local\Android\debug.keystore</code></li> -<li>Windows XP: <code>C:\Documents and Settings\<user>\Local Settings\Application Data\Android\debug.keystore</code></li> -<li>OS X and Linux: <code>~/.android/debug.keystore</code></li> -</ul> - -<p>If you are using Eclipse/ADT and are unsure where the debug keystore is located, you can select <strong>Windows</strong> > <strong>Prefs</strong> > <strong>Android</strong> > <strong>Build</strong> to check the full path, which you can then paste into a file explorer to locate the directory containing the keystore.</p> - -<p>Once you have located the keystore, use this Keytool command to get the MD5 fingerprint of the debug certificate:</p> - -<pre>$ keytool -list -alias androiddebugkey \ --keystore <path_to_debug_keystore>.keystore \ --storepass android -keypass android</pre> - -<h2 id="registering">Registering the Certificate Fingerprint with the Google Maps Service</h2> - -<p>When you are ready to register for a Maps API Key, load this page in a browser: </p> - -<p><a href="http://code.google.com/android/maps-api-signup.html">http://code.google.com/android/maps-api-signup.html</a></p> - -<p>To register for a Maps API Key, follow these steps:</p> - -<ol> -<li>If you don't have a Google account, use the link on the page to set one up. </li> -<li>Read the Android Maps API Terms of Service carefully. If you agree to the terms, indicate so using the checkbox on the screen. </li> -<li>Paste the MD5 certificate fingerprint of the certificate that you are registering into the appropriate form field.</li> -<li>Click "Generate API Key"</li> -</ol> - -<p>The server will handle your request, associating the fingerprint with your developer identity and generating a unique Maps API Key, then returning a results page that gives you your Key string. </p> - -<p>To use the Maps API Key string, copy and paste it into your code as described in the next section.</p> - -<h2 id="addingkey">Adding the Maps API Key to your Application</h2> - -<p>Once you've registered with the Google Maps service and have obtained a Maps API Key, you must add it to your application's MapView objects, so that the Maps server will allow them to download Maps tiles. </p> - -<p>For <code><MapView></code> elements declared in XML layout files, add the Maps API Key as the value of a special attribute — <code>android:apiKey</code>. For example: </li> - -<pre><com.google.android.maps.MapView - android:layout_width="fill_parent" - android:layout_height="fill_parent" - android:enabled="true" - android:clickable="true" - android:apiKey="example_Maps_ApiKey_String" - /></pre> -</li> - -<p>For MapView objects instantiated directly from code, pass the Maps API Key string as a parameter in the constructor. For example: </p> - -<pre>mMapView = new MapView(this, "example_Maps_ApiKey_String");</pre> - -<p>For more information about MapView, see the MapView class Documentation. </p> - -<h2 id="finalsteps">Final Steps to Enable MapView Elements</h2> - -<p>If you've added the Maps API Key to the MapViews in your application, here are the final steps to enable the MapView elements to run properly:</p> - -<ul> -<li>Make sure that you added a <code><uses-library></code> element referencing the external <code>com.google.android.maps</code> library. The element must be a child of the <code><application></code> element in the application's manifest. For example: - -<p><pre><manifest xmlns:android="http://schemas.android.com/apk/res/android" - package="com.example.package.name"> - ... - <application android:name="MyApplication" > - <uses-library android:name="com.google.android.maps" /> - ... - </application></pre></p></li> - -<li>Sign your application with the certificate that corresponds to the Maps API Key referenced in your MapView elements. </li> - -</ul> - -<div class="special"><p>Note that, when you are ready to publish your application, you must get a Maps API Key that is based on the certificate that you will use to sign the application for release. You must then change the Maps API Key string referenced by all of your MapView elements, so that they reference the new Key. </p></div> - - - diff --git a/docs/html/guide/topics/location/index.jd b/docs/html/guide/topics/location/index.jd index 53f1d29..e988ecb 100644 --- a/docs/html/guide/topics/location/index.jd +++ b/docs/html/guide/topics/location/index.jd @@ -1,35 +1,43 @@ -page.title=Location +page.title=Location and Maps @jd:body <div id="qv-wrapper"> <div id="qv"> + <h2>Location and Maps quickview</h2> + <ul> + <li>Android provides a location framework that your application can use to determine the device's location and bearing and register for updates.</li> + <li>A Google Maps external library is available that lets you display and manage Maps data.</li> + </ul> <h2>In this document</h2> <ol> - <li><a href="#location">android.location</a></li> - <li><a href="#maps">com.google.android.maps</a></li> + <li><a href="#location">Location Services</a></li> + <li><a href="#maps">Google Maps External Library</a></li> + </ol> + <h2>See Also</h2> + <ol> + <li><a href="http://code.google.com/android/add-ons/google-apis/index.html">Google APIs add-on download»</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> +<p>Location- and maps-based applications and services are compelling for mobile device users. You can build these capabilities into your applications using the classes of the {@link android.location} package and the Google Maps external library. The sections below provide details. </p> + +<h2 id="location">Location Services</h2> -<h2 id="location">android.location</h2> +<p>Android gives your applications access to the location services supported by +the device through the classes in the <code>android.location</code> package. The +central component of the location framework is the +{@link android.location.LocationManager} system service, which provides an API to +determine location and bearing if the underlying device (if it supports location +capabilities). </p> -<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>As with other system services, you do not instantiate a LocationManager directly. +Rather, you request an LocationManager instance from the system by calling +{@link android.content.Context#getSystemService(String) getSystemService(Context.LOCATION_SERVICE)}. +The method returns a handle to a new LocationManager instance.</p> -<p>Once your application has a handle to the LocationManager, your application +<p>Once your application has a handle to a LocationManager instance, your application will be able to do three things:</p> <ul> @@ -42,20 +50,20 @@ will be able to do three things:</p> 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>However, during initial development in the emulator, you may not have access to real +data from a real location provider (Network or GPS). In that case, it may be necessary to +spoof some data for your application using a mock location provider.</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 +previous versions of the SDK, 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> - +Please follow the new procedures outlined 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> +ways to send it some mock location data: you can use the DDMS tool or the "geo" command +option in the emulator console.</p> <h4 id="ddms">Using DDMS</h4> <p>With the DDMS tool, you can simulate location data a few different ways:</p> @@ -67,9 +75,9 @@ ways to send it some spoof location data: with the DDMS tool or the "geo" comman <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> +<h4 id="geo">Using the "geo" command in the emulator console</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> +your SDK's <code>/tools</code> directory. Connect to the emulator console. 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> @@ -82,28 +90,51 @@ your SDK's <code>/tools</code> directory. Now you can use:</p> </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/topics/location/geo/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> +<p>For information about how to connect to the emulator console, see +<a href="{@docRoot}guide/developing/tools/emulator.html#console">Using the Emulator Console</a>.</p> + +<h2 id="maps">Google Maps External Library</h2> + +<p>To make it easier for you to add powerful mapping capabilities to your +application, Google provides a Maps external library that includes the +com.google.android.maps package. The classes of the com.google.android.maps +package offer built-in downloading, rendering, and caching of Maps tiles, as +well as a variety of display options and controls. </p> + +<p>The key class in the Maps package is +<code>com.google.android.maps.MapView</code>, a subclass of +{@link android.view.ViewGroup ViewGroup}. A MapView displays a map with data obtained +from the Google Maps service. When the MapView has focus, it will capture +keypresses and touch gestures to pan and zoom the map automatically, including +handling network requests for additional maps tiles. It also provides all of the +UI elements necessary for users to control the map. Your application can also +use MapView class methods to control the MapView programmatically and draw a +number of Overlay types on top of the map. </p> + +<p>In general, the MapView class provides a wrapper around the Google Maps API +that lets your application manipulate Google Maps data through class methods, +and it lets you work with Maps data as you would other types of Views.</p> + +<p>The Maps external library is not part of the standard Android library, so it +may not be present on some compliant Android-powered devices. Similarly, the +Maps external library is not included in the standard Android library provided +in the SDK. So that you can develop using the classes of the +com.google.android.maps package, the Maps external library is made available to +you as part of the Google APIs add-on for the Android SDK. </p> + +<p>To learn more about the Maps external library and how to download and use the +Google APIs add-on, visit</p> + +<p style="margin-left:2em;"><a +href="http://code.google.com/android/add-ons/google-apis">http://code.google.com/android/add-ons/google-apis</a></p> + +<p>For your convenience, the Google APIs add-on is also included in the Android +SDK. <!-- To learn now to use the Maps external library in your application, see +[[Using External Libraries]].--></p> + +<p class="note"><strong>Note:</strong> In order to display Google Maps data in a +MapView, you must register with the Google Maps service and obtain a Maps API +Key. For information about how to get a Maps API Key, see <a +href="http://code.google.com/android/add-ons/google-apis/mapkey.html">Obtaining +a Maps API Key</a>.</p> diff --git a/docs/html/guide/topics/media/index.jd b/docs/html/guide/topics/media/index.jd index 4541024..96c500c 100644 --- a/docs/html/guide/topics/media/index.jd +++ b/docs/html/guide/topics/media/index.jd @@ -9,24 +9,33 @@ page.title=Audio and Video <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> +<li>Built-in codecs for a variety of media. See <a href="{@docRoot}guide/appendix/media-formats.html">Android Supported 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> +<li>{@link android.media.MediaPlayer MediaPlayer} (all available formats)</li> +<li>{@link android.media.MediaRecorder MediaRecorder} (all available formats)</li> +<li>{@link android.media.JetPlayer JetPlayer} (playback, JET content)</li> +<li>{@link android.media.SoundPool SoundPool} (sound management)</li> </ol> <h2>In this document</h2> <ol> -<li><a href="#playback.html">Audio and Video Playback</a></li> +<li><a href="#playback.html">Audio and Video Playback</a> + <ol> + <li><a href="#playraw">Playing from a Raw Resource</li> + <li><a href="#playfile">Playing from a File or Stream</li> + <li><a href="#jet">Playing JET Content</li> + </ol> +</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> +<li><a href="{@docRoot}guide/topics/media/jet/jetcreator_manual.html">JetCreator User Manual</a></li> </ol> </div> @@ -115,6 +124,28 @@ above.</p> If you're passing a URL to an online media file, the file must be capable of progressive download.</p> +<h3 id="jet">Playing JET content</h3> +<p>The Android platform includes a JET engine that lets you add interactive playback of JET audio content in your applications. You can create JET content for interactive playback using the JetCreator authoring application that ships with the SDK. To play and manage JET content from your application, use the {@link android.media.JetPlayer JetPlayer} class.</p> + +<p>For a description of JET concepts and instructions on how to use the JetCreator authoring tool, see the <a href="{@docRoot}guide/topics/media/jet/jetcreator_manual.html">JetCreator User Manual</a>. The tool is available fully-featured on the OS X and Windows platforms and the Linux version supports all the content creation features, but not the auditioning of the imported assets. </p> + +<p>Here's an example of how to set up JET playback from a .jet file stored on the SD card:</p> + +<pre> +JetPlayer myJet = JetPlayer.getJetPlayer(); +myJet.loadJetFile("/sdcard/level1.jet"); +byte segmentId = 0; + +// queue segment 5, repeat once, use General MIDI, transpose by -1 octave +myJet.queueJetSegment(5, -1, 1, -1, 0, segmentId++); +// queue segment 2 +myJet.queueJetSegment(2, -1, 0, 0, 0, segmentId++); + +myJet.play(); +</pre> + +<p>The SDK includes an example application — JetBoy — that shows how to use {@link android.media.JetPlayer JetPlayer} to create an interactive music soundtrack in your game. It also illustrates how to use JET events to synchronize music and game logic. The application is located at <code><sdk>/platforms/android-1.5/samples/JetBoy</code>. + <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> diff --git a/docs/html/guide/topics/media/jet/jetcreator_manual.jd b/docs/html/guide/topics/media/jet/jetcreator_manual.jd new file mode 100644 index 0000000..9692d97 --- /dev/null +++ b/docs/html/guide/topics/media/jet/jetcreator_manual.jd @@ -0,0 +1,1152 @@ +page.title=SONiVOX JETCreator User Manual +@jd:body + + + +<p>Content Authoring Application for the JET Interactive Music Engine</p> + + +<h1>1 Introduction</h1> + +<h2>1.1 Overview</h2> + +<p>This document contains the user guidelines +for the SONiVOX JET Creator, an authoring application for creating and +auditioning JET files. JET is an interactive music player for small embedded +devices, including the those running the Android platform. It allows applications to +include interactive music soundtracks, in MIDI +format, that respond in real-time to game play events and user interaction.</p> + + +<p>JET works in conjunction with SONiVOX's +Embedded Audio Synthesizer (EAS) which is the MIDI +playback device for Android. Both the +JET and EAS engines are integrated into the Android embedded platform through the +{@link android.media.JetPlayer} class, as well +as inherent in the JET Creator application. As such, the JET content author can +be sure that the playback will sound exactly the same in both the JET Creator +and the final Android application playing back on Android mobile devices.</p> + + +<p>In addition to the graphical user +interface, there are two main functionalities taking place in JET Creator. The +first involves gathering all the source data (MIDI +files and DLS file), adding JET's real-time attributes and building a JET +(.jet) file that the Android application will use. The second functionality +involves auditioning the interactive playback elements as they will take place +in the Android application.</p> + + +<p>The JET Creator application is written in +the Python programming language, therefore you need to have the current version +of Python and WXWidgets installed. There is both a Mac and Windows version.</p> + + +<h2>1.2 Abbreviations and Common Terms</h2> + +<p>It is important to use a common set of +terms to minimize confusion. Since JET uses MIDI +in a unique way, normal industry terms may not always suffice. Here is the +definition of terms as they are used in this document and in the JET Creator +application:</p> + + +<p><i>Channel</i>: MIDI data associated with a specific MIDI +channel. Standard MIDI allows for 16 channels of MIDI +data each of which are typically associated with a specific instrument. </p> + + + +<p><i>Controller</i>: A MIDI event consisting of a +channel number, controller number, and a controller value. The MIDI + spec associates many controller numbers with +specific functions, such as volume, expression, sustain pedal, etc. JET also +uses controller events as a means of embedding special control information in a +MIDI sequence to provide for audio synchronization.</p> + + + +<p><i>DAW</i>: Digital Audio Workstation. A common term for MIDI +and audio sequencing applications such as Logic, SONAR, Cubase and others. </p> + + + +<p><i>EAS:</i> Embedded MIDI Synthesizer. The +name of the SONiVOX MIDI synthesizer engine.</p> + + + +<p><i>JET</i>: Jet Interactive Engine. The name of the SONiVOX JET interactive +music engine.</p> + + + +<p><i>M/B/T</i>: Measures, Beats and Ticks</p> + + + +<p><i>Segment</i>: A musical section such as a chorus or verse that is a component of +the overall composition. In JET, a segment can be an entire MIDI file or a +derived from a portion of a MIDI file.</p> + + + +<p><i>SMF-0</i>: Standard MIDI File Type 0, a MIDI file that contains a single +track, but may be made up of multiple channels of MIDI +data.</p> + + + +<p><i>SMF-1</i>: Standard MIDI File Type 1, a MIDI file that contains a one more +tracks, and each track may in turn be made up of one or more channels of MIDI + data. By convention, each channel is stored on a +separate track in an SMF-1 file. However, it is possible to have multiple MIDI +channels on a single track, or multiple tracks that contain data for the same MIDI +channel.</p> + + + +<p><i>Track</i>: A single track in a DAW containing a timed sequence of events. Be careful not to confuse Tracks with +Channels. A MIDI file may contain many tracks with several tracks utilizing the +same MIDI channel. </p> + + + + + +<h1>2 The JET Interactive Music Concept</h1> + +<p>Interactive music can be defined as music +that changes in real-time according to non-predictable events such as user +interaction or game play events. In this way, interactive music is much more +engaging as it has the ability to match the energy and mood of a game much +closer than a pre-composed composition that never changes. In some applications +and games, interactive music is central to the game play. Guitar Hero is one +such popular game. When the end user successfully captures the musical notes +coming down the fret board, the music adapts itself and simultaneously keeps +score of successes and failures. JET allows for these types of music driven +games as well.</p> + + + +<p>There are several methods for making and +controlling interactive music and JET is one such method. This section +describes the features of JET and how they might be used in a game or software +application. It also describes how JET can be used to save memory in small +footprint devices such as Android enabled mobile handsets.</p> + +<h3>2.1.1 Data Compression</h3> + +<p>JET supports a flexible music format that +can be used to create extended musical sequences with a minimal amount of data. +A musical composition is broken up into segments that can be sequenced to +create a longer piece. The sequencing can be fixed at the time the music file +is authored, or it can be created dynamically under program control.</p> + +<h3>2.1.2 Linear Music Example</h3> + +<p> +<img border=0 width=575 height=393 src="{@docRoot}images/jet/linear_music.png"> +<br>Figure 1: Linear Music Piece</p> + +<p>This diagram shows how musical segments are +stored. Each segment is authored as a separate MIDI +file. A post-processing tool combines the files into a single container file. +Each segment can contain alternate music tracks that can be muted or un-muted +to create additional interest. An example might be a brass accent in the chorus +that is played only the last time through. Also, segments can be transposed up +or down.</p> + + +<p>The bottom part of the diagram shows how +the musical segments can be recombined to create a linear music piece. In this +example, the bridge might end with a half-step key modulation and the remaining +segments could be transposed up a half-step to match.</p> + +<h3>2.1.3 Non-linear Music Example</h3> + +<p> +<img border=0 width=576 height=389 +src="{@docRoot}images/jet/nonlinear_music.png"> +<br>Figure 2: Non-linear music piece</p> + + +<p>In this diagram, we see a non-linear music +piece. The scenario is a first-person-shooter (FPS) and JET is providing the +background music. The intro plays as the level is loading and then transitions +under program control to the Searching segment. This segment is repeated indefinitely, +perhaps with small variations (using the mute/un-mute feature) until activity +in the game dictates a change.</p> + + + +<p>As the player nears a monster lair, the +program starts a synchronized transition to the Danger segment, increasing the +tension level in the audio. As the player draws closer to the lair, additional +tracks are un-muted to increase the tension.</p> + + + +<p>As the player enters into combat with the +monster, the program starts a synchronized transition to the Combat segment. +The segment repeats indefinitely as the combat continues. A Bonus Hit +temporarily un-mutes a decorative track that notifies the player of a +successful attack, and similarly, another track is temporarily un-muted to +signify when the player receives Special Damage.</p> + + + +<p>At the end of combat, the music transitions +to a victory or defeat segment based on the outcome of battle.</p> + +<h3>2.1.4 Mute/Un-mute Synchronization</h3> + +<p>JET can also synchronize the muting and +un-muting of tracks to events in the music. For example, in the FPS game, it would +probably be desirable to place the musical events relating to bonuses and +damage as close to the actual game event as possible. However, simply un-muting +a track at the moment the game event occurs might result in a music clip +starting in the middle. Alternatively, a clip could be started from the +beginning, but then it wouldn't be synchronized with the other music tracks.</p> + + +<p>However, with the JET sync engine, a clip +can be started at the next opportune moment and maintain synchronization. This +can be accomplished by placing a number of short music clips on a decorative +track. A MIDI event in the stream signifies +the start of a clip and a second event signifies the end of a clip. When the +application calls the JET clip function, the next clip in the track is allowed +to play fully synchronized to the music. Optionally, the track can be +automatically muted by a second MIDI event.</p> + + +<p> +<img border=0 width=576 height=155 +src="{@docRoot}images/jet/sync_muteunmute.png"> +<br>Figure 3: Synchronized Mute/Unmute</p> + + +<h2>2.2 Audio Synchronization</h2> + +<p>JET provides an audio synchronization API +that allows game play to be synchronized to events in the audio. The mechanism +relies on data embedded in the MIDI file at +the time the content is authored. When the JET engine senses an event during +playback it generates a callback into the application program. The timing of +the callback can be adjusted to compensate for any latency in the audio +playback system so that audio and video can be synchronized. The diagram below +shows an example of a simple music game that involves pressing the left and +right arrows in time with the music.</p> + +<p><img border=0 width=576 height=134 +src="{@docRoot}images/jet/music_game.png"> +<br>Figure 4: Music Game</p> + + + +<p>The arrows represent events in the music sequence +where game events need to be synchronized. In this case, the blue arrow +represents a time where the player is supposed to press the left button, and +the red arrow is for the right button. The yellow arrow tells the game engine +that the sequence is complete. The player is allowed a certain time window +before and after the event to press the appropriate key.</p> + + + +<p>If an event is received and the player has +not pressed a button, a timer is set to half the length of the window. If the +player presses the button before the timer expires, the game registers a +success, and if not, the game registers a failure. </p> + + + +<p>If the player presses the button before the +event is received, a timer is set to half the length of the window. If an event +is received before the timer expires, the game registers a success, and if not, +the game registers a failure. Game play might also include bonuses for getting +close to the timing of the actual event. </p> + + + +<h1>3 JET Content Authoring Overview</h1> + +<p>To author JET files and hear them playback +interactively, the content author will work in two applications which are +designed to work together smoothly. The first is application is any +off-the-shelf MIDI sequencing application that +supports VST (for PC) or AU (for Mac) plugins. Here the author will compose +their MIDI music files using the plugin as the +synthesizer device. The second application is the JET Creator application. Here +the author will import their MIDI music files +(and optionally a DLS2 soundset) and setup the conditions for interactive +playback within the JET enabled game. Optionally the content author may create +a custom set of DLS instruments using an instrument editor that supports the +DLS Level 2 format. One such application is Awave from MJSoft. </p> + +<p>Please see the JET Content Authoring Guidelines</i> documentation for additional +details on content authoring.</p> + + + +<h1>4 Installing and Launching JET Creator</h1> + +<p>JET Creator is a python language +application, therefore, you must have Python and wxPython installed on your +machine. </p> + + +<p>JetCreator was created and tested with:</p> + +<p>Python Version 2.5.4</p> + +<p>wxPython Version 2.8.7.1</p> + + +<p>These can be downloaded here:</p> + + + +<p>PC:</p> +<ul> +<li>http://www.python.org/download/releases/2.5.4/</li> + +<li>http://www.wxpython.org/download.php</li> +</ul> + + +<p>MAC:</p> +<ul> +<li>http://wiki.python.org/moin/MacPython/Leopard</li> + +<li>http://www.wxpython.org/download.php</li> +</ul> + + +<p>After installing Python and wxPython, +simply unzip or copy all the files in the JET Creator application directory to +a folder on your hard drive.</p> + + +<p>To launch JET Creator go to a command +prompt and set the directory to where you've installed Python. Next run python +with the command:</p> + +<p><pre>python jetcreator.py</pre></p> + + + + + +<h1>5 Using JET Creator</h1> + + + +<h2>5.1 File Types</h2> + +<p>There are a few different file types +associated with JET Creator.</p> + + + +<p>.jtc JET +Creator project file. This file contains all the information associated with a +JET Creator project. When you Save or Save-as out of JET Creator, this file +type is saved.</p> + + + +<p>.jet JET +File. This output file is automatically generated from JET Creator whenever you +save your JET Creator project. This is the file that bundles all JET assets +together into a single file that the Android application will use. Give this +file to the Android application developer.</p> + + + +<p>.mid File. This is the standard MIDI +type 1 file that JET Creator will use to make segments.</p> + + + +<p>.seg Segment +File. This is a JET Segment file. It has the same name as the MIDI +file which it references but contains additional Segment information.</p> + + + +<p>.zip Zip +Archive file. When you Export a JET Archive, a zip file is created that +contains all the assets (files) necessary for JET Creator. Use this to transfer +JET Creator projects to other people.</p> + + + +<h2>5.2 Open Dialog</h2> + +<p>When +you first launch JET Creator you are presented with an open dialog like the +following.</p> + + + +<p><img border=0 width=450 height=285 +src="{@docRoot}images/jet/jc_open_dlg.png" +</p> + + + + + +<p> <b>Open</b> will open an existing .jtc (JET Creator file) file. Use the browser +button to browse to the directory where you have saved your .jtc file.</p> + + + +<p> <b>New</b> will create a new .jtc file.</p> + + + +<p> <b>Import</b> will import a JET Archive (.zip) file.</p> + + + +<p> <b>Cancel</b> will cancel the dialog and exit the application.</p> + + + + + +<h1>5 Main Window </h1> + +<p>The main window of the JET Creator +application looks like the picture below. There are three main sections from +top to bottom: segment view, event view, and timeline. </p> + + + +<p>The segment view section displays a list of +the current segments, which MIDI file and +(optionally) DLS2 file each segment is derived from. It also shows each +segments start and stop time and each segments quantize, transpose, repeat and +mute flag settings.</p> + + + +<p>Just below the Segment view is the event +view. The event view section displays all events associated with a given +segment. Events only display when the segment they are assigned to is +highlighted. Each event displays its type, start and end points, track and midi +channel assignment, and its event ID.</p> + + + +<p>Just below the Event view is the timeline +display. The timeline shows how many measures a given segment is as well as any +events associated with that segment. The timeline changes to display the +currently selected or playing segment. You can trigger an event in this window +while the segment is play by simply clicking on the event in the timeline +display.</p> + + +<p><img border=0 width=554 height=378 +src="{@docRoot}images/jet/jc_main_wnd.png"> +<br><i>JET +Creator Main Window<o:p></o:p></i></p> + + +<p>The buttons along the left side of main +window do the following:</p> + +<p>Add: +Displays the segment or event window for adding a new segment or event</p> + +<p>Revise: +Displays the segment or event window for updating an existing segment or event</p> + +<p>Delete: +Deletes the selected segment or event (will ask for confirmation)</p> + +<p>Move: +Displays the move window which allows you to move selected segments or events +in time</p> + +<p>Queue All: Queue's +(selects) all segments for playback</p> + +<p>Dequeue All: Dequeues +(deselects) all segments</p> + +<p>Play: +Starts playback of all queued segments. This button changes to Stop if any +segments are playing</p> + +<p>Audition: +Displays the Audition window (see below)</p> + + + +<h2>5.1 Segment Window</h2> + +<p>The segment window is where a given +segment's attributes are assigned and auditioned, as shown in the picture +below. The left side of the window displays the segments attributes that are +stored in the JET file. The right side of the window allows the author to set +mute flags, repeat and transpose settings and audition the segment as it will +play in the JET game.</p> + + + +<p><b>Note</b>: the audition attributes (mute flags, repeat and transpose) are <i +>not</i> stored in the JET content file +(.jet) but rather are defined by the game or application itself. In programming +language, these settings correspond directly with the API calls to the JET +engine. By including them here, the JET content author can simulate how the +segment will respond to the applications API commands during game play.</p> + + + +<p><img border=0 width=553 height=295 +src="{@docRoot}images/jet/jc_seg_wnd.png" > +</p> + +<p>The segment parameters do the following:</p> + +<ul> +<li>Segment Name - Sets +the name of the segment</li> + +<li>MIDI File - +The name and location of the MIDI file from which +the segment is derived. The button to the immediate right will bring up a +browser for locating a midi file on the hard drive.</li> + +<li>DLS File - +The name and location of the DLS2 file, if any, that the MIDI +file uses for that segment.</li> + +<li>Starting M/B/T - +Starting measure, beat and tick of the segment</li> + +<li>Ending M/B/T - +Ending measure, beat and tick of the segment</li> + +<li>Quantize - +Quantize value for quantizing the current segment during playback</li> + +</ul> + +<p>The audition fields are as follows:</p> + +<ul> +<li>Track Mutes - +Shows the MIDI <b>tracks</b> (not channels) +in the MIDI file. Clicking on a track's +checkbox will mute that track. </li> + +<li>Channel - +Displays the MIDI channel assigned to each +track</li> + +<li>Name - +Displays the track name meta event (if present) for each track</li> + +<li>Repeat - +Indicates the number of times a segment should repeat during playback</li> + +<li>Transpose - +Indicates the transposition in semi-tones or half-steps a segment should +transpose during playback</li> + +<li>To the right of the Audition window are a few additional buttons. +These do as follows:</li> + +<li>OK - +Selecting OK confirms all segment settings and closes the segment window</li> + +<li>Cancel - +Selecting Cancel cancels any changes and closes the segment window</li> + +<li>Replicate - +Displays the Replicate Segment window for entering multiple segments at once. +See below.</li> + +<li>Play/Stop Segment - Starts +or Stops playback of the segment using the segment attributes assigned. </li> + +<li>Play/Stop MIDI File - +Starts or Stops playback of the MIDI file +which the segment is assigned to. </li> + +<li>Pause/Resume - +Pauses or Resumes playback.</li> + +</ul> + + + +<h2>5.2 Event Window</a></h2> + +<p>The event window is where a given segment's +event attributes are assigned and auditioned, as shown in the picture below. To +add an event to a segment, the author must first select the segment which will +contain the event, then select the Add button. This will bring up the Event +window.</p> + + + +<p> +<img border=0 width=554 height=294 +src="{@docRoot}images/jet/jc_event_wnd.png"></p> + + + + + +<p>There are two main sections to the event +window. The segment section on the left side of the event window is for display +only. It shows what the segment attributes are for the given segment. The Event +section, on the right side, is where events can be assigned. The following +parameters are available:</p> + + + +<p>Event Name - +Assigns a name to an event</p> + +<p>Event Type - +Selects which type of event to assign.</p> + +<p>Starting M/B/T - +Sets the starting measure, beat, and tick for the event</p> + +<p>Ending M/B/T - +Sets the ending measure, beat, and tick for the event, if applicable</p> + +<p>Track - +Sets which track in the given segment the event will apply to</p> + +<p>Channel - +Sets which MIDI channel the event will apply +to. The MIDI channel should match the MIDI +channel of the track</p> + +<p>Event ID - +Sets the event ID for the event. Multiple events can be assigned to the same +segment and therefore the Event ID is used to identify them</p> + + + +<p>To the right of the Audition window are a few additional buttons. +These do as follows:</p> + +<p> + +<p>OK - +Selecting OK confirms all event settings and closes the event window</p> + +<p>Cancel - +Selecting Cancel cancels any changes and closes the event window</p> + +<p>Replicate - +Displays the Replicate Event window for entering multiple events at once. See +below.</p> + +<p>Play/Stop - +Starts or Stops playback of the segment using the segment attributes assigned. +While the segment is playing, events can be triggered and auditioned.</p> + +<p>Trigger - +Triggers the event assigned. This replicates the API command that the JET game +will use to trigger the event, therefore giving the content author a method for +auditioning the behaviour of the event.</p> + +<p>Mute/UnMute - +Mute/UnMute will mute or unmute the track that the event is assigned to</p> + +<p>Pause/Resume - +Pauses or Resumes playback.</p> + + + +<p>To audition the behaviour of an event, you +can select the Play button. This will initiate playback. The trigger button +will send the trigger event when pressed. This is equivalent to selecting the +green trigger event in the timeline. </p> + + + +<p>Note: Trigger events are meant to unmute a +single track of a segment when triggered, then mute that track at the end of +the trigger segment. Therefore you should make sure the mute flag is set to +mute the track that a trigger event will be unmuting when receiving a trigger event. +</p> + + + +<p>Please read Section <i>6 Under The Hood</i> +below for details on how trigger events work and behave. </p> + + + +<h2>5.3 Replicate Windows</h2> + +<p>Often in creating JET files, you'll need to +create tens or even hundreds of events. You may also need to move events. The +Replicate and Move windows allow for this. There are two Replicate windows for +creating multiple segments or events. They look like the following:</p> + + + +<p><img border=0 width=395 height=419 +src="{@docRoot}images/jet/jc_rep_wnd.png" ></p> + +<p>Replicate Segment Window</p> + + +<p><img border=0 width=398 height=425 +src="{@docRoot}images/jet/jc_repseg_wnd.png"></p> + + + +<p>Replicate Event Window</p> + + + +<p>Both Replicate windows function the same. +After creating an initial segment or event, you can select the Replicate +button. The parameters are as follows:</p> + + + +<p>Name Prefix - +Sets the prefix for the name of each segment or event created</p> + +<p>Starting M/B/T - +Sets the starting time for the first segment or event</p> + +<p>Increment M/B/T - +Sets the time between segments or events created. </p> + +<p>Number - +Sets the number of segments or events you wish to create. If the number +overflows the length of the MIDI file (for +segments) or segment (for events), those objects will not be created.</p> + +<p>Preview - +Preview allows you to examine the objects created before saying OK to insert +them.</p> + + + + + +<h2>5.4 Move Windows</h2> + +<p>The Move function acts similarly to the +Replicate function in that it allows you to edit multiple segments or events at +one time, in this case move them in time. Like Replicate, there are two Move +windows, one for Segments and one for Events. The windows look like the +following:</p> + + + +<p><img border=0 width=400 height=424 +src="{@docRoot}images/jet/jc_moveseg_wnd.png"></p> + + + +<p>Move Event Window</p> + + + +<p>To use Move, first select the segments or +events you wish to move in time, then click the Move button. The parameters are +as follows:</p> + + + +<p>Starting M/B/T - +Sets the starting time for the first segment or event</p> + +<p>Increment M/B/T - +Sets the time in M/B/T you wish to move the objects by. </p> + +<p>Preview - +Preview allows you to examine the objects created before saying OK to move +them.</p> + + + + + +<h2>5.5 Audition Window</a></h2> + +<p>Clicking the Audition button in the main +window of the JET Creator application will open the Audition window. This is +where the content author or application programmer can simulate the interactive +playback as it may occur in the mobile application or game itself.</p> + + + +<p><img border=0 width=554 height=370 +src="{@docRoot}images/jet/jc_audition_wnd.png"></p> + + + +<p>JET Audition Window</p> + + + + + +<p>There are four main sections to the +audition window. The left most section displays the available segments and +their length in seconds. The middle section displays a running list of what +segments are queued for playback and what their playback status is. The far +right section displays the mute flags for the currently playing segment. The +timeline section at the bottom is the same as in the main window. It displays +the currently playing segment as well as a visual display of any event triggers +associated with that segment. </p> + + + +<p>The Audition window allows you to queue up +any segment in any order for playback. To do this simply select the segment you +wish to cue and hit Queue. That segment will appear in the queue window and +start playing (if it is the first segment). Subsequently you can select any +other segment or segments and cue them up for playback. As the segments +complete playback, the next segment in the queue will begin playing. As is the +other windows of JET Creator, you can mute, unmute, trigger event clips, etc. +in realtime as each segment is playing back.</p> + + + +<p>Specifically the buttons behave as follows:</p> + + + +<p>Queue - +loads the selected segment into the queue and starts playback</p> + +<p>Cancel and Queue - +cancels the currently playing segment before queueing the selected segment for +playback</p> + +<p>Cancel Current - +cancels the currently playing segment in the queue and begins playback of the +next segment</p> + +<p>Stop - +stops playback of all queued segments</p> + +<p>Mute All - +mutes all tracks in the current segment</p> + +<p>Mute None - +unmutes all tracks in the current segment</p> + +<p>Original Mutes - +sets the original mute flags for the current segment</p> + + + +<p>The combination of these playback options +allows an author or application programmer to audition any behaviour an +interactive music application may encounter. </p> + + + + + +<h2>5.6 JET Creator Menus </h2> + +<p>The JET Creator menus provide access to +many of the parameters in the main window plus a few additional parameters.</p> + +<h3>5.6.1 File Menu</h3> + +<p>The File Menu contains the following +elements:</p> + + + +<p>New - +Creates a new JET Creator file (.jtc)</p> + +<p>Open - +Opens an existing JET Creator file</p> + +<p>Save - +Saves the currently opened JET Creator file</p> + +<p>Save As - +Saves the currently opened JET Creator file to a new file</p> + +<p>Import Project - Imports a JET Creator archive (.zip)</p> + +<p>Export Project - Exports a JET Creator archive (.zip)</p> + +<p>Exit - +Exits the application</p> + + + +<h3>5.6.2 Edit Menu</h3> + +<p>The Edit Menu contains the following +elements:</p> + + + +<p>Undo - +Undo will undo the last edit made</p> + +<p>Redo - +Redo will redo the last undo</p> + +<p>Cut - +Copy selected parameter into clipboard and Delete selection</p> + +<p>Copy - +Copy selected parameter into clipboard and keep selection</p> + +<p>Paste - +Paste selected parameter</p> + + + +<h3>5.6.3 JET</h3> + +<p>The Edit Menu contains the following +elements:</p> + + + +<p>Properties - +Brings up the JET Creator priorities window. This window allows you to set the +following conditions for a given JET file:</p> + +<p>Copyright Info - Contains copyright info to be inserted into JET file</p> + +<p>Chase Controllers - Option to chase controllers (on/off). This should usually +be ON.</p> + +<p>Delete Empty Tracks - Deletes any empty MIDI tracks</p> + + + +<h3>5.6.4 Segments</h3> + +<p>The Segments Menu contains the following +elements:</p> + + + +<p>Add Segment - +Brings up the Segment window</p> + +<p>Update Segment - Updates segment attributes</p> + +<p>Delete Segment - Deletes the current segment from the +Segment List</p> + + + +<h3>5.6.5 Help</h3> + +<p>The Help Menu will contain at least the +following elements:</p> + + + +<p>JET Creator Help - will launch PDF help document or go to on-line help</p> + +<p>About - +JET Creator version number, SONiVOX info</p> + + + + + +<h1>6 Trigger Events Explained</h1> + +<p>Breaking a MIDI +file into individual (non-linear) segments and queueing up those segments for +playback in a game based on events within the game is one way JET music files are +interactive. Trigger events are an additional method for interactive playback. +Both would be used together in an interactive game or application.</p> + + + +<p>Trigger events allow for the following:</p> + + +<ol> + <li><span + lang=EN-IE>Tracks <i>within</i> a MIDI segment can be turned on or off based on game + events. For example the composer could author two drum tracks, one fast + and one slow. If the action in a game is fast, the fast drum track could + play. If the action in the game is slow, the slow drum track can play.</li> + <li><span + lang=EN-IE>User actions can be compared to trigger events which are + pre-inserted into a music file at musically correct places. Based on the + results, scoring or other game actions can take place. </li> + <li><span + lang=EN-IE>Musical transitions between levels or action sequences can be + synchronized to be musically seemless.</li> +</ol> + + + +<p>Under the hood, JET uses standard MIDI CC +events to accomplish these actions and to synchronize audio. The controllers +used by JET are among those not defined for specific use by the specification. The specific controller definitions +are as follows:</p> + + + +<p> Controllers +80-83 Reserved for use by +application</p> + +<p> Controller +102 JET event marker</p> + +<p> Controller +103 JET clip marker</p> + +<p> Controllers +104-119 Reserved for future use</p> + + + +<h2>6.1 JET Clip Marker (CC103)</h2> + +<p>Controller 103 is reserved for marking +clips in a MIDI track that can be triggered by +the JET_TriggerClip API call. The clip ID is encoded in the low 6 bits of the +controller value. Bit 6 is set to one to indicate the start of a clip, and set +to zero to indicate the end of a clip.</p> + + + +<p>For example, to identify a clip with a clip +ID of 1, the author inserts a MIDI controller +event with controller=103 and value=65 at the start of the clip and another +event with controller=103 and value=1 at the end of the clip. When the +JET_TriggerClip() function is called with a clip ID of 1, the track will be +un-muted when the controller value 65 is encountered and muted again when the +controller value 1 is encountered.</p> + + + +<p><img border=0 width=492 height=367 +src="{@docRoot}images/jet/clip_marker.png"></p> + +<p>Figure 5: Synchronized Clip</p> + + + +<p>In the figure above, if the +JET_TriggerClip() function is called prior to the first controller event, Track +3 will be un-muted when the first controller event occurs, the first clip will +play, and the track will be muted when the second controller event occurs. If +the JET_TriggerClip() function is called after the first controller event has +occurred, Track 3 will be un-muted when the third controller event occurs, the +second clip will play, and the track will be muted again when the fourth +controller event occurs.</p> + + + +<p><b>Note:</b> Normally, the track containing the clip is muted by the application +when the segment is initially queued by the call to JET_QueueSegment(). If it +is not muted, the clip will always play until Jet_TriggerClip() has been called +with the clip ID.</p> + + + +<h2>6.2 JET Event Marker (CC102)</h2> + +<p>Controller 102 is reserved for marking +events in the MIDI streams that are specific +to JET functionality. Currently, the only defined value is 0, which marks the +end of a segment for timing purposes. </p> + + + +<p>Normally, JET starts playback of the next +segment (or repeats the current segment) when the MIDI +end-of-track meta-event is encountered. Some MIDI +authoring tools make it difficult to place the end-of-track marker accurately, +resulting in synchronization problems when segments are joined together.</p> + + + +<p>To avoid this problem, the author can place +a JET end-of-segment marker (controller=102, value=0) at the point where the +segment is to be looped. When the end-of-segment marker is encountered, the +next segment will be triggered, or if the current segment is looped, playback +will resume at the start of the segment.</p> + + + +<p>The end-of-segment marker can also be used +to allow for completion of a musical figure beyond the end of measure that +marks the start of the next segment. For example, the content author might +create a 4-bar segment with a drum fill that ends on beat 1 of the 5<sup>th</sup> +bar, a bar beyond the natural end of the segment. By placing an end-of-segment +marker at the end of the 4<sup>th</sup> bar, the next segment will be +triggered, but the drum fill will continue in parallel with the next segment +providing musical continuity.</p> + + + +<p><img border=0 width=467 height=185 +src="{@docRoot}images/jet/event_marker.png"></p> + +<p>Figure 6: End-of-segment Marker</p> + +<h2>6.3 Application Controllers (CC80-83)</h2> + +<p>The application may use controllers in this +range for its own purposes. When a controller in this range is encountered, the +event is entered into an event queue that can be queried by the application. +Some possible uses include synchronizing video events with audio and marking a +point in a MIDI segment to queue up the next +segment. The range of controllers monitored by the application can be modified +by the application during initialization.</p> + +<h1>7 JET Creator Guidelines</h1> + +<p></p> + +<h2>7.1 Order of Tasks</h2> + +<p>As with all projects, its best to discuss and design the interactive music scheme with the game designer and programmer before beginning your composition. An outline and/or specification can go a long way in saving you from having to redo things after the game is in place.</p> + +<p>In general you’ll want to first write your music in your DAW of choice the way you’re used to composing, then break up the final MIDI file as needed for the application. Next, move to JET Creator and create all of your music segments in the order easiest to preview them when played in order. Finally, add the JET Events to control the segments via the Android game and Audition them as needed in JET Creator. Finally, save the project in JET Creator and hand off the .jet file to the programmer to integrate it in the game. After previewing there will likely be changes to the MIDI file(s) and JET Creator attributes. </p> + +<h2>7.2 Conserving Memory</h2> + +<p>If you’re trying to conserve memory, compose as few MIDI files as possible, and create several segments from that MIDI file. For example a 12 bar MIDI file with three sections of 4 bars, A, B, C, can create a much longer song. Simply create multiple segments that reference the one MIDI file, then order them however you like. For example, A, A, B, A, C, A, B, A, A would create a 36 bar song. Use JET to add repeats, transpose segments, and interactively mute and unmute tracks to keep it even more interesting.</p> + +<h2>7.3 Replicate</h2> + +<p>To make adding segments or events faster, use the Replicate command. Replicate can add multiple segments or events at one time and uses an offset parameter and prefix naming convention to keep things easy to read. The MOVE command is also useful for moving multiple events by a set number of measures, beats or ticks.</p> + +<h2>7.4 Interactive Options</h2> + +<p>There are several interactive audio concepts possible in JET. Below are a few examples although we hope developers will come up with others we haven’t thought of! These are:</p> + +<h3>7.4.1 Multiple Segment Triggering</h3> + +<p>In this method the application is triggering specific segments based on events in the game. For example a hallway with lots of fighting might trigger segment 1 and a hallway with no fighting might trigger segment 2. Using JET TriggerClips in conjunction with this method creates even more diversity.</p> + +<h3>7.4.2 Mute Arrays</h3> + +<p>In this method the application is triggering mute and unmute events to specific tracks in a single MIDI sequence. For example a hallway with lots of fighting might play MIDI tracks 1-16 and a hallway with no fighting might play the same midi file but mute tracks 9-16. Using JET TriggerClips in conjunction with this method creates even more diversity.</p> + +<h3>7.4.3 Music Driven Gameplay</h3> + +<p>Music driven gaming is similar to what Guitar Hero and JETBOY have done in that the music content determines how graphic events are displayed. The application then queries the user response to the graphic events and interactively modifies the music in response. In this method the game is utilizing JET Application Events, MIDI controllers that are embedded in the MIDI file and read by the game in real-time. Based on the user response, multiple segment triggering and/or mute arrays can be set.</p> + diff --git a/docs/html/guide/topics/media/media.jd b/docs/html/guide/topics/media/media.jd deleted file mode 100644 index 463686d..0000000 --- a/docs/html/guide/topics/media/media.jd +++ /dev/null @@ -1,172 +0,0 @@ -page.title=Media Capabilities -@jd:body - -<div class="sidebox"> - -<h3>Media Quickview</h3> - -<h4>Built-in capabilities</h4> -<ul> -<li>Audio playback and record</li> -<li>Video playback</li> -</ul> - -<h4>Data sources</h4> -<ul> -<li>Raw resources</li> -<li>Data files</li> -<li>Streams</li> -</ul> - -<h4>Media Formats</h4> -<ul> -<li>See appendix <a href="{@docRoot}devguide/appendix/media_formats.html">Android 1.0 Media Formats</a></li> -</ul> - -<h4>Key APIs</h4> -<ul> -<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 -capabilities is fairly straightforward &mdash 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}devguide/appendix/media_formats.html">Android Media Formats</a> appendix. </p> - -<h2>Playing Audio and Video</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>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:<br><br></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>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:<br><br></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>Recording Media Resources</h2> -<p>Recording media is a little more involved than playing it back, as you would -probably expect, but it is still fairly simple. There is just a little more set -up to do</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>Finally, {@link android.media.MediaRecorder#prepare prepare()} and - {@link android.media.MediaRecorder#start start()} the recording. - {@link android.media.MediaRecorder#stop stop()} and - {@link android.media.MediaRecorder#release release()} when you are done</li> -</ol> -<p>Here is a code example that will hopefully help fill in the gaps:</p> -<p><strong>Start Recording</strong></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> -<p><strong>Stop Recording</strong></p> -<pre> - recorder.stop(); - recorder.release(); -</pre> - diff --git a/docs/html/guide/topics/resources/index.jd b/docs/html/guide/topics/resources/index.jd index 7e3bce42..1425cfa 100644 --- a/docs/html/guide/topics/resources/index.jd +++ b/docs/html/guide/topics/resources/index.jd @@ -18,8 +18,8 @@ In general, these are external elements that you want to include and reference w 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 +as an asset when you need to read the raw bytes. The directories for resources and assets both +reside at the top of an Android project tree, at the same level as your source code directory (<code>src/</code>).</p> <p>The difference between "resources" and "assets" isn't much on the surface, but in general, diff --git a/docs/html/guide/topics/resources/resources-i18n.jd b/docs/html/guide/topics/resources/resources-i18n.jd index b1da4cd..4bbb44a 100644 --- a/docs/html/guide/topics/resources/resources-i18n.jd +++ b/docs/html/guide/topics/resources/resources-i18n.jd @@ -111,21 +111,30 @@ the containing file.</p> <td><code>res/drawable/</code></td> <td><p>.png, .9.png, .jpg files that are compiled into the following Drawable resource subtypes:</p> - <p>To get a resource of this type, use <code>Resource.getDrawable(<em>id</em>)</code> - <ul> + <ul class="nolist"> <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> + </ul> + <p>To get a resource of this type, use <code>mContext.getResources().getDrawable(R.drawable.<em>imageId</em>)</code></p> + <p class="note"><strong>Note:</strong> Image resources placed in here may + be automatically optimized with lossless image compression by the + <a href="{@docRoot}guide/developing/tools/aapt.html">aapt</a> tool. For example, a true-color PNG + that does not require more than 256 colors may be converted to an 8-bit PNG with a color palette. + This will result in an image of equal quality but which requires less memory. So be aware that the + image binaries placed in this directory can change during the build. If you plan on reading + an image as a bit stream in order to convert it to a bitmap, put your images in the + <code>res/raw/</code> folder instead, where they will not be optimized.</p> + </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}guide/topics/ui/declaring-layout.html">Declaring Layout</a></td> + See <a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a>.</td> </tr> <tr> <td><code>res/values/</code></td> <td><p>XML files that can be compiled into many kinds of resource.</p> - <p class="note"><strong>Note:</strong> unlike the other res/ folders, this one + <p class="note"><strong>Note:</strong> Unlike the other res/ folders, this one can hold any number of files that hold descriptions of resources to create rather than the resources themselves. The XML element types control where these resources are placed under the R class.</p> diff --git a/docs/html/guide/topics/ui/custom-components.jd b/docs/html/guide/topics/ui/custom-components.jd index eccc2ca..76d1034 100644 --- a/docs/html/guide/topics/ui/custom-components.jd +++ b/docs/html/guide/topics/ui/custom-components.jd @@ -34,7 +34,7 @@ that you can use to construct your UI.</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}, +{@link android.widget.FrameLayout FrameLayout}, {@link android.widget.RelativeLayout RelativeLayout}, and others. For more examples, see <a href="layout-objects.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. diff --git a/docs/html/guide/topics/ui/dialogs.jd b/docs/html/guide/topics/ui/dialogs.jd new file mode 100644 index 0000000..c0c0b1b --- /dev/null +++ b/docs/html/guide/topics/ui/dialogs.jd @@ -0,0 +1,650 @@ +page.title=Creating Dialogs +parent.title=User Interface +parent.link=index.html +@jd:body + +<div id="qv-wrapper"> + <div id="qv"> + <h2>Key classes</h2> + <ol> + <li>{@link android.app.Dialog}</li> + </ol> + <h2>In this document</h2> + <ol> + <li><a href="#ShowingADialog">Showing a Dialog</a></li> + <li><a href="#DismissingADialog">Dismissing a Dialog</a></li> + <li><a href="#AlertDialog">Creating an AlertDialog</a> + <ol> + <li><a href="#AddingButtons">Adding buttons</a></li> + <li><a href="#AddingAList">Adding a list</a></li> + </ol> + </li> + <li><a href="#ProgressDialog">Creating a ProgressDialog</a> + <ol> + <li><a href="#ShowingAProgressBar">Showing a progress bar</a></li> + </ol> + </li> + <li><a href="#CustomDialog">Creating a Custom Dialog</a></li> + </ol> + </div> +</div> + +<p>A dialog is usually a small window that appears in front of the current Activity. +The underlying Activity loses focus and the dialog accepts all user interaction. +Dialogs are normally used +for notifications and short activities that directly relate to the application in progress.</p> + +<p>The Android API supports the following types of {@link android.app.Dialog} objects:</p> +<dl> + <dt>{@link android.app.AlertDialog}</dt> + <dd>A dialog that can manage zero, one, two, or three buttons, and/or a list of + selectable items that can include checkboxes or radio buttons. The AlertDialog + is capable of constructing most dialog user interfaces and is the suggested dialog type. + See <a href="#AlertDialog">Creating an AlertDialog</a> below.</dd> + <dt>{@link android.app.ProgressDialog}</dt> + <dd>A dialog that displays a progress wheel or progress bar. Because it's an extension of + the AlertDialog, it also supports buttons. + See <a href="#ProgressDialog">Creating a ProgressDialog</a> below.</dd> + <dt>{@link android.app.DatePickerDialog}</dt> + <dd>A dialog that allows the user to select a date. See the + <a href="{@docRoot}guide/tutorials/views/hello-datepicker.html">Hello DatePicker</a> tutorial.</dd> + <dt>{@link android.app.TimePickerDialog}</dt> + <dd>A dialog that allows the user to select a time. See the + <a href="{@docRoot}guide/tutorials/views/hello-timepicker.html">Hello TimePicker</a> tutorial.</dd> +</dl> + +<p>If you would like to customize your own dialog, you can extend the +base {@link android.app.Dialog} object or any of the subclasses listed above and define a new layout. +See the section on <a href="#CustomDialog">Creating a Custom Dialog</a> below.</p> + + +<h2 id="ShowingADialog">Showing a Dialog</h2> + +<p>A dialog is always created and displayed as a part of an {@link android.app.Activity}. +You should normally create dialogs from within your Activity's +{@link android.app.Activity#onCreateDialog(int)} callback method. +When you use this callback, the Android system automatically manages the state of +each dialog and hooks them to the Activity, effectively making it the "owner" of each dialog. +As such, each dialog inherits certain properties from the Activity. For example, when a dialog +is open, the Menu key reveals the options menu defined for the Activity and the volume +keys modify the audio stream used by the Activity.</p> + +<p class="note"><strong>Note:</strong> If you decide to create a dialog outside of the +<code>onCreateDialog()</code> method, it will not be attached to an Activity. You can, however, +attach it to an Activity with {@link android.app.Dialog#setOwnerActivity(Activity)}.</p> + +<p>When you want to show a dialog, call +{@link android.app.Activity#showDialog(int)} and pass it an integer that uniquely identifies the +dialog that you want to display.</p> + +<p>When a dialog is requested for the first time, Android calls +{@link android.app.Activity#onCreateDialog(int)} from your Activity, which is +where you should instantiate the {@link android.app.Dialog}. This callback method +is passed the same ID that you passed to {@link android.app.Activity#showDialog(int)}. +After you create the Dialog, return the object at the end of the method.</p> + +<p>Before the dialog is displayed, Android also calls the optional callback method +{@link android.app.Activity#onPrepareDialog(int,Dialog)}. Define this method if you want to change +any properties of the dialog each time it is opened. This method is called +every time a dialog is opened, whereas {@link android.app.Activity#onCreateDialog(int)} is only +called the very first time a dialog is opened. If you don't define +{@link android.app.Activity#onPrepareDialog(int,Dialog) onPrepareDialog()}, then the dialog will +remain the same as it was the previous time it was opened. This method is also passed the dialog's +ID, along with the Dialog object you created in {@link android.app.Activity#onCreateDialog(int) +onCreateDialog()}.</p> + +<p>The best way to define the {@link android.app.Activity#onCreateDialog(int)} and +{@link android.app.Activity#onPrepareDialog(int,Dialog)} callback methods is with a +<em>switch</em> statement that checks the <var>id</var> parameter that's passed into the method. +Each <em>case</em> should check for a unique dialog ID and then create and define the respective Dialog. +For example, imagine a game that uses two different dialogs: one to indicate that the game +has paused and another to indicate that the game is over. First, define an integer ID for +each dialog:</p> +<pre> +static final int DIALOG_PAUSED_ID = 0; +static final int DIALOG_GAMEOVER_ID = 1; +</pre> + +<p>Then, define the {@link android.app.Activity#onCreateDialog(int)} callback with a +switch case for each ID:</p> +<pre> +protected Dialog onCreateDialog(int id) { + Dialog dialog; + switch(id) { + case DIALOG_PAUSED_ID: + // do the work to define the pause Dialog + break; + case DIALOG_GAMEOVER_ID: + // do the work to define the game over Dialog + break; + default: + dialog = null; + } + return dialog; +} +</pre> + +<p class="note"><strong>Note:</strong> In this example, there's no code inside +the case statements because the procedure for defining your Dialog is outside the scope +of this section. See the section below about <a href="#AlertDialog">Creating an AlertDialog</a>, +offers code suitable for this example.</p> + +<p>When it's time to show one of the dialogs, call {@link android.app.Activity#showDialog(int)} +with the ID of a dialog:</p> +<pre> +showDialog(DIALOG_PAUSED_ID); +</pre> + + +<h2 id="DismissingADialog">Dismissing a Dialog</h2> + +<p>When you're ready to close your dialog, you can dismiss it by calling +{@link android.app.Dialog#dismiss()} on the Dialog object. +If necessary, you can also call {@link android.app.Activity#dismissDialog(int)} from the +Activity, which effectively calls {@link android.app.Dialog#dismiss()} on the +Dialog for you.</p> + +<p>If you are using {@link android.app.Activity#onCreateDialog(int)} to manage the state +of your dialogs (as discussed in the previous section), then every time your dialog is +dismissed, the state of the Dialog +object is retained by the Activity. If you decide that you will no longer need this object or +it's important that the state is cleared, then you should call +{@link android.app.Activity#removeDialog(int)}. This will remove any internal references +to the object and if the dialog is showing, it will dismiss it.</p> + +<h3>Using dismiss listeners</h3> + +<p>If you'd like your applcation to perform some procedures the moment that a dialog is dismissed, +then you should attach an on-dismiss listener to your Dialog.</p> + +<p>First define the {@link android.content.DialogInterface.OnDismissListener} interface. +This interface has just one method, +{@link android.content.DialogInterface.OnDismissListener#onDismiss(DialogInterface)}, which +will be called when the dialog is dismissed. +Then simply pass your OnDismissListener implementation to +{@link android.app.Dialog#setOnDismissListener(DialogInterface.OnDismissListener) +setOnDismissListener()}.</p> + +<p>However, note that dialogs can also be "cancelled." This is a special case that indicates +the dialog was explicitly cancelled by the user. This will occur if the user presses the +"back" button to close the dialog, or if the dialog explicitly calls {@link android.app.Dialog#cancel()} +(perhaps from a "Cancel" button in the dialog). When a dialog is cancelled, +the OnDismissListener will still be notified, but if you'd like to be informed that the dialog +was explicitly cancelled (and not dismissed normally), then you should register +an {@link android.content.DialogInterface.OnCancelListener} with +{@link android.app.Dialog#setOnCancelListener(DialogInterface.OnCancelListener) +setOnCancelListener()}.</p> + + +<h2 id="AlertDialog">Creating an AlertDialog</h2> + +<p>An {@link android.app.AlertDialog} is an extension of the {@link android.app.Dialog} +class. It is capable of constructing most dialog user interfaces and is the suggested dialog type. +You should use it for dialogs that use any of the following features:</p> +<ul> + <li>A title</li> + <li>A text message</li> + <li>One, two, or three buttons</li> + <li>A list of selectable items (with optional checkboxes or radio buttons)</li> +</ul> + +<p>To create an AlertDialog, use the {@link android.app.AlertDialog.Builder} subclass. +Get a Builder with {@link android.app.AlertDialog.Builder#AlertDialog.Builder(Context)} and +then use the class's public methods to define all of the +AlertDialog properties. After you're done with the Builder, retrieve the +AlertDialog object with {@link android.app.AlertDialog.Builder#create()}.</p> + +<p>The following topics show how to define various properties of the AlertDialog using the +AlertDialog.Builder class. If you use any of the following sample code inside your +{@link android.app.Activity#onCreateDialog(int) onCreateDialog()} callback method, +you can return the resulting Dialog object to display the dialog.</p> + + +<h3 id="AddingButtons">Adding buttons</h3> + +<img src="{@docRoot}images/dialog_buttons.png" alt="" style="float:right" /> + +<p>To create an AlertDialog with side-by-side buttons like the one shown in the screenshot to the right, +use the <code>set...Button()</code> methods:</p> + +<pre> +AlertDialog.Builder builder = new AlertDialog.Builder(this); +builder.setMessage("Are you sure you want to exit?") + .setCancelable(false) + .setPositiveButton("Yes", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + MyActivity.this.finish(); + } + }) + .setNegativeButton("No", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + dialog.cancel(); + } + }); +AlertDialog alert = builder.create(); +</pre> + +<p>First, add a message for the dialog with +{@link android.app.AlertDialog.Builder#setMessage(CharSequence)}. Then, begin +method-chaining and set the dialog +to be <em>not cancelable</em> (so the user cannot close the dialog with the back button) +with {@link android.app.AlertDialog.Builder#setCancelable(boolean)}. For each button, +use one of the <code>set...Button()</code> methods, such as +{@link android.app.AlertDialog.Builder#setPositiveButton(CharSequence,DialogInterface.OnClickListener) +setPositiveButton()}, that accepts the name for the button and a +{@link android.content.DialogInterface.OnClickListener} that defines the action to take +when the user selects the button.</p> + +<p class="note"><strong>Note:</strong> You can only add one of each button type to the +AlertDialog. That is, you cannot have more than one "positive" button. This limits the number +of possible buttons to three: positive, neutral, and negative. These names are technically irrelevant to the +actual functionality of your buttons, but should help you keep track of which one does what.</p> + + +<h3 id="AddingAList">Adding a list</h3> + +<img src="{@docRoot}images/dialog_list.png" alt="" style="float:right" /> + +<p>To create an AlertDialog with a list of selectable items like the one shown to the right, +use the <code>setItems()</code> method:</p> + +<pre> +final CharSequence[] items = {"Red", "Green", "Blue"}; + +AlertDialog.Builder builder = new AlertDialog.Builder(this); +builder.setTitle("Pick a color"); +builder.setItems(items, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int item) { + Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show(); + } +}); +AlertDialog alert = builder.create(); +</pre> + +<p>First, add a title to the dialog with +{@link android.app.AlertDialog.Builder#setTitle(CharSequence)}. +Then, add a list of selectable items with +{@link android.app.AlertDialog.Builder#setItems(CharSequence[],DialogInterface.OnClickListener) +setItems()}, which accepts the array of items to display and a +{@link android.content.DialogInterface.OnClickListener} that defines the action to take +when the user selects an item.</p> + + +<h4>Adding checkboxes and radio buttons</h4> + +<img src="{@docRoot}images/dialog_singlechoicelist.png" alt="" style="float:right" /> + +<p>To create a list of multiple-choice items (checkboxes) or +single-choice items (radio buttons) inside the dialog, use the +{@link android.app.AlertDialog.Builder#setMultiChoiceItems(Cursor,String,String, +DialogInterface.OnMultiChoiceClickListener) setMultiChoiceItems()} and +{@link android.app.AlertDialog.Builder#setSingleChoiceItems(int,int,DialogInterface.OnClickListener) +setSingleChoiceItems()} methods, respectively. +If you create one of these selectable lists in the +{@link android.app.Activity#onCreateDialog(int) onCreateDialog()} callback method, +Android manages the state of the list for you. As long as the Activity is active, +the dialog remembers the items that were previously selected, but when the user exits the +Activity, the selection is lost. + +<p class="note"><strong>Note:</strong> To save the selection when the user leaves or +pauses the Activity, you must properly save and restore the setting throughout +the <a href="{@docRoot}guide/topics/fundamentals.html#lcycles">Activity Lifecycle</a>. +To permanently save the selections, even when the Activity process is completely shutdown, +you need to save the settings +with one of the <a href="{@docRoot}guide/topics/data/data-storage.html">Data +Storage</a> techniques.</p> + +<p>To create an AlertDialog with a list of single-choice items like the one shown to the right, +use the same code from the previous example, but replace the <code>setItems()</code> method with +{@link android.app.AlertDialog.Builder#setSingleChoiceItems(int,int,DialogInterface.OnClickListener) +setSingleChoiceItems()}:</p> + +<pre> +final CharSequence[] items = {"Red", "Green", "Blue"}; + +AlertDialog.Builder builder = new AlertDialog.Builder(this); +builder.setTitle("Pick a color"); +builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int item) { + Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show(); + } +}); +AlertDialog alert = builder.create(); +</pre> + +<p>The second parameter in the +{@link android.app.AlertDialog.Builder#setSingleChoiceItems(CharSequence[],int,DialogInterface.OnClickListener) +setSingleChoiceItems()} method is an integer value for the <var>checkedItem</var>, which indicates the +zero-based list position of the default selected item. Use "-1" to indicate that no item should be +selected by default.</p> + + +<h2 id="ProgressDialog">Creating a ProgressDialog</h2> + +<img src="{@docRoot}images/dialog_progress_spinning.png" alt="" style="float:right" /> + +<p>A {@link android.app.ProgressDialog} is an extension of the {@link android.app.AlertDialog} +class that can display a progress animation in the form of a spinning wheel, for a task with +progress that's undefined, or a progress bar, for a task that has a defined progression. +The dialog can also provide buttons, such as one to cancel a download.</p> + +<p>Opening a progress dialog can be as simple as calling +{@link android.app.ProgressDialog#show(Context,CharSequence,CharSequence) +ProgressDialog.show()}. For example, the progress dialog shown to the right can be +easily achieved without managing the dialog through the +{@link android.app.Activity#onCreateDialog(int)} callback, +as shown here:</p> + +<pre> +ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "", + "Loading. Please wait...", true); +</pre> + +<p>The first parameter is the application {@link android.content.Context}, +the second is a title for the dialog (left empty), the third is the message, +and the last parameter is whether the progress +is indeterminate (this is only relevant when creating a progress bar, which is +discussed in the next section). +</p> + +<p>The default style of a progress dialog is the spinning wheel. +If you want to create a progress bar that shows the loading progress with granularity, +some more code is required, as discussed in the next section.</p> + + +<h3 id="ShowingAProgressBar">Showing a progress bar</h3> + +<img src="/images/dialog_progress_bar.png" alt="" style="float:right" /> + +<p>To show the progression with an animated progress bar:</p> + +<ol> + <li>Initialize the + ProgressDialog with the class constructor, + {@link android.app.ProgressDialog#ProgressDialog(Context)}.</li> + <li>Set the progress style to "STYLE_HORIZONTAL" with + {@link android.app.ProgressDialog#setProgressStyle(int)} and + set any other properties, such as the message.</li> + <li>When you're ready to show the dialog, call + {@link android.app.Dialog#show()} or return the ProgressDialog from the + {@link android.app.Activity#onCreateDialog(int)} callback.</li> + <li>You can increment the amount of progress displayed + in the bar by calling either {@link android.app.ProgressDialog#setProgress(int)} with a value for + the total percentage completed so far or {@link android.app.ProgressDialog#incrementProgressBy(int)} + with an incremental value to add to the total percentage completed so far.</li> +</ol> + +<p>For example, your setup might look like this:</p> +<pre> +ProgressDialog progressDialog; +progressDialog = new ProgressDialog(mContext); +progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); +progressDialog.setMessage("Loading..."); +progressDialog.setCancelable(false); +</pre> + +<p>The setup is simple. Most of the code needed to create a progress dialog is actually +involved in the process that updates it. You might find that it's +necessary to create a second thread in your application for this work and then report the progress +back to the Activity's UI thread with a {@link android.os.Handler} object. +If you're not familiar with using additional +threads with a Handler, see the example Activity below that uses a second thread to +increment a progress dialog managed by the Activity.</p> + +<script type="text/javascript"> +function toggleDiv(link) { + var toggleable = $(link).parent(); + if (toggleable.hasClass("closed")) { + $(".toggleme", toggleable).slideDown("fast"); + toggleable.removeClass("closed"); + toggleable.addClass("open"); + $(".toggle-img", toggleable).attr("title", "hide").attr("src", "/assets/images/triangle-opened.png"); + } else { + $(".toggleme", toggleable).slideUp("fast"); + toggleable.removeClass("open"); + toggleable.addClass("closed"); + $(".toggle-img", toggleable).attr("title", "show").attr("src", "/assets/images/triangle-closed.png"); + } + return false; +} +</script> +<style> +.toggleme { + padding:0 0 1px 0; +} +.toggleable a { + text-decoration:none; +} +.toggleable.closed .toggleme { + display:none; +} +#jd-content .toggle-img { + margin:0; +} +</style> + +<div class="toggleable closed"> + <a href="#" onclick="return toggleDiv(this)"> + <img src="/assets/images/triangle-closed.png" class="toggle-img" /> + <strong>Example ProgressDialog with a second thread</strong></a> + <div class="toggleme"> + <p>This example uses a second thread to track the progress of a process (which actually just +counts up to 100). The thread sends a {@link android.os.Message} back to the main +Activity through a {@link android.os.Handler} each time progress is made. The main Activity then updates the +ProgressDialog.</p> + +<pre> +package com.example.progressdialog; + +import android.app.Activity; +import android.app.Dialog; +import android.app.ProgressDialog; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Button; + +public class NotificationTest extends Activity { + static final int PROGRESS_DIALOG = 0; + Button button; + ProgressThread progressThread; + ProgressDialog progressDialog; + + /** Called when the activity is first created. */ + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.main); + + // Setup the button that starts the progress dialog + button = (Button) findViewById(R.id.progressDialog); + button.setOnClickListener(new OnClickListener(){ + public void onClick(View v) { + showDialog(PROGRESS_DIALOG); + } + }); + } + + protected Dialog onCreateDialog(int id) { + switch(id) { + case PROGRESS_DIALOG: + progressDialog = new ProgressDialog(NotificationTest.this); + progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); + progressDialog.setMessage("Loading..."); + progressThread = new ProgressThread(handler); + progressThread.start(); + return progressDialog; + default: + return null; + } + } + + // Define the Handler that receives messages from the thread and update the progress + final Handler handler = new Handler() { + public void handleMessage(Message msg) { + int total = msg.getData().getInt("total"); + progressDialog.setProgress(total); + if (total >= 100){ + dismissDialog(PROGRESS_DIALOG); + progressThread.setState(ProgressThread.STATE_DONE); + } + } + }; + + /** Nested class that performs progress calculations (counting) */ + private class ProgressThread extends Thread { + Handler mHandler; + final static int STATE_DONE = 0; + final static int STATE_RUNNING = 1; + int mState; + int total; + + ProgressThread(Handler h) { + mHandler = h; + } + + public void run() { + mState = STATE_RUNNING; + total = 0; + while (mState == STATE_RUNNING) { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + Log.e("ERROR", "Thread Interrupted"); + } + Message msg = mHandler.obtainMessage(); + Bundle b = new Bundle(); + b.putInt("total", total); + msg.setData(b); + mHandler.sendMessage(msg); + total++; + } + } + + /* sets the current state for the thread, + * used to stop the thread */ + public void setState(int state) { + mState = state; + } + } +} +</pre> + </div> <!-- end toggleme --> +</div> <!-- end toggleable --> + + + +<h2 id="CustomDialog">Creating a Custom Dialog</h2> + +<img src="{@docRoot}images/dialog_custom.png" alt="" style="float:right" /> + +<p>If you want a customized design for a dialog, you can create your own layout +for the dialog window with layout and widget elements. +After you've defined your layout, pass the root View object or +layout resource ID to {@link android.app.Dialog#setContentView(View)}.</p> + +<p>For example, to create the dialog shown to the right:</p> + +<ol> + <li>Create an XML layout saved as <code>custom_dialog.xml</code>: +<pre> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/layout_root" + android:orientation="horizontal" + android:layout_width="fill_parent" + android:layout_height="fill_parent" + android:padding="10dp" + > + <ImageView android:id="@+id/image" + android:layout_width="wrap_content" + android:layout_height="fill_parent" + android:layout_marginRight="10dp" + /> + <TextView android:id="@+id/text" + android:layout_width="wrap_content" + android:layout_height="fill_parent" + android:textColor="#FFF" + /> +</LinearLayout> +</pre> + + <p>This XML defines an {@link android.widget.ImageView} and a {@link android.widget.TextView} + inside a {@link android.widget.LinearLayout}.</p> + <li>Set the above layout as the dialog's content view and define the content + for the ImageView and TextView elements:</p> +<pre> +Context mContext = getApplicationContext(); +Dialog dialog = new Dialog(mContext); + +dialog.setContentView(R.layout.custom_dialog); +dialog.setTitle("Custom Dialog"); + +TextView text = (TextView) dialog.findViewById(R.id.text); +text.setText("Hello, this is a custom dialog!"); +ImageView image = (ImageView) dialog.findViewById(R.id.image); +image.setImageResource(R.drawable.android); +</pre> + + <p>After you instantiate the Dialog, set your custom layout as the dialog's content view with + {@link android.app.Dialog#setContentView(int)}, passing it the layout resource ID. + Now that the Dialog has a defined layout, you can capture View objects from the layout with + {@link android.app.Dialog#findViewById(int)} and modify their content.</p> + </li> + + <li>That's it. You can now show the dialog as described in + <a href="#ShowingADialog">Showing A Dialog</a>.</li> +</ol> + +<p>A dialog made with the base Dialog class must have a title. If you don't call +{@link android.app.Dialog#setTitle(CharSequence) setTitle()}, then the space used for the title +remains empty, but still visible. If you don't want +a title at all, then you should create your custom dialog using the +{@link android.app.AlertDialog} class. However, because an AlertDialog is created easiest with +the {@link android.app.AlertDialog.Builder} class, you do not have access to the +{@link android.app.Dialog#setContentView(int)} method used above. Instead, you must use +{@link android.app.AlertDialog.Builder#setView(View)}. This method accepts a {@link android.view.View} object, +so you need to inflate the layout's root View object from +XML.</p> + +<p>To inflate the XML layout, retrieve the {@link android.view.LayoutInflater} with +{@link android.app.Activity#getLayoutInflater()} +(or {@link android.content.Context#getSystemService(String) getSystemService()}), +and then call +{@link android.view.LayoutInflater#inflate(int, ViewGroup)}, where the first parameter +is the layout resource ID and the second is the ID of the root View. At this point, you can use +the inflated layout to find View objects in the layout and define the content for the +ImageView and TextView elements. Then instantiate the AlertDialog.Builder and set the +inflated layout for the dialog with {@link android.app.AlertDialog.Builder#setView(View)}.</p> + +<p>Here's an example, creating a custom layout in an AlertDialog:</p> + +<pre> +AlertDialog.Builder builder; +AlertDialog alertDialog; + +Context mContext = getApplicationContext(); +LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER); +View layout = inflater.inflate(R.layout.custom_dialog, + (ViewGroup) findViewById(R.id.layout_root)); + +TextView text = (TextView) layout.findViewById(R.id.text); +text.setText("Hello, this is a custom dialog!"); +ImageView image = (ImageView) layout.findViewById(R.id.image); +image.setImageResource(R.drawable.android); + +builder = new AlertDialog.Builder(mContext); +builder.setView(layout); +alertDialog = builder.create(); +</pre> + +<p>Using an AlertDialog for your custom layout lets you +take advantage of built-in AlertDialog features like managed buttons, +selectable lists, a title, an icon and so on.</p> + +<p>For more information, refer to the reference documentation for the +{@link android.app.Dialog} and {@link android.app.AlertDialog.Builder} +classes.</p> + + + diff --git a/docs/html/guide/topics/ui/how-android-draws.jd b/docs/html/guide/topics/ui/how-android-draws.jd index a511005..21f9833 100644 --- a/docs/html/guide/topics/ui/how-android-draws.jd +++ b/docs/html/guide/topics/ui/how-android-draws.jd @@ -70,8 +70,8 @@ and each View is responsible for drawing itself. 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. + For example, RelativeLayout has its own subclass of LayoutParams, which includes + the ability to center child Views horizontally and vertically. </p> <p> diff --git a/docs/html/guide/topics/ui/index.jd b/docs/html/guide/topics/ui/index.jd index 6bd1d15..ef23672 100644 --- a/docs/html/guide/topics/ui/index.jd +++ b/docs/html/guide/topics/ui/index.jd @@ -116,7 +116,7 @@ complex layout.</p> <p>There are a variety of ways in which you can layout your views. Using more and different kinds of view groups, you can structure child views and view groups in an infinite number of ways. -Some pre-defined view groups offered by Android (called layouts) include LinearLayout, RelativeLayout, AbsoluteLayout, +Some pre-defined view groups offered by Android (called layouts) include LinearLayout, RelativeLayout, TableLayout, GridLayout and others. Each offers a unique set of layout parameters that are used to define the positions of child views and layout structure.</p> <p>To learn about some of the different kinds of view groups used for a layout, diff --git a/docs/html/guide/topics/ui/layout-objects.jd b/docs/html/guide/topics/ui/layout-objects.jd index cf85fd6..bb13a18 100644 --- a/docs/html/guide/topics/ui/layout-objects.jd +++ b/docs/html/guide/topics/ui/layout-objects.jd @@ -10,7 +10,6 @@ parent.link=index.html <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> @@ -143,16 +142,6 @@ documentation for more details. </p> 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 adjust to different types of - displays. </p> - - <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 @@ -232,11 +221,6 @@ RelativeLayout</a> tutorial.</p> <th scope="col">Description</th> </tr> <tr> - <td>{@link android.widget.AbsoluteLayout AbsoluteLayout}<br /></td> - <td>Enables you to specify the location of child objects relative to the - parent in exact measurements (for example, pixels). </td> - </tr> - <tr> <td>{@link android.widget.FrameLayout FrameLayout}</td> <td>Layout that acts as a view frame to display a single object. </td> diff --git a/docs/html/guide/topics/ui/notifiers/index.jd b/docs/html/guide/topics/ui/notifiers/index.jd new file mode 100644 index 0000000..5b37f5b6 --- /dev/null +++ b/docs/html/guide/topics/ui/notifiers/index.jd @@ -0,0 +1,107 @@ +page.title=Notifying the User +@jd:body + +<div id="qv-wrapper"> + <div id="qv"> + <h2>In this document</h2> + <ol> + <li><a href="#Toast">Toast Notification</a></li> + <li><a href="#StatusBarNotification">Status Bar Notification</a></li> + <li><a href="#Dialog">Dialog Notification</a></li> + </ol> + <h2>More about</h2> + <ol> + <li><a href="toasts.html">Creating Toast Notifications</a></li> + <li><a href="notifications.html">Creating Status Bar Notifications</a></li> + <li><a href="{@docRoot}guide/topics/ui/dialogs.html">Creating Dialogs</a></li> + </ol> + </div> +</div> + +<p>Several types of situations may arise that require you to notify the user +about an event that occurs in your application. Some events require the user to respond +and others do not. For example:</p> +<ul> + <li>When an event such as saving a file is complete, a small message +should appear to confirm that the save was successful.</li> + <li>If the application is running in the background and needs the user's attention, +the application should create a notificaiton that allows the user to respond at +his or her convenience.</li> + <li>If the application is +performing work that the user must wait for (such as loading a file), +the application should show a hovering progress wheel or bar.</li> +</ul> + +<p>Each of these notification tasks can be achieved using a different technique:</p> +<ul> + <li>A <a href="#Toast">Toast Notification</a>, for brief messages that come + from the background.</li> + <li>A <a href="#StatusBar">Status Bar Notification</a>, for persistent reminders + that come from the background and request the user's response.</li> + <li>A <a href="#Dialog">Dialog Notification</a>, for Activity-related notifications.</li> +</ul> + +<p>This document summarizes each of these techniques for notifying the user and includes +links to full documentation.</p> + + +<h2 id="Toast">Toast Notification</h2> + +<img src="{@docRoot}images/toast.png" alt="" style="float:right" /> + +<p>A toast notificaiton is a message that pops up on the surface of the window. +It only fills the amount of space required for the message and the user's current +activity remains visible and interactive. The notification automatically fades in and +out, and does not accept interaction events. Because a toast can be created from a background +{@link android.app.Service}, it appears even if the application isn't visible.</p> + +<p>A toast is best for short text messages, such as "File saved," +when you're fairly certain the user is paying attention +to the screen. A toast can not accept user interaction events; if you'd like +the user to respond and take action, consider using a +<a href="#StatusBar">Status Bar Notification</a> instead.</p> + +<p>For more information, refer to <a href="toasts.html">Creating Toast Notifications</a>.</p> + + +<h2 id="StatusBar">Status Bar Notification</h2> + +<img src="{@docRoot}images/notifications_window.png" alt="" style="float:right; clear:right;" /> + +<p>A status bar notification adds an icon to the system's status bar +(with an optional ticker-text message) and an expanded message in the "Notifications" window. +When the user selects the expanded message, Android fires an +{@link android.content.Intent} that is defined by the notification (usually to launch an +{@link android.app.Activity}). +You can also configure the notification to alert the user with a sound, a vibration, and flashing +lights on the device.</p> + +<p>This kind of notification is ideal when your application is working in +a background {@link android.app.Service} and needs to +notify the user about an event. If you need to alert the user about an event that occurs +while your Activity is still in focus, consider using a +<a href="#Dialog">Dialog Notification</a> instead.</p> + +<p>For more information, refer to +<a href="notifications.html">Creating Status Bar Notifications</a>.</p> + + +<h2 id="Dialog">Dialog Notification</h2> + +<img src="{@docRoot}images/dialog_progress_spinning.png" alt="" style="float:right" /> + +<p>A dialog is usually a small window that appears in front of the current Activity. +The underlying Activity loses focus and the dialog accepts all user interaction. +Dialogs are normally used +for notifications and short activities that directly relate to the application in progress.</p> + +<p>You should use a dialog when you need to show a progress bar or a short +message that requires confirmation from the user (such as an alert with "OK" and "Cancel" buttons). +You can use also use dialogs as integral componenents +in your application's UI and for other purposes besides notifications. +For a complete discussion on all the available types of dialogs, +including its uses for notifications, refer to +<a href="{@docRoot}guide/topics/ui/dialogs.html">Creating Dialogs</a>.</p> + + + diff --git a/docs/html/guide/topics/ui/notifiers/notifications.jd b/docs/html/guide/topics/ui/notifiers/notifications.jd new file mode 100644 index 0000000..e6fa48f --- /dev/null +++ b/docs/html/guide/topics/ui/notifiers/notifications.jd @@ -0,0 +1,432 @@ +page.title=Creating Status Bar Notifications +parent.title=Notifying the User +parent.link=index.html +@jd:body + +<div id="qv-wrapper"> + <div id="qv"> + <h2>Key classes</h2> + <ol> + <li>{@link android.app.Notification}</li> + <li>{@link android.app.NotificationManager}</li> + </ol> + <h2>In this document</h2> + <ol> + <li><a href="#Basics">The Basics</a></li> + <li><a href="#ManageYourNotifications">Managing your Notifications</a></li> + <li><a href="#CreateANotification">Creating a Notification</a> + <ol> + <li><a href="#Update">Updating the notification</a></li> + <li><a href="#Sound">Adding a sound</a></li> + <li><a href="#Vibration">Adding vibration</a></li> + <li><a href="#Lights">Adding flashing lights</a></li> + <li><a href="#More">More features</a></li> + </ol> + </li> + <li><a href="#CustomExpandedView">Creating a Custom Expanded View</a></li> + </ol> + </div> +</div> + +<p>A status bar notification adds an icon to the system's status bar +(with an optional ticker-text message) and an expanded message in the "Notifications" window. +When the user selects the expanded message, Android fires an +{@link android.content.Intent} that is defined by the notification (usually to launch an +{@link android.app.Activity}). +You can also configure the notification to alert the user with a sound, a vibration, and flashing +lights on the device.</p> + +<p>A status bar notification should be used for any case in +which a background Service needs to alert the user about an event that requires a response. A background Service +<strong>should never</strong> launch an Activity on its own in order to receive user interaction. +The Service should instead create a status bar notification that will launch the Activity +when selected by the user.</p> + +<p>The screenshot below shows the status bar with a notification icon on the left side.</p> +<img src="{@docRoot}images/status_bar.png" alt="" /> + +<p>The next screenshot shows the notification's expanded message in the "Notifications" window. +The user can reveal the Notifications window by pulling down the status bar +(or selecting <em>Notifications</em> from the Home options menu).</p> +<img src="{@docRoot}images/notifications_window.png" alt="" /> + + +<h2 id="Basics">The Basics</h2> + +<p>An {@link android.app.Activity} or {@link android.app.Service} can initiate a status bar +notification. Because an Activity can perform actions only while it is +active and in focus, you should create your status bar notifications from a +Service. This way, the notification can be created from the background, +while the user is using another application or +while the device is asleep. To create a notification, you must use two +classes: {@link android.app.Notification} and {@link android.app.NotificationManager}.</p> + +<p>Use an instance of the {@link android.app.Notification} class to define the properties of your +status bar notification, such as the status bar icon, the expanded message, and extra settings such +as a sound to play. The {@link android.app.NotificationManager} is an Android system service that +executes and manages all Notifications. You do not instantiate the NotificationManager. In order +to give it your Notification, you must retrieve a reference to the NotificationManager with +{@link android.app.Activity#getSystemService(String) getSystemService()} and +then, when you want to notify the user, pass it your Notification object with +{@link android.app.NotificationManager#notify(int,Notification) notify()}. </p> + +<p>To create a status bar notification:</p> +<ol> + <li>Get a reference to the NotificationManager: +<pre> +String ns = Context.NOTIFICATION_SERVICE; +NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); +</pre> + </li> + <li>Instantiate the Notification: +<pre> +int icon = R.drawable.notification_icon; +CharSequence tickerText = "Hello"; +long when = System.currentTimeMillis(); + +Notification notification = new Notification(icon, tickerText, when); +</pre> + </li> + <li>Define the Notification's expanded message and Intent: +<pre> +Context context = getApplicationContext(); +CharSequence contentTitle = "My notification"; +CharSequence contentText = "Hello World!"; +Intent notificationIntent = new Intent(this, MyClass.class); +PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); + +notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); +</pre> + </li> + <li>Pass the Notification to the NotificationManager: +<pre> +private static final int HELLO_ID = 1; + +mNotificationManager.notify(HELLO_ID, notification); +</pre> + <p>That's it. Your user has now been notified.</p> + </li> +</ol> + + +<h2 id="ManageYourNotifications">Managing your Notifications</h2> + +<p>The {@link android.app.NotificationManager} is a system service that manages all +notifications. You must retrieve a reference to it with the +{@link android.app.Activity#getSystemService(String) getSystemService()} method. +For example:</p> +<pre> +String ns = Context.NOTIFICATION_SERVICE; +NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); +</pre> + +<p>When you want to send your status bar notification, pass the Notification object +to the NotificationManager with {@link android.app.NotificationManager#notify(int,Notification)}. +The first parameter is the unique ID for the Notification and the second is the Notification object. +The ID uniquely identifies the Notification from within your +application. This is necessary if you need to update the Notification or (if +your application manages different kinds of Notifications) select the appropriate action +when the user returns to your application via the Intent defined in the Notification.</p> + +<p>To clear the status bar notification when the user selects it from the Notifications +window, add the "FLAG_AUTO_CANCEL" flag to your Notification object. You can also clear it +manually with {@link android.app.NotificationManager#cancel(int)}, passing it the notification ID, +or clear all your Notifications with {@link android.app.NotificationManager#cancelAll()}.</p> + + +<h2 id="CreateANotification">Creating a Notification</h2> + +<p>A {@link android.app.Notification} object defines the details of the notification +message that is displayed in the status bar and "Notifications" window, and any other +alert settings, such as sounds and blinking lights.</p> + +<p>A status bar notification <em>requires</em> all of the following:</p> +<ul> + <li>An icon for the status bar</li> + <li>A title and expanded message for the expanded view (unless you define a + <a href="#CustomExpandedView">custom expanded view</a>)</li> + <li>A {@link android.app.PendingIntent}, to be fired when the notification is selected</li> +</ul> +<p>Optional settings for the status bar notification include:</p> +<ul> + <li>A ticker-text message for the status bar</li> + <li>An alert sound</li> + <li>A vibrate setting</li> + <li>A flashing LED setting</li> +</ul> + +<p>The starter-kit for a new Notification includes the +{@link android.app.Notification#Notification(int,CharSequence,long)} constructor and the +{@link android.app.Notification#setLatestEventInfo(Context,CharSequence,CharSequence,PendingIntent)} +method. These define all the required settings for a Notification. +The following snippet demonstrates a basic Notification setup:</p> +<pre> +int icon = R.drawable.notification_icon; // icon from resources +CharSequence tickerText = "Hello"; // ticker-text +long when = System.currentTimeMillis(); // notification time +Context context = getApplicationContext(); // application Context +CharSequence contentTitle = "My notification"; // expanded message title +CharSequence contentText = "Hello World!"; // expanded message text + +Intent notificationIntent = new Intent(this, MyClass.class); +PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); + +// the next two lines initialize the Notification, using the configurations above +Notification notification = new Notification(icon, tickerText, when); +notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); +</pre> + + +<h3 id="Updating">Updating the notification</h3> + +<p>You can update the information in your status bar notification as events +continue to occur in your application. For example, when a new SMS text message arrives +before previous messages have been read, the Messaging application updates the existing +notification to display the total number of new messages received. +This practice of updating an existing Notification is much better than adding new Notifications +to the NotificationManager because it avoids clutter in the Notifications window.</p> + +<p>Because each notification is uniquely identified +by the NotificationManager with an integer ID, you can revise the notification by calling +{@link android.app.Notification#setLatestEventInfo(Context,CharSequence,CharSequence,PendingIntent) +setLatestEventInfo()} with new values, change some field values of the Notification, and then call +{@link android.app.NotificationManager#notify(int,Notification) notify()} again.</p> + +<p>You can revise each property with the object member fields +(except for the Context and the expanded message title and text). You should always +revise the text message when you update the notification by calling +{@link android.app.Notification#setLatestEventInfo(Context,CharSequence,CharSequence,PendingIntent) +setLatestEventInfo()} with new values for <var>contentTitle</var> and <var>contentText</var>. +Then call {@link android.app.NotificationManager#notify(int,Notification) notify()} to update the +notification. (Of course, if you've created a <a href="#CustomExpandedView">custom expanded +view</a>, then updating these title and text values has no effect.)</p> + + +<h3 id="Sound">Adding a sound</h3> + +<p>You can alert the user with the default notification sound +(which is defined by the user) or with a sound specified by your application.</p> + +<p>To use the user's default sound, add "DEFAULT_SOUND" to the <var>defaults</var> field:</p> +<pre> +notification.defaults |= Notification.DEFAULT_SOUND; +</pre> + +<p>To use a different sound with your notifications, pass a Uri reference to the +<var>sound</var> field. +The following example uses a known audio file saved to the device SD card:</p> +<pre> +notification.sound = Uri.parse("file:///sdcard/notification/ringer.mp3"); +</pre> + +<p>In the next example, the audio file is chosen from the internal +{@link android.provider.MediaStore.Audio.Media MediaStore}'s {@link android.content.ContentProvider}:</p> +<pre> +notification.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6"); +</pre> + +<p>In this case, the exact ID of the media file ("6") is known and appended to the content +{@link android.net.Uri}. If you don't know the exact ID, you must query all the +media available in the MediaStore with a {@link android.content.ContentResolver}. +See the <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a> +documentation for more information on using a ContentResolver.</p> + +<p>If you want the sound to continuously repeat until the user responds to the notification +or the notification is cancelled, add "FLAG_INSISTENT" to the <var>flags</var> field.</p> + +<p class="note"><strong>Note:</strong> If the <var>defaults</var> field includes +"DEFAULT_SOUND", then the default sound overrides any sound defined by the <var>sound</var> field.</p> + + +<h3 id="Vibration">Adding vibration</h3> + +<p>You can alert the user with the the default +vibration pattern or with a vibration pattern defined by your application.</p> + +<p>To use the default pattern, add "DEFAULT_VIBRATE" to the <var>defaults</var> field:</p> +<pre> +notification.defaults |= Notification.DEFAULT_VIBRATE; +</pre> + +<p>To define your own vibration pattern, pass an array of <em>long</em> values to the +<var>vibrate</var> field:</p> +<pre> +long[] vibrate = {0,100,200,300}; +notification.vibrate = vibrate; +</pre> + +<p>The long array defines the alternating pattern for the length of vibration off and on +(in milliseconds). The first value is how long to wait (off) before beginning, the second +value is the length of the first vibration, the third is the next length off, and so on. +The pattern can be as long as you like, but it can't be set to repeat. +</p> + +<p class="note"><strong>Note:</strong> If the <var>defaults</var> field includes +"DEFAULT_VIBRATE", then the default vibration overrides any vibration defined by the +<var>vibrate</var> field.</p> + + +<h3 id="Lights">Adding flashing lights</h3> + +<p>To alert the user by flashing LED lights, you can implement the default +light pattern (if available), or define your own color and pattern for the lights.</p> + +<p>To use the default light setting, add "DEFAULT_LIGHTS" to the <var>defaults</var> field:</p> +<pre> +notification.defaults |= Notification.DEFAULT_LIGHTS; +</pre> + +<p>To define your own color and pattern, define a value for the <var>ledARGB</var> field +(for the color), the <var>ledOffMS</var> field (length of time, in milliseconds, to +keep the light off), the <var>ledOnMS</var> (length of time, in milliseconds, to keep the light on), +and also add "FLAG_SHOW_LIGHTS" to the <var>flags</var> field:</p> +<pre> +notification.ledARGB = 0xff00ff00; +notification.ledOnMS = 300; +notification.ledOffMS = 1000; +notification.flags |= Notification.FLAG_SHOW_LIGHTS; +</pre> + +<p>In this example, the green light repeatedly flashes on for 300 milliseconds and +turns off for one second. Not every color in the spectrum is supported by the +device LEDs, and not every device supports the same colors, so the hardware +estimates to the best of its ability. Green is the most common notification color.</p> + + +<h3 id="More">More features</h3> + +<p>You can add several more features to your notifications +using Notification fields and flags. Some useful features include the following:</p> + +<dl> + <dt>"FLAG_AUTO_CANCEL" flag</dt> + <dd>Add this to the <var>flags</var> field to automatically cancel the notification + after it is selected from the Notifications window.</dd> + <dt>"FLAG_INSISTENT" flag</dt> + <dd>Add this to the <var>flags</var> field to repeat the audio until the + user responds.</dd> + <dt>"FLAG_ONGOING_EVENT" flag</dt> + <dd>Add this to the <var>flags</var> field to group the notification under the "Ongoing" + title in the Notifications window. This indicates that the application is on-going — + its processes is still running in the background, even when the application is not + visible (such as with music or a phone call).</dd> + <dt>"FLAG_NO_CLEAR" flag</dt> + <dd>Add this to the <var>flags</var> field to indicate that the notification should + <em>not</em> be cleared by the "Clear notifications" button. This is particularly useful if + your notification is on-going.</dd> + <dt><var>number</var> field</dt> + <dd>This value indicates the current number of events represented by the notification. + The appropriate number is overlayed on top of the status bar icon. + If you intend to use this field, then you must start with "1" when the Notification is first + created. (If you change the value from zero to anything greater during an update, the number + is not shown.)</dd> + <dt><var>iconLevel</var> field</dt> + <dd>This value indicates the current level of a + {@link android.graphics.drawable.LevelListDrawable} that is used for the notification icon. + You can animate the icon in the status bar by changing this value to correlate with the + drawable's defined in a LevelListDrawable. See the {@link android.graphics.drawable.LevelListDrawable} + reference for more information.</dd> +</dl> + +<p>See the {@link android.app.Notification} class reference for more information about additional +features that you can customize for your application.</p> + + +<h2 id="CustomExpandedView">Creating a Custom Expanded View</h2> + +<img src="{@docRoot}images/custom_message.png" alt="" style="float:right;" /> + +<p>By default, the expanded view used in the "Notifications" window includes a basic title and text +message. These are defined by the <var>contentTitle</var> and <var>contentText</var> +parameters of the {@link android.app.Notification#setLatestEventInfo(Context,CharSequence,CharSequence,PendingIntent) +setLatestEventInfo()} method. However, you can also define a custom layout for the expanded view using +{@link android.widget.RemoteViews}. The screenshot to the right shows an example of a +custom expanded view that uses an ImageView and TextView in a LinearLayout.</p> + +<p>To define your own layout for the expanded message, +instantiate a {@link android.widget.RemoteViews} object and +pass it to the <var>contentView</var> field of your Notification. Pass the +{@link android.app.PendingIntent} to the <var>contentIntent</var> field.</p> + +<p>Creating a custom expanded view is best understood with an example:</p> + +<ol> + <li>Create the XML layout for the expanded view. + For example, create a layout file called <code>custom_notification_layout.xml</code> and + build it like so: +<pre> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:orientation="horizontal" + android:layout_width="fill_parent" + android:layout_height="fill_parent" + android:padding="3dp" + > + <ImageView android:id="@+id/image" + android:layout_width="wrap_content" + android:layout_height="fill_parent" + android:layout_marginRight="10dp" + /> + <TextView android:id="@+id/text" + android:layout_width="wrap_content" + android:layout_height="fill_parent" + android:textColor="#000" + /> +</LinearLayout> +</pre> + + <p>This layout is used for the expanded view, + but the content of the ImageView and TextView still needs to be defined by the applicaiton. + RemoteViews offers some convenient methods that allow you to define this content...</p> + </li> + + <li>In the application code, use the RemoveViews + methods to define the image and text. Then pass the RemoteViews object to the <var>contentView</var> + field of the Notification, as shown in this example: +<pre> +RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification_layout); +contentView.setImageViewResource(R.id.image, R.drawable.notification_image); +contentView.setTextViewText(R.id.text, "Hello, this message is in a custom expanded view"); +notification.contentView = contentView; +</pre> + + <p>As shown here, pass the applicaiton's package name and the layout + resource ID to the RemoteViews constructor. Then, define the content for the ImageView and TextView, + using the {@link android.widget.RemoteViews#setImageViewResource(int, int) setImageViewResource()} + and {@link android.widget.RemoteViews#setTextViewText(int, CharSequence) setTextViewText()}. + In each case, pass the reference ID of the appropriate View object that you want to set, along with + the value for that View. Finally, the RemoteViews object is passed to the Notification in the + <var>contentView</var> field.</p> + </li> + + <li>Because you don't need the + {@link android.app.Notification#setLatestEventInfo(Context,CharSequence,CharSequence,PendingIntent) + setLatestEventInfo()} method when using a custom view, you must define the Intent for the Notification + with the <var>contentIntent</var> field, as in this example: +<pre> +Intent notificationIntent = new Intent(this, MyClass.class); +PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); +notification.contentIntent = contentIntent; +</pre> + </li> + + <li>The notification can now be sent as usual: + <pre>mNotificationManager.notify(CUSTOM_VIEW_ID, notification);</pre> + </li> +</ol> + + +<p>The RemoteViews class also includes methods that you can use to easily add a +{@link android.widget.Chronometer} or {@link android.widget.ProgressBar} +in your notification's expanded view. For more information about creating custom layouts with +RemoteViews, refer to the {@link android.widget.RemoteViews} class reference.</p> + +<p class="warning"><strong>Note:</strong> +When creating a custom expanded view, you must take special care to ensure that your +custom layout functions properly in different device orientations and resolutions. While this +advice applies to all View layouts created on Android, it is especially important in this case +because your layout real estate is very restricted. So don't make your custom layout too +complex and be sure to test it in various configurations.</p> + + + + diff --git a/docs/html/guide/topics/ui/notifiers/toasts.jd b/docs/html/guide/topics/ui/notifiers/toasts.jd new file mode 100644 index 0000000..a800c3c --- /dev/null +++ b/docs/html/guide/topics/ui/notifiers/toasts.jd @@ -0,0 +1,154 @@ +page.title=Creating Toast Notifications +parent.title=Notifying the User +parent.link=index.html +@jd:body + +<div id="qv-wrapper"> + <div id="qv"> + <h2>Key classes</h2> + <ol> + <li>{@link android.widget.Toast}</li> + </ol> + <h2>In this document</h2> + <ol> + <li><a href="#Basics">The Basics</a></li> + <li><a href="#Position">Positioning your Toast</a></li> + <li><a href="#CustomToastView">Creating a Custom Toast View</a></li> + </ol> + </div> +</div> + +<p>A toast notificaiton is a message that pops up on the surface of the window. +It only fills the amount of space required for the message and the user's current +activity remains visible and interactive. The notification automatically fades in and +out, and does not accept interaction events.</p> + +<p>The screenshot below shows an example toast notification from the Alarm application. +Once an alarm is turned on, a toast is displayed to assure you that the +alarm was set.</p> +<img src="{@docRoot}images/toast.png" alt="" /> + +<p>A toast can be created and displayed from an {@link android.app.Activity} or +{@link android.app.Service}. If you create a toast notification from a Service, it +appears in front of the Activity currently in focus.</p> + +<p>If user response to the notification is required, consider using a +<a href="notifications.html">Status Bar Notification</a>.</p> + + +<h2 id="Basics">The Basics</h2> + +<p>First, instantiate a {@link android.widget.Toast} +object with one of the {@link android.widget.Toast#makeText(Context,int,int) makeText()} methods. +This method takes three parameters: the application {@link android.content.Context}, +the text message, and the duration for the toast. It returns a properly initialized Toast +object. You can display the toast notification with {@link android.widget.Toast#show()}, +as shown in the following example:</p> + +<pre> +Context context = getApplicationContext(); +CharSequence text = "Hello toast!"; +int duration = Toast.LENGTH_SHORT; + +Toast toast = Toast.makeText(context, text, duration); +toast.show(); +</pre> + +<p>This example demonstrates everything you need for most toast notifications. +You should rarely need anything else. You may, however, want to position the +toast differently or even use your own layout instead of a simple text message. +The following sections describe how you can do these things.</p> + +<p>You can also chain your methods and avoid holding on to the Toast object, like this:</p> +<pre>Toast.makeText(context, text, duration).show();</pre> + + +<h2 id="Positioning">Positioning your Toast</h2> + +<p>A standard toast notification appears near the bottom of the screen, centered horizontally. +You can change this position with the {@link android.widget.Toast#setGravity(int,int,int)} +method. This accepts three parameters: a {@link android.view.Gravity} constant, +an x-position offset, and a y-position offset.</p> + +<p>For example, if you decide that the toast should appear in the top-left corner, you can set the +gravity like this:</p> +<pre> +toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0); +</pre> + +<p>If you want to nudge the position to the right, increase the value of the second parameter. +To nudge it down, increase the value of the last parameter. + + +<h2 id="CustomToastView">Creating a Custom Toast View</h2> + +<img src="{@docRoot}images/custom_toast.png" alt="" style="float:right" /> + +<p>If a simple text message isn't enough, you can create a customized layout for your +toast notification. To create a custom layout, define a View layout, +in XML or in your application code, and pass the root {@link android.view.View} object +to the {@link android.widget.Toast#setView(View)} method.</p> + +<p>For example, you can create the layout for the toast visible in the screenshot to the right +with the following XML (saved as <em>toast_layout.xml</em>):</p> +<pre> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/toast_layout_root" + android:orientation="horizontal" + android:layout_width="fill_parent" + android:layout_height="fill_parent" + android:padding="10dp" + android:background="#DAAA" + > + <ImageView android:id="@+id/image" + android:layout_width="wrap_content" + android:layout_height="fill_parent" + android:layout_marginRight="10dp" + /> + <TextView android:id="@+id/text" + android:layout_width="wrap_content" + android:layout_height="fill_parent" + android:textColor="#FFF" + /> +</LinearLayout> +</pre> + +<p>Notice that the ID of the LinearLayout element is "toast_layout". You must use this +ID to inflate the layout from the XML, as shown here:</p> + +<pre> +LayoutInflater inflater = getLayoutInflater(); +View layout = inflater.inflate(R.layout.toast_layout, + (ViewGroup) findViewById(R.id.toast_layout_root)); + +ImageView image = (ImageView) layout.findViewById(R.id.image); +image.setImageResource(R.drawable.android); +TextView text = (TextView) layout.findViewById(R.id.text); +text.setText("Hello! This is a custom toast!"); + +Toast toast = new Toast(getApplicationContext()); +toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); +toast.setDuration(Toast.LENGTH_LONG); +toast.setView(layout); +toast.show(); +</pre> + +<p>First, retrieve the {@link android.view.LayoutInflater} with +{@link android.app.Activity#getLayoutInflater()} +(or {@link android.content.Context#getSystemService(String) getSystemService()}), +and then inflate the layout from XML using +{@link android.view.LayoutInflater#inflate(int, ViewGroup)}. The first parameter +is the layout resource ID and the second is the root View. You can use +this inflated layout to find more View objects in the layout, so now capture and +define the content for the ImageView and TextView elements. Finally, create +a new Toast with {@link android.widget.Toast#Toast(Context)} and set some properties +of the toast, such as the gravity and duration. Then call +{@link android.widget.Toast#setView(View)} and pass it the inflated layout. +You can now display the toast with your custom layout by calling +{@link android.widget.Toast#show()}.</p> + +<p class="note"><strong>Note:</strong> Do not use the public constructor for a Toast +unless you are going to define the layout with {@link android.widget.Toast#setView(View)}. +If you do not have a custom layout to use, you must use +{@link android.widget.Toast#makeText(Context,int,int)} to create the Toast.</p> + |