diff options
Diffstat (limited to 'docs/html/guide/topics')
59 files changed, 7039 insertions, 2443 deletions
diff --git a/docs/html/guide/topics/admin/device-admin.jd b/docs/html/guide/topics/admin/device-admin.jd index 820c3c0..4a325db 100644 --- a/docs/html/guide/topics/admin/device-admin.jd +++ b/docs/html/guide/topics/admin/device-admin.jd @@ -75,8 +75,8 @@ server. </li> not currently have an automated provisioning solution. Some of the ways a sysadmin might distribute the application to users are as follows: <ul> -<li>Android Market.</li> -<li>Enabling non-market installation.</li> +<li>Google Play.</li> +<li>Enabling installation from another store.</li> <li>Distributing the application through other means, such as email or websites.</li> </ul> diff --git a/docs/html/guide/topics/appwidgets/index.jd b/docs/html/guide/topics/appwidgets/index.jd index 2cb23c1..ba7b67c 100644 --- a/docs/html/guide/topics/appwidgets/index.jd +++ b/docs/html/guide/topics/appwidgets/index.jd @@ -186,36 +186,34 @@ folder.</p> <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> -<p class="note"><strong>Note:</strong> To make your app widget portable across -devices, your app widget's minimum size should never be larger than 4 x 4 cells. -See the <a -href="{@docRoot}guide/practices/ui_guidelines/widget_design.html#sizes">App -Widget Design Guidelines</a> for more discussion of Home screen cell sizes.</p> + attributes specify the minimum amount of space the App Widget consumes + <em>by default</em>. 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. + <p>See the <a href="{@docRoot}guide/practices/ui_guidelines/widget_design.html#anatomy_determining_size"> + App Widget Design Guidelines</a> for more information on sizing your App + Widgets.</p> + + <p class="note"><strong>Note:</strong> To make your app widget portable + across devices, your app widget's minimum size should never be larger + than 4 x 4 cells.</p> </li> + + <li>The <code>minResizeWidth</code> and <code>minResizeHeight</code> attributes + specify the App Widget's absolute minimum size. These values should specify + the size below which the App Widget would be illegible or otherwise unusable. + Using these attributes allows the user to resize the widget to a size that + may be smaller than the default widget size defined by the + <code>minWidth</code> and <code>minHeight</code> attributes. + Introduced in Android 3.1. + + <p>See the <a href="{@docRoot}guide/practices/ui_guidelines/widget_design.html#anatomy_determining_size"> + App Widget Design Guidelines</a> for more information on sizing your App + Widgets.</p> + </li> + <li>The <code>updatePeriodMillis</code> attribute defines how often the App Widget framework should request an update from the {@link android.appwidget.AppWidgetProvider} by calling the @@ -520,15 +518,12 @@ 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 +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}resources/samples/ApiDemos/src/com/example/android/apis/ -appwidget/ExampleAppWidgetProvider.html"> -ExampleAppWidgetProvider.java</a> sample class.</p> +href="{@docRoot}resources/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> @@ -685,9 +680,8 @@ cancelled and the App Widget will not be added.</p> <p>See the <a -href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/ -appwidget/ExampleAppWidgetConfigure.html"> -ExampleAppWidgetConfigure.java</a> sample class in ApiDemos for an example.</p> +href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/appwidget/ExampleAppWidgetConfigure.html">ExampleAppWidgetConfigure.java</a> +sample class in ApiDemos for an example.</p> <h2 id="preview">Setting a Preview Image</h2> diff --git a/docs/html/guide/topics/data/backup.jd b/docs/html/guide/topics/data/backup.jd index dec2146..4eba4f3 100644 --- a/docs/html/guide/topics/data/backup.jd +++ b/docs/html/guide/topics/data/backup.jd @@ -900,8 +900,8 @@ href="{@docRoot}guide/developing/tools/bmgr.html">{@code bmgr}</a>.</p> <li>Install your application on a suitable Android system image <ul> <li>If using the emulator, create and use an AVD with Android 2.2 (API Level 8).</li> - <li>If using a device, the device must be running Android 2.2 or greater and have Android -Market built in.</li> + <li>If using a device, the device must be running Android 2.2 or greater and have Google +Play built in.</li> </ul> </li> <li>Ensure that backup is enabled diff --git a/docs/html/guide/topics/fundamentals.jd b/docs/html/guide/topics/fundamentals.jd index 661f5cb..a86d905 100644 --- a/docs/html/guide/topics/fundamentals.jd +++ b/docs/html/guide/topics/fundamentals.jd @@ -243,7 +243,7 @@ performing transactions with the provider doesn't need to and instead calls meth android.content.ContentResolver} object. This leaves a layer of abstraction between the content provider and the component requesting information (for security).</p> -<p>There are separate methods for activiting each type of component:</p> +<p>There are separate methods for activating each type of component:</p> <ul> <li>You can start an activity (or give it something new to do) by passing an {@link android.content.Intent} to {@link android.content.Context#startActivity @@ -392,15 +392,15 @@ same features and capabilities. In order to prevent your application from being that lack features needed by your application, it's important that you clearly define a profile for the types of devices your application supports by declaring device and software requirements in your manifest file. Most of these declarations are informational only and the system does not read -them, but external services such as Android Market do read them in order to provide filtering +them, but external services such as Google Play do read them in order to provide filtering for users when they search for applications from their device.</p> <p>For example, if your application requires a camera and uses APIs introduced in Android 2.1 (<a href="{@docRoot}guide/appendix/api-levels.html">API Level</a> 7), you should declare these as requirements in your manifest file. That way, devices that do <em>not</em> have a camera and have an -Android version <em>lower</em> than 2.1 cannot install your application from Android Market.</p> +Android version <em>lower</em> than 2.1 cannot install your application from Google Play.</p> -<p>However, you can also declare that your applicaiton uses the camera, but does not +<p>However, you can also declare that your application uses the camera, but does not <em>require</em> it. In that case, your application must perform a check at runtime to determine if the device has a camera and disable any features that use the camera if one is not available.</p> @@ -458,12 +458,12 @@ element.</dd> </dl> <p>It's important that you declare all such requirements for your application, because, when you -distribute your application on Android Market, Market uses these declarations to filter which +distribute your application on Google Play, the store uses these declarations to filter which applications are available on each device. As such, your application should be available only to devices that meet all your application requirements.</p> -<p>For more information about how Android Market filters applications based on these (and other) -requirements, see the <a href="{@docRoot}guide/appendix/market-filters.html">Market Filters</a> +<p>For more information about how Google Play filters applications based on these (and other) +requirements, see the <a href="{@docRoot}guide/appendix/market-filters.html">Filters on Google Play</a> document.</p> diff --git a/docs/html/guide/topics/fundamentals/activities.jd b/docs/html/guide/topics/fundamentals/activities.jd index cb453da..b79136c 100644 --- a/docs/html/guide/topics/fundamentals/activities.jd +++ b/docs/html/guide/topics/fundamentals/activities.jd @@ -19,9 +19,10 @@ page.title=Activities </li> <li><a href="#StartingAnActivity">Starting an Activity</a> <ol> - <li><a href="#StartingAnActivityForResult">Starting an Activity for a Result</a></li> + <li><a href="#StartingAnActivityForResult">Starting an activity for a result</a></li> </ol> </li> + <li><a href="#ShuttingDown">Shutting Down an Activity</a></li> <li><a href="#Lifecycle">Managing the Activity Lifecycle</a> <ol> <li><a href="#ImplementingLifecycleCallbacks">Implementing the lifecycle callbacks</a></li> @@ -61,8 +62,8 @@ is presented to the user when launching the application for the first time. Each activity can then start another activity in order to perform different actions. Each time a new activity starts, the previous activity is stopped, but the system preserves the activity in a stack (the "back stack"). When a new activity starts, it is pushed onto the back stack and -takes user focus. The back stack abides to the basic "last in, first out" queue mechanism, -so, when the user is done with the current activity and presses the BACK key, it +takes user focus. The back stack abides to the basic "last in, first out" stack mechanism, +so, when the user is done with the current activity and presses the <em>Back</em> button, it is popped from the stack (and destroyed) and the previous activity resumes. (The back stack is discussed more in the <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back Stack</a> document.)</p> @@ -612,17 +613,9 @@ that when an activity is paused or stopped, the state of the activity is retained. This is true because the {@link android.app.Activity} object is still held in memory when it is paused or stopped—all information about its members and current state is still alive. Thus, any changes -the user made within the activity are retained in memory, so that when the activity returns to the +the user made within the activity are retained so that when the activity returns to the foreground (when it "resumes"), those changes are still there.</p> -<div class="figure" style="width:615px"> -<img src="{@docRoot}images/fundamentals/restore_instance.png" alt="" /> -<p class="img-caption"><strong>Figure 2.</strong> The two ways in which an activity returns to user -focus with its state intact: either the activity is stopped, then resumed and the activity state -remains intact (left), or the activity is destroyed, then recreated and the activity must restore -the previous activity state (right).</p> -</div> - <p>However, when the system destroys an activity in order to recover memory, the {@link android.app.Activity} object is destroyed, so the system cannot simply resume it with its state intact. Instead, the system must recreate the {@link android.app.Activity} object if the user @@ -630,26 +623,36 @@ navigates back to it. Yet, the user is unaware that the system destroyed the activity and recreated it and, thus, probably expects the activity to be exactly as it was. In this situation, you can ensure that important information about the activity state is preserved by implementing an additional -callback method that allows you to save information about the state of your activity and then -restore it when the the system recreates the activity.</p> +callback method that allows you to save information about the state of your activity: {@link +android.app.Activity#onSaveInstanceState onSaveInstanceState()}.</p> -<p>The callback method in which you can save information about the current state of your activity is -{@link android.app.Activity#onSaveInstanceState onSaveInstanceState()}. The system calls this method -before making the activity vulnerable to being destroyed and passes it -a {@link android.os.Bundle} object. The {@link android.os.Bundle} is where you can store +<p>The system calls {@link android.app.Activity#onSaveInstanceState onSaveInstanceState()} +before making the activity vulnerable to destruction. The system passes this method +a {@link android.os.Bundle} in which you can save state information about the activity as name-value pairs, using methods such as {@link -android.os.Bundle#putString putString()}. Then, if the system kills your activity's -process and the user navigates back to your activity, the system passes the {@link -android.os.Bundle} to {@link android.app.Activity#onCreate onCreate()} so you can restore the -activity state you saved during {@link android.app.Activity#onSaveInstanceState -onSaveInstanceState()}. If there is no state information to restore, then the {@link -android.os.Bundle} passed to {@link android.app.Activity#onCreate onCreate()} is null.</p> +android.os.Bundle#putString putString()} and {@link +android.os.Bundle#putInt putInt()}. Then, if the system kills your application +process and the user navigates back to your activity, the system recreates the activity and passes +the {@link android.os.Bundle} to both {@link android.app.Activity#onCreate onCreate()} and {@link +android.app.Activity#onRestoreInstanceState onRestoreInstanceState()}. Using either of these +methods, you can extract your saved state from the {@link android.os.Bundle} and restore the +activity state. If there is no state information to restore, then the {@link +android.os.Bundle} passed to you is null (which is the case when the activity is created for +the first time).</p> + +<img src="{@docRoot}images/fundamentals/restore_instance.png" alt="" /> +<p class="img-caption"><strong>Figure 2.</strong> The two ways in which an activity returns to user +focus with its state intact: either the activity is destroyed, then recreated and the activity must restore +the previously saved state, or the activity is stopped, then resumed and the activity state +remains intact.</p> <p class="note"><strong>Note:</strong> There's no guarantee that {@link android.app.Activity#onSaveInstanceState onSaveInstanceState()} will be called before your activity is destroyed, because there are cases in which it won't be necessary to save the state -(such as when the user leaves your activity using the BACK key, because the user is explicitly -closing the activity). If the method is called, it is always called before {@link +(such as when the user leaves your activity using the <em>Back</em> button, because the user is +explicitly +closing the activity). If the system calls {@link android.app.Activity#onSaveInstanceState +onSaveInstanceState()}, it does so before {@link android.app.Activity#onStop onStop()} and possibly before {@link android.app.Activity#onPause onPause()}.</p> @@ -657,17 +660,17 @@ onPause()}.</p> android.app.Activity#onSaveInstanceState onSaveInstanceState()}, some of the activity state is restored by the {@link android.app.Activity} class's default implementation of {@link android.app.Activity#onSaveInstanceState onSaveInstanceState()}. Specifically, the default -implementation calls {@link -android.view.View#onSaveInstanceState onSaveInstanceState()} for every {@link android.view.View} -in the layout, which allows each view to provide information about itself +implementation calls the corresponding {@link +android.view.View#onSaveInstanceState onSaveInstanceState()} method for every {@link +android.view.View} in the layout, which allows each view to provide information about itself that should be saved. Almost every widget in the Android framework implements this method as appropriate, such that any visible changes to the UI are automatically saved and restored when your activity is recreated. For example, the {@link android.widget.EditText} widget saves any text entered by the user and the {@link android.widget.CheckBox} widget saves whether it's checked or not. The only work required by you is to provide a unique ID (with the <a href="{@docRoot}guide/topics/resources/layout-resource.html#idvalue">{@code android:id}</a> -attribute) for each widget you want to save its state. If a widget does not have an ID, then it -cannot save its state.</p> +attribute) for each widget you want to save its state. If a widget does not have an ID, then the +system cannot save its state.</p> <div class="sidebox-wrapper"> <div class="sidebox"> @@ -689,7 +692,9 @@ restored, by default).</p> android.app.Activity#onSaveInstanceState onSaveInstanceState()} helps save the state of the UI, if you override the method in order to save additional state information, you should always call the superclass implementation of {@link android.app.Activity#onSaveInstanceState onSaveInstanceState()} -before doing any work.</p> +before doing any work. Likewise, you should also call the supercall implementation of {@link +android.app.Activity#onRestoreInstanceState onRestoreInstanceState()} if you override it, so the +default implementation can restore view states.</p> <p class="note"><strong>Note:</strong> Because {@link android.app.Activity#onSaveInstanceState onSaveInstanceState()} is not guaranteed @@ -701,7 +706,7 @@ to a database) when the user leaves the activity.</p> <p>A good way to test your application's ability to restore its state is to simply rotate the device so that the screen orientation changes. When the screen orientation changes, the system destroys and recreates the activity in order to apply alternative resources that might be available -for the new orientation. For this reason alone, it's very important that your activity +for the new screen configuration. For this reason alone, it's very important that your activity completely restores its state when it is recreated, because users regularly rotate the screen while using applications.</p> @@ -709,22 +714,25 @@ using applications.</p> <h3 id="ConfigurationChanges">Handling configuration changes</h3> <p>Some device configurations can change during runtime (such as screen orientation, keyboard -availability, and language). When such a change occurs, Android restarts the running Activity -({@link android.app.Activity#onDestroy} is called, followed immediately by {@link -android.app.Activity#onCreate onCreate()}). The restart behavior is +availability, and language). When such a change occurs, Android recreates the running activity +(the system calls {@link android.app.Activity#onDestroy}, then immediately calls {@link +android.app.Activity#onCreate onCreate()}). This behavior is designed to help your application adapt to new configurations by automatically reloading your -application with alternative resources that you've provided. If you design your activity to -properly handle this event, it will be more resilient to unexpected events in the activity -lifecycle.</p> +application with alternative resources that you've provided (such as different layouts for +different screen orientations and sizes).</p> + +<p>If you properly design your activity to handle a restart due to a screen orientation change and +restore the activity state as described above, your application will be more resilient to other +unexpected events in the activity lifecycle.</p> -<p>The best way to handle a configuration change, such as a change in the screen orientation, is - to simply preserve the state of your application using {@link +<p>The best way to handle such a restart is + to save and restore the state of your activity using {@link android.app.Activity#onSaveInstanceState onSaveInstanceState()} and {@link android.app.Activity#onRestoreInstanceState onRestoreInstanceState()} (or {@link android.app.Activity#onCreate onCreate()}), as discussed in the previous section.</p> -<p>For a detailed discussion about configuration changes that happen at runtime and how you should -handle them, read <a href="{@docRoot}guide/topics/resources/runtime-changes.html">Handling +<p>For more information about configuration changes that happen at runtime and how you can handle +them, read the guide to <a href="{@docRoot}guide/topics/resources/runtime-changes.html">Handling Runtime Changes</a>.</p> diff --git a/docs/html/guide/topics/fundamentals/fragments.jd b/docs/html/guide/topics/fundamentals/fragments.jd index d6ba646..e0740aa 100644 --- a/docs/html/guide/topics/fundamentals/fragments.jd +++ b/docs/html/guide/topics/fundamentals/fragments.jd @@ -33,7 +33,7 @@ parent.link=activities.html </li> <li><a href="#Lifecycle">Handling the Fragment Lifecycle</a> <ol> - <li><a href="#CoordinadingWithActivity">Coordinating with the activity lifecycle</a></li> + <li><a href="#CoordinatingWithActivity">Coordinating with the activity lifecycle</a></li> </ol> </li> <li><a href="#Example">Example</a></li> @@ -78,7 +78,7 @@ manipulate each fragment independently, such as add or remove them. When you per fragment transaction, you can also add it to a back stack that's managed by the activity—each back stack entry in the activity is a record of the fragment transaction that occurred. The back stack allows the user to reverse a fragment transaction (navigate backwards), -by pressing the BACK button.</p> +by pressing the <em>Back</em> button.</p> <p>When you add a fragment as a part of your activity layout, it lives in a {@link android.view.ViewGroup} inside the activity's view hierarchy and the fragment defines its own view @@ -129,7 +129,7 @@ handset design.</p> <p>For example—to continue with the news application example—the application can embed two fragments in <em>Activity A</em>, when running on a tablet-sized device. However, on a -handset-sized screen, there's not be enough room for both fragments, so <em>Activity A</em> includes +handset-sized screen, there's not enough room for both fragments, so <em>Activity A</em> includes only the fragment for the list of articles, and when the user selects an article, it starts <em>Activity B</em>, which includes the second fragment to read the article. Thus, the application supports both tablets and handsets by reusing fragments in different combinations, as illustrated in @@ -143,7 +143,7 @@ href="{@docRoot}guide/practices/tablets-and-handsets.html">Supporting Tablets an <h2 id="Creating">Creating a Fragment</h2> -<div class="figure" style="width:314px"> +<div class="figure" style="width:327px"> <img src="{@docRoot}images/fragment_lifecycle.png" alt="" /> <p class="img-caption"><strong>Figure 2.</strong> The lifecycle of a fragment (while its activity is running).</p> @@ -398,7 +398,7 @@ android.app.FragmentManager#findFragmentById findFragmentById()} (for fragments the activity layout) or {@link android.app.FragmentManager#findFragmentByTag findFragmentByTag()} (for fragments that do or don't provide a UI).</li> <li>Pop fragments off the back stack, with {@link -android.app.FragmentManager#popBackStack()} (simulating a BACK command by the user).</li> +android.app.FragmentManager#popBackStack()} (simulating a <em>Back</em> command by the user).</li> <li>Register a listener for changes to the back stack, with {@link android.app.FragmentManager#addOnBackStackChangedListener addOnBackStackChangedListener()}.</li> </ul> @@ -439,7 +439,7 @@ to the activity, you must call {@link android.app.FragmentTransaction#commit()}. android.app.FragmentTransaction#commit()}, however, you might want to call {@link android.app.FragmentTransaction#addToBackStack addToBackStack()}, in order to add the transaction to a back stack of fragment transactions. This back stack is managed by the activity and allows -the user to return to the previous fragment state, by pressing the BACK key.</p> +the user to return to the previous fragment state, by pressing the <em>Back</em> button.</p> <p>For example, here's how you can replace one fragment with another, and preserve the previous state in the back stack:</p> @@ -462,14 +462,14 @@ transaction.commit(); layout container identified by the {@code R.id.fragment_container} ID. By calling {@link android.app.FragmentTransaction#addToBackStack addToBackStack()}, the replace transaction is saved to the back stack so the user can reverse the transaction and bring back the -previous fragment by pressing the BACK key.</p> +previous fragment by pressing the <em>Back</em> button.</p> <p>If you add multiple changes to the transaction (such as another {@link android.app.FragmentTransaction#add add()} or {@link android.app.FragmentTransaction#remove remove()}) and call {@link android.app.FragmentTransaction#addToBackStack addToBackStack()}, then all changes applied before you call {@link android.app.FragmentTransaction#commit commit()} are added to the -back stack as a single transaction and the BACK key will reverse them all together.</p> +back stack as a single transaction and the <em>Back</em> button will reverse them all together.</p> <p>The order in which you add changes to a {@link android.app.FragmentTransaction} doesn't matter, except:</p> @@ -657,7 +657,7 @@ href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a> developer guides. <h2 id="Lifecycle">Handling the Fragment Lifecycle</h2> -<div class="figure" style="width:403px"> +<div class="figure" style="width:350px"> <img src="{@docRoot}images/activity_fragment_lifecycle.png" alt=""/> <p class="img-caption"><strong>Figure 3.</strong> The activity lifecycle's affect on the fragment lifecycle.</p> @@ -696,7 +696,7 @@ document.</p> <p>The most significant difference in lifecycle between an activity and a fragment is how one is stored in its respective back stack. An activity is placed into a back stack of activities that's managed by the system when it's stopped, by default (so that the user can navigate back -to it with the BACK key, as discussed in <a +to it with the <em>Back</em> button, as discussed in <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back Stack</a>). However, a fragment is placed into a back stack managed by the host activity only when you explicitly request that the instance be saved by calling {@link diff --git a/docs/html/guide/topics/fundamentals/loaders.jd b/docs/html/guide/topics/fundamentals/loaders.jd index 3aad204..ddd513b 100644 --- a/docs/html/guide/topics/fundamentals/loaders.jd +++ b/docs/html/guide/topics/fundamentals/loaders.jd @@ -491,7 +491,7 @@ href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/Load LoaderCursor</a> — A complete version of the snippet shown above.</li> <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/LoaderThrottle.html"> LoaderThrottle</a> — An example of how to use throttling to -reduce the number of queries a content provider does then its data changes.</li> +reduce the number of queries a content provider does when its data changes.</li> </ul> <p>For information on downloading and installing the SDK samples, see <a diff --git a/docs/html/guide/topics/fundamentals/tasks-and-back-stack.jd b/docs/html/guide/topics/fundamentals/tasks-and-back-stack.jd index 216420c..0880614 100644 --- a/docs/html/guide/topics/fundamentals/tasks-and-back-stack.jd +++ b/docs/html/guide/topics/fundamentals/tasks-and-back-stack.jd @@ -34,7 +34,9 @@ to perform other tasks without losing their work</li> <h2>See also</h2> <ol> - <li><a><a href="{@docRoot}videos/index.html#v=fL6gSd4ugSI">Application Lifecycle video</a></li> + <li><a href="{@docRoot}design/patterns/navigation.html">Android Design: +Navigation</a></li> + <li><a href="{@docRoot}videos/index.html#v=fL6gSd4ugSI">Application Lifecycle video</a></li> <li><a href="{@docRoot}guide/topics/manifest/activity-element.html">{@code <activity>} manifest element</a></li> @@ -72,7 +74,7 @@ order in which each activity is opened.</p> suppose you have a two-pane layout using fragments, one of which is a list view (fragment A) and the other being a layout to display an item from the list (fragment B). When the user selects an item from the list, fragment B is replaced by a new fragment (fragment C). In this case, it might be -desireable for the user to navigate back to reveal fragment B, using the BACK key.</p> +desireable for the user to navigate back to reveal fragment B, using the <em>Back</em> button.</p> <p>In order to add fragment B to the back stack so that this is possible, you must call {@link android.app.FragmentTransaction#addToBackStack addToBackStack()} before you {@link android.app.FragmentTransaction#commit()} the transaction that replaces fragment B with fragment @@ -92,41 +94,47 @@ is created and the "main" activity for that application opens as the root activi <p>When the current activity starts another, the new activity is pushed on the top of the stack and takes focus. The previous activity remains in the stack, but is stopped. When an activity -stops, the system retains the current state of its user interface. When the user presses the BACK -key, the current activity is popped from the top of the stack (the activity is destroyed) and the +stops, the system retains the current state of its user interface. When the user presses the +<em>Back</em> +button, the current activity is popped from the top of the stack (the activity is destroyed) and the previous activity resumes (the previous state of its UI is restored). Activities in the stack are never rearranged, only pushed and popped from the stack—pushed onto the stack when started by -the current activity and popped off when the user leaves it using the BACK key. As such, the back +the current activity and popped off when the user leaves it using the <em>Back</em> button. As such, +the back stack operates as a "last in, first out" object structure. Figure 1 visualizes this behavior with a timeline showing the progress between activities along with the current back stack at each point in time.</p> <img src="{@docRoot}images/fundamentals/diagram_backstack.png" alt="" /> <p class="img-caption"><strong>Figure 1.</strong> A representation of how each new activity in a -task adds an item to the back stack. When the user presses the BACK key, the current activity is +task adds an item to the back stack. When the user presses the <em>Back</em> button, the current +activity is destroyed and the previous activity resumes.</p> -<p>If the user continues to press BACK, then each activity in the stack is popped off to reveal the +<p>If the user continues to press <em>Back</em>, then each activity in the stack is popped off to +reveal the previous one, until the user returns to the Home screen (or to whichever activity was running when the task began). When all activities are removed from the stack, the task no longer exists.</p> -<div class="figure" style="width:369px"> +<div class="figure" style="width:287px"> <img src="{@docRoot}images/fundamentals/diagram_multitasking.png" alt="" /> <p -class="img-caption"><strong>Figure 2.</strong> Two tasks: Task A is in the background, waiting -to be resumed, while Task B receives user interaction in the foreground.</p> +class="img-caption"><strong>Figure 2.</strong> Two tasks: Task B receives user interaction +in the foreground, while Task A is in the background, waiting to be resumed.</p> </div> -<div class="figure" style="width:178px"> +<div class="figure" style="width:215px"> <img src="{@docRoot}images/fundamentals/diagram_multiple_instances.png" alt="" /> <p class="img-caption"><strong>Figure 3.</strong> A single activity is instantiated multiple times.</p> </div> <p>A task is a cohesive unit that can move to the "background" when users begin a new task or go -to the Home screen, via the HOME key. While in the background, all the activities in the task are +to the Home screen, via the <em>Home</em> button. While in the background, all the activities in the +task are stopped, but the back stack for the task remains intact—the task has simply lost focus while another task takes place, as shown in figure 2. A task can then return to the "foreground" so users can pick up where they left off. Suppose, for example, that the current task (Task A) has three -activities in its stack—two under the current activity. The user presses the HOME key, then +activities in its stack—two under the current activity. The user presses the <em>Home</em> +button, then starts a new application from the application launcher. When the Home screen appears, Task A goes into the background. When the new application starts, the system starts a task for that application (Task B) with its own stack of activities. After interacting with @@ -135,7 +143,8 @@ started Task A. Now, Task A comes to the foreground—all three activities in its stack are intact and the activity at the top of the stack resumes. At this point, the user can also switch back to Task B by going Home and selecting the application icon -that started that task (or by touching and holding the HOME key to reveal recent tasks and selecting +that started that task (or by touching and holding the <em>Home</em> button to reveal recent tasks +and selecting one). This is an example of multitasking on Android.</p> <p class="note"><strong>Note:</strong> Multiple tasks can be held in the background at once. @@ -145,10 +154,11 @@ See the following section about <a href="#ActivityState">Activity state</a>.</p> <p>Because the activities in the back stack are never rearranged, if your application allows users to start a particular activity from more than one activity, a new instance of -that activity is created and popped onto the stack (rather than bringing any previous instance of +that activity is created and pushed onto the stack (rather than bringing any previous instance of the activity to the top). As such, one activity in your application might be instantiated multiple times (even from different tasks), as shown in figure 3. As such, if the user navigates backward -using the BACK key, each instance of the activity is revealed in the order they were opened (each +using the <em>Back</em> button, each instance of the activity is revealed in the order they were +opened (each with their own UI state). However, you can modify this behavior if you do not want an activity to be instantiated more than once. How to do so is discussed in the later section about <a href="#ManagingTasks">Managing Tasks</a>.</p> @@ -159,19 +169,28 @@ href="#ManagingTasks">Managing Tasks</a>.</p> <ul> <li>When Activity A starts Activity B, Activity A is stopped, but the system retains its state (such as scroll position and text entered into forms). -If the user presses the BACK key while in Activity B, Activity A resumes with its state +If the user presses the <em>Back</em> button while in Activity B, Activity A resumes with its state restored.</li> - <li>When the user leaves a task by pressing the HOME key, the current activity is stopped and + <li>When the user leaves a task by pressing the <em>Home</em> button, the current activity is +stopped and its task goes into the background. The system retains the state of every activity in the task. If the user later resumes the task by selecting the launcher icon that began the task, the task comes to the foreground and resumes the activity at the top of the stack.</li> - <li>If the user presses the BACK key, the current activity is popped from the stack and + <li>If the user presses the <em>Back</em> button, the current activity is popped from the stack +and destroyed. The previous activity in the stack is resumed. When an activity is destroyed, the system <em>does not</em> retain the activity's state.</li> <li>Activities can be instantiated multiple times, even from other tasks.</li> </ul> +<div class="design-announce"> +<p><strong>Navigation Design</strong></p> + <p>For more about how app navigation works on Android, read Android Design's <a +href="{@docRoot}design/patterns/navigation.html">Navigation</a> guide.</p> +</div> + + <h2 id="ActivityState">Saving Activity State</h2> <p>As discussed above, the system's default behavior preserves the state of an activity when it is @@ -247,7 +266,8 @@ flags to define how activities are associated with tasks and how the behave in t <p class="caution"><strong>Caution:</strong> Most applications should not interrupt the default behavior for activities and tasks. If you determine that it's necessary for your activity to modify the default behaviors, use caution and be sure to test the usability of the activity during -launch and when navigating back to it from other activities and tasks with the BACK key. Be sure +launch and when navigating back to it from other activities and tasks with the <em>Back</em> button. +Be sure to test for navigation behaviors that might conflict with the user's expected behavior.</p> @@ -271,7 +291,7 @@ B should associate with current task. If both activities define how Activity B should associate with a task, then Activity A's request (as defined in the intent) is honored over Activity B's request (as defined in its manifest).</p> -<p class="note"><strong>Note:</strong> Some the launch modes available in the manifest +<p class="note"><strong>Note:</strong> Some launch modes available for the manifest file are not available as flags for an intent and, likewise, some launch modes available as flags for an intent cannot be defined in the manifest.</p> @@ -311,8 +331,10 @@ android.app.Activity#onNewIntent onNewIntent()}, because it's at the top of the stack remains A-B-C-D. However, if an intent arrives for an activity of type B, then a new instance of B is added to the stack, even if its launch mode is {@code "singleTop"}.</p> <p class="note"><strong>Note:</strong> When a new instance of an activity is created, -the user can press the BACK key to return to the previous activity. But when an existing instance of -an activity handles a new intent, the user cannot press the BACK key to return to the state of +the user can press the <em>Back</em> button to return to the previous activity. But when an existing +instance of +an activity handles a new intent, the user cannot press the <em>Back</em> button to return to the +state of the activity before the new intent arrived in {@link android.app.Activity#onNewIntent onNewIntent()}.</p> </dd> @@ -324,7 +346,7 @@ intent to the existing instance through a call to its {@link android.app.Activity#onNewIntent onNewIntent()} method, rather than creating a new instance. Only one instance of the activity can exist at a time. <p class="note"><strong>Note:</strong> Although the activity starts in a new task, the -BACK key still returns the user to the previous activity.</p></dd> +<em>Back</em> button still returns the user to the previous activity.</p></dd> <dt>{@code "singleInstance"}.</dt> <dd>Same as {@code "singleTask"}, except that the system doesn't launch any other activities into the task holding the instance. The activity is always the single and only member of its task; @@ -342,19 +364,17 @@ already has a task running in the background, that task is brought forward to ha intent.</p> <p>Regardless of whether an activity starts in a new task or in the same task as the activity that -started it, the BACK key always takes the user to the previous activity. However, if you -start an activity from your task (Task A) that specifies the {@code singleTask} launch mode, then -that activity might have an instance in the background that belongs to a task with its own back -stack (Task B). In this -case, when Task B is brought forward to handle a new intent, the BACK key first navigates -backward through the activities in Task B before returning to -the top-most activity in Task A. Figure 4 visualizes this type of scenario.</p> +started it, the <em>Back</em> button always takes the user to the previous activity. However, if you +start an activity that specifies the {@code singleTask} launch mode, then if an instance of +that activity exists in a background task, that whole task is brought to the foreground. At this +point, the back stack now includes all activities from the task brought forward, at the top of the +stack. Figure 4 illustrates this type of scenario.</p> <img src="{@docRoot}images/fundamentals/diagram_backstack_singletask_multiactivity.png" alt="" /> <p class="img-caption"><strong>Figure 4.</strong> A representation of how an activity with launch mode "singleTask" is added to the back stack. If the activity is already a part of a -background task with its own back stack (Task B), then the entire back stack also comes -forward, on top of the current task (Task A).</p> +background task with its own back stack, then the entire back stack also comes +forward, on top of the current task.</p> <p>For more information about using launch modes in the manifest file, see the <code><a href="{@docRoot}guide/topics/manifest/activity-element.html"><activity></a></code> @@ -447,7 +467,8 @@ flag, the system looks for a different task to house the new activity. Often, it However, it doesn't have to be. If there's already an existing task with the same affinity as the new activity, the activity is launched into that task. If not, it begins a new task.</p> -<p>If this flag causes an activity to begin a new task and the user presses the HOME key to leave +<p>If this flag causes an activity to begin a new task and the user presses the <em>Home</em> button +to leave it, there must be some way for the user to navigate back to the task. Some entities (such as the notification manager) always start activities in an external task, never as part of their own, so they always put {@code FLAG_ACTIVITY_NEW_TASK} in the intents they pass to {@link @@ -549,9 +570,10 @@ android.content.Intent#ACTION_MAIN} and a {@link android.content.Intent#CATEGORY_LAUNCHER} filter. Imagine, for example, what could happen if the filter is missing: An intent launches a {@code "singleTask"} activity, initiating a new task, and the user spends some time working in -that task. The user then presses the HOME key. The task is now sent to the background and not -visible. Because it is not represented in the application launcher, the user has no way to return to -the task. +that task. The user then presses the <em>Home</em> button. The task is now sent to the background +and is +not visible. Now the user has no way to return to the task, because it is not represented in the +application launcher. </p> <p>For those cases where you don't want the user to be able to return to an activity, set the diff --git a/docs/html/guide/topics/graphics/hardware-accel.jd b/docs/html/guide/topics/graphics/hardware-accel.jd index c8703a5..f5cd1e6 100644 --- a/docs/html/guide/topics/graphics/hardware-accel.jd +++ b/docs/html/guide/topics/graphics/hardware-accel.jd @@ -42,19 +42,20 @@ parent.link=index.html <li><a href="{@docRoot}guide/topics/graphics/opengl.html">OpenGL with the Framework APIs</a></li> - <li><a href="{@docRoot}guide/topics/renderscript/index.html">RenderScript</a></li> + <li><a href="{@docRoot}guide/topics/renderscript/index.html">Renderscript</a></li> </ol> </div> </div> <p>Beginning in Android 3.0 (API level 11), the Android 2D rendering pipeline is designed to better support hardware acceleration. Hardware acceleration carries out all drawing operations - that are performed on a {@link android.view.View}'s canvas using the GPU.</p> + that are performed on a {@link android.view.View}'s canvas using the GPU. Because of the + increased resources required to enable hardware acceleration, your app will consume more RAM.</p> <p>The easiest way to enable hardware acceleration is to turn it on globally for your entire application. If your application uses only standard views and {@link android.graphics.drawable.Drawable}s, turning it on globally should not cause any adverse - effects. However, because hardware acceleration is not supported for all of the 2D drawing + drawing effects. However, because hardware acceleration is not supported for all of the 2D drawing operations, turning it on might affect some of your applications that use custom views or drawing calls. Problems usually manifest themselves as invisible elements, exceptions, or wrongly rendered pixels. To remedy this, Android gives you the option to enable or disable hardware diff --git a/docs/html/guide/topics/graphics/opengl.jd b/docs/html/guide/topics/graphics/opengl.jd index 6a2a20f..a786d42 100644 --- a/docs/html/guide/topics/graphics/opengl.jd +++ b/docs/html/guide/topics/graphics/opengl.jd @@ -189,7 +189,7 @@ shown below. <uses-feature android:glEsVersion="0x00020000" android:required="true" /> </pre> - <p>Adding this declaration causes the Android Market to restrict your application from being + <p>Adding this declaration causes Google Play to restrict your application from being installed on devices that do not support OpenGL ES 2.0.</p> </li> <li><strong>Texture compression requirements</strong> - If your application uses texture @@ -200,9 +200,9 @@ formats, see <a href="#textures">Texture compression support</a>. <p>Declaring texture compression requirements in your manifest hides your application from users with devices that do not support at least one of your declared compression types. For more -information on how Android Market filtering works for texture compressions, see the <a +information on how Google Play filtering works for texture compressions, see the <a href="{@docRoot}guide/topics/manifest/supports-gl-texture-element.html#market-texture-filtering"> -Android Market and texture compression filtering</a> section of the {@code +Google Play and texture compression filtering</a> section of the {@code <supports-gl-texture>} documentation.</p> </li> </ul> @@ -470,7 +470,7 @@ the next section. <p class="note"><strong>Note:</strong> Once you decide which texture compression formats your application will support, make sure you declare them in your manifest using <a href="{@docRoot}guide/topics/manifest/supports-gl-texture-element.html"><supports-gl-texture> -</a>. Using this declaration enables filtering by external services such as Android Market, so that +</a>. Using this declaration enables filtering by external services such as Google Play, so that your app is installed only on devices that support the formats your app requires. For details, see <a href="{@docRoot}guide/topics/graphics/opengl.html#manifest">OpenGL manifest declarations</a>.</p> diff --git a/docs/html/guide/topics/intents/intents-filters.jd b/docs/html/guide/topics/intents/intents-filters.jd index 3f94553..3ad3c93 100644 --- a/docs/html/guide/topics/intents/intents-filters.jd +++ b/docs/html/guide/topics/intents/intents-filters.jd @@ -247,7 +247,7 @@ several category constants, including these: </tr><tr> <td>{@code CATEGORY_HOME} <td>The activity displays the home screen, the first screen the user sees when - the device is turned on or when the HOME key is pressed. + the device is turned on or when the <em>Home</em> button is pressed. </tr><tr> <td>{@code CATEGORY_LAUNCHER} <td>The activity can be the initial activity of a task and is listed in diff --git a/docs/html/guide/topics/location/index.jd b/docs/html/guide/topics/location/index.jd index 5f98902..8a2e9cd 100644 --- a/docs/html/guide/topics/location/index.jd +++ b/docs/html/guide/topics/location/index.jd @@ -98,7 +98,7 @@ Google APIs add-on, visit</p> 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 available as a downloadable component from -the Android SDK and AVD Manager (see <a href="{@docRoot}sdk/adding-components.html">Adding SDK +the Android SDK Manager (see <a href="{@docRoot}sdk/adding-components.html">Adding SDK Components</a>).</p> <p class="note"><strong>Note:</strong> In order to display Google Maps data in a diff --git a/docs/html/guide/topics/manifest/activity-element.jd b/docs/html/guide/topics/manifest/activity-element.jd index e23fb0ec..9dc124b 100644 --- a/docs/html/guide/topics/manifest/activity-element.jd +++ b/docs/html/guide/topics/manifest/activity-element.jd @@ -59,7 +59,7 @@ by the system and will never be run. <dt>attributes:</dt> <dd><dl class="attr"> -<dt><a href name="reparent"></a>{@code android:allowTaskReparenting}</dt> +<dt><a name="reparent"></a>{@code android:allowTaskReparenting}</dt> <dd>Whether or not the activity can move from the task that started it to the task it has an affinity for when that task is next brought to the front — "{@code true}" if it can move, and "{@code false}" if it @@ -133,21 +133,21 @@ is meaningful only for activities that start a new task (the root activity); it's ignored for all other activities in the task. <p> -When the value is "{@code true}", every time users start the task again, they -are brought to its root activity, regardless of what they were last doing in -the task and regardless of whether they used BACK or HOME to last leave it. -When the value is "{@code false}", the task may be cleared of activities in +When the value is "{@code true}", every time users start the task again, they +are brought to its root activity regardless of what they were last doing in +the task and regardless of whether they used the <em>Back</em> or <em>Home</em> button to +leave it. When the value is "{@code false}", the task may be cleared of activities in some situations (see the <code><a href="#always">alwaysRetainTaskState</a></code> attribute), but not always. </p> <p> Suppose, for example, that someone launches activity P from the home screen, -and from there goes to activity Q. The user next presses HOME, and then returns +and from there goes to activity Q. The user next presses <em>Home</em>, and then returns to activity P. Normally, the user would see activity Q, since that is what they were last doing in P's task. However, if P set this flag to "{@code true}", all of the activities on top of it (Q in this case) were removed when the user pressed -HOME and the task went to the background. So the user sees only P when returning +<em>Home</em> and the task went to the background. So the user sees only P when returning to the task. </p> @@ -272,10 +272,11 @@ is "{@code false}", it cannot be instantiated. </p></dd> <dt><a name="exclude"></a>{@code android:excludeFromRecents}</dt> -<dd>Whether or not the activity should be excluded from the list of recently -launched activities that can be displayed to users — "{@code true}" if -it should be excluded, and "{@code false}" if it should be included. -The default value is "{@code false}". +<dd>Whether or not the task initiated by this activity should be excluded from the list of recently +used applications ("recent apps"). That is, when this activity is the root activity of a new task, +this attribute determines whether the task should not appear in the list of recent apps. "{@code +true}" if the task should be <em>excluded</em> from the list; "{@code false}" if it should be +<em>included</em>. The default value is "{@code false}". </p></dd> <dt><a name="exported"></a>{@code android:exported}</dt> @@ -306,7 +307,7 @@ attribute). <dd>Whether or not an existing instance of the activity should be shut down (finished) whenever the user again launches its task (chooses the task on the home screen) — "{@code true}" if it should be shut down, and "{@code false}" -if not. The default value is "{@code false}". +if not. The default value is "{@code false}". <p> If this attribute and @@ -320,13 +321,15 @@ activity is ignored. The activity is not re-parented, but destroyed. Activity — "{@code true}" if it should be enabled, and "{@code false}" if not. The default value is "{@code false}". + <p>Starting from Android 3.0, a hardware-accelerated OpenGL renderer is available to applications, to improve performance for many common 2D graphics operations. When the hardware-accelerated renderer is enabled, most operations in Canvas, Paint, Xfermode, ColorFilter, Shader, and Camera are accelerated. This results in smoother animations, smoother scrolling, and improved responsiveness overall, even for applications that do not explicitly make use -the framework's OpenGL libraries. </p> +the framework's OpenGL libraries. Because of the increased resources required to +enable hardware acceleration, your app will consume more RAM.</p> <p>Note that not all of the OpenGL 2D operations are accelerated. If you enable the hardware-accelerated renderer, test your application to ensure that it can @@ -501,7 +504,7 @@ users and is very different from most other applications. <p>Regardless of the launch mode that you choose, make sure to test the usability of the activity during launch and when navigating back to it from -other activities and tasks using the BACK key. </p> +other activities and tasks using the <em>Back</em> button. </p> <p>For more information on launch modes and their interaction with Intent flags, see the @@ -586,9 +589,9 @@ Permissions</a>. </p></dd> <dt><a name="proc"></a>{@code android:process}</dt> -<dd>The name of the process in which the activity should run. Normally, +<dd>The name of the process in which the activity should run. Normally, all components of an application run in the default process created for the -application. It has the same name as the application package. The <code><a href="{@docRoot}guide/topics/manifest/application-element.html"><application></a></code> element's +application. It has the same name as the application package. The <code><a href="{@docRoot}guide/topics/manifest/application-element.html"><application></a></code> element's <code><a href="{@docRoot}guide/topics/manifest/application-element.html#proc">process</a></code> attribute can set a different default for all components. But each component can override the default, allowing you to spread your application across @@ -669,7 +672,7 @@ unspecified}" setting.</td> <p class="note"><strong>Note:</strong> When you declare one of the landscape or portrait values, it is considered a hard requirement for the orientation in which the activity runs. As such, -the value you declare enables filtering by services such as Android Market so your application is +the value you declare enables filtering by services such as Google Play so your application is available only to devices that support the orientation required by your activities. For example, if you declare either {@code "landscape"}, {@code "reverseLandscape"}, or {@code "sensorLandscape"}, then your application will be available only to devices that support @@ -678,7 +681,7 @@ your application requires either portrait or landscape orientation with the <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html">{@code <uses-feature>}</a> element. For example, <code><uses-feature android:name="android.hardware.screen.portrait"/></code>. This is purely a filtering behavior -provided by Android Market (and other services that support it) and the platform itself does not +provided by Google Play (and other services that support it) and the platform itself does not control whether your app can be installed when a device supports only certain orientations.</p> </dd> @@ -705,7 +708,7 @@ activity started for the first time. A "{@code true}" setting ensures that the activity can be restarted in the absence of retained state. For example, the activity that displays the home screen uses this setting to make sure that it does not get removed if it -crashes for some reason. +crashes for some reason. </p></dd> <dt><a name="aff"></a>{@code android:taskAffinity}</dt> diff --git a/docs/html/guide/topics/manifest/application-element.jd b/docs/html/guide/topics/manifest/application-element.jd index 4f1964c..df6f61a 100644 --- a/docs/html/guide/topics/manifest/application-element.jd +++ b/docs/html/guide/topics/manifest/application-element.jd @@ -249,7 +249,7 @@ of that name is created. A global process can be shared with other applications, reducing resource usage. </p></dd> -<dt><a href name="restoreany"></a>{@code android:restoreAnyVersion}</dt> +<dt><a name="restoreany"></a>{@code android:restoreAnyVersion}</dt> <dd>Indicate that the application is prepared to attempt a restore of any backed-up data set, even if the backup was stored by a newer version of the application than is currently installed on the device. Setting @@ -260,7 +260,7 @@ incompatible. <em>Use with caution!</em> <p>The default value of this attribute is {@code false}. </p></dd> -<dt><a href name="aff"></a>{@code android:taskAffinity}</dt> +<dt><a name="aff"></a>{@code android:taskAffinity}</dt> <dd>An affinity name that applies to all activities within the application, except for those that set a different affinity with their own <code><a href="{@docRoot}guide/topics/manifest/activity-element.html#aff">taskAffinity</a></code> diff --git a/docs/html/guide/topics/manifest/compatible-screens-element.jd b/docs/html/guide/topics/manifest/compatible-screens-element.jd index 5c89869..a27c316 100644 --- a/docs/html/guide/topics/manifest/compatible-screens-element.jd +++ b/docs/html/guide/topics/manifest/compatible-screens-element.jd @@ -27,10 +27,10 @@ specifies a specific screen size-density combination with which the application <p>The Android system <em>does not</em> read the {@code <compatible-screens>} manifest element (neither at install-time nor at runtime). This element is informational only and may be used -by external services (such as Android Market) to better understand the application's compatibility +by external services (such as Google Play) to better understand the application's compatibility with specific screen configurations and enable filtering for users. Any screen configuration that is <em>not</em> declared in this element is a screen with which the application is <em>not</em> -compatible. Thus, external services (such as Android Market) should not provide the application to +compatible. Thus, external services (such as Google Play) should not provide the application to devices with such screens.</p> <p class="caution"><strong>Caution:</strong> Normally, <strong>you should not use this manifest @@ -48,14 +48,14 @@ should use the <a href="{@docRoot}guide/topics/manifest/supports-screens-element only for <em>large</em> and <em>xlarge</em> screen devices, the <a href="{@docRoot}guide/topics/manifest/supports-screens-element.html">{@code <supports-screens>}</a> element allows you to declare that your application does not -support <em>small</em> and <em>normal</em> screen sizes. External services (such as Android -Market) will filter your application accordingly. You can also use the <a +support <em>small</em> and <em>normal</em> screen sizes. External services (such as Google +Play) will filter your application accordingly. You can also use the <a href="{@docRoot}guide/topics/manifest/supports-screens-element.html">{@code <supports-screens>}</a> element to declare whether the system should resize your application for different screen sizes.</p> - <p>Also see the <a href="{@docRoot}guide/appendix/market-filters.html">Market Filters</a> -document for more information about how Android Market filters applications using this and + <p>Also see the <a href="{@docRoot}guide/appendix/market-filters.html">Filters on Google Play</a> +document for more information about how Google Play filters applications using this and other manifest elements.</p> </dd> @@ -138,5 +138,5 @@ entry looks like if your application is compatible with only small and normal sc <dt>see also:</dt> <dd><a href="{@docRoot}guide/practices/screens_support.html">Supporting Multiple Screens</a></dd> -<dd><a href="{@docRoot}guide/appendix/market-filters.html">Market Filters</a></dd> +<dd><a href="{@docRoot}guide/appendix/market-filters.html">Filters on Google Play</a></dd> </dl> diff --git a/docs/html/guide/topics/manifest/manifest-element.jd b/docs/html/guide/topics/manifest/manifest-element.jd index d737a67..98968d7 100644 --- a/docs/html/guide/topics/manifest/manifest-element.jd +++ b/docs/html/guide/topics/manifest/manifest-element.jd @@ -37,7 +37,7 @@ parent.link=manifest-intro.html <dt>description:</dt> <dd>The root element of the AndroidManifest.xml file. It must contain an <code><a href="{@docRoot}guide/topics/manifest/application-element.html"><application></a></code> element -and specify {@code xlmns:android} and {@code package} attributes.</dd> +and specify {@code xmlns:android} and {@code package} attributes.</dd> <dt>attributes:</dt> <dd> @@ -150,9 +150,9 @@ either internal or external storage through the system settings.</td> </tr> </table> -<p class="caution"><strong>Caution:</strong> If your application uses the Android Market's Copy - Protection feature, it cannot be installed to a device's SD card. However, if you use Android - Market's <a href="{@docRoot}guide/publishing/licensing.html">Application Licensing</a> instead, +<p class="caution"><strong>Caution:</strong> If your application uses Google Play's Copy + Protection feature, it cannot be installed to a device's SD card. However, if you use Google + Play's <a href="{@docRoot}guide/market/licensing.html">Application Licensing</a> instead, your application <em>can</em> be installed to internal or external storage, including SD cards.</p> <p class="note"><strong>Note:</strong> By default, your application will be installed on the diff --git a/docs/html/guide/topics/manifest/supports-gl-texture-element.jd b/docs/html/guide/topics/manifest/supports-gl-texture-element.jd index 6c4a05a..ebdd0b1 100644 --- a/docs/html/guide/topics/manifest/supports-gl-texture-element.jd +++ b/docs/html/guide/topics/manifest/supports-gl-texture-element.jd @@ -18,20 +18,20 @@ parent.link=manifest-intro.html <div class="sidebox-wrapper"> <img id="rule" src="{@docRoot}assets/images/grad-rule-qv.png"> <div id="qv-sub-rule"> - <img src="{@docRoot}assets/images/icon_market.jpg" + <img src="{@docRoot}assets/images/icon_play.png" style="float:left;margin:0;padding:0;"> - <p style="color:#669999;">Android Market and <code + <p style="color:#669999;padding-top:1em;">Google Play and <code style="color:#669999;"><supports-gl-texture></code> elements</p> - <p style="margin-top:1em;">Android Market filters applications according + <p style="margin-top:1em;">Google Play filters applications according to the texture compression formats that they support, to ensure that they can be installed only on devices that can handle their textures properly. Developers can use texture compression filtering as a way of targeting specific device types, based on GPU platform.</p> <p style="margin-top:1em;" class="caution">For important information about how - Android Market uses <code><supports-gl-texture></code> elements as - the basis for filtering, please read <a href="#market-texture-filtering">Android - Market and texture compression filtering</a>, below.</p> + Google Play uses <code><supports-gl-texture></code> elements as + the basis for filtering, please read <a href="#market-texture-filtering">Google + Play and texture compression filtering</a>, below.</p> </div> </div> @@ -57,7 +57,7 @@ texture compression formats, you can declare multiple <p>Declared <code><supports-gl-texture></code> elements are informational, meaning that the Android system itself does not examine the elements at install time to ensure matching support on the device. However, other services -(such as Android Market) or applications can check your application's +(such as Google Play) or applications can check your application's <code><supports-gl-texture></code> declarations as part of handling or interacting with your application. For this reason, it's very important that you declare all of the texture compression formats (from the list below) that @@ -141,20 +141,20 @@ and others.</td> <dt>see also:</dt> <dd> <ul> - <li><a href="{@docRoot}guide/appendix/market-filters.html">Android Market Filters</a></li> + <li><a href="{@docRoot}guide/appendix/market-filters.html">Filters on Google Play</a></li> </ul> </dd> -<h2 id="market-texture-filtering">Android Market and texture compression filtering</h2> +<h2 id="market-texture-filtering">Google Play and texture compression filtering</h2> -<p>Android Market filters the applications that are visible to users, so that +<p>Google Play filters the applications that are visible to users, so that users can see and download only those applications that are compatible with -their devices. One of the ways Market filters applications is by texture +their devices. One of the ways it filters applications is by texture compression compatibility, giving you control over the availability of your application to various devices, based on the capabilities of their GPUs.</p> <p>To determine an application's texture compression compatibility with a given -user's device, Android Market compares:</p> +user's device, Google Play compares:</p> <ul> <li>Texture compression formats that are supported by the application — @@ -164,26 +164,26 @@ an application declares its supported texture compression formats in a device reports the formats it supports as read-only system properties.</li> </ul> -<p>Each time you upload an application to the Android Market Publisher Site, -Android Market scans the application's manifest file and looks for any +<p>Each time you upload an application to the Google Play publisher site, +Google Play scans the application's manifest file and looks for any <code><supports-gl-texture></code> elements. It extracts the format descriptors from the elements and stores them internally as metadata associated with the application <code>.apk</code> and the application version. </p> -<p>When a user searches or browses for applications on Android Market, +<p>When a user searches or browses for applications on Google Play, the service compares the texture compression formats supported by the application with those supported by the user's device. The comparison is based on the format descriptor strings and a match must be exact.</p> <p>If <em>any</em> of an application's supported texture compression formats is -also supported by the device, Android Market allows the user to see the +also supported by the device, Google Play allows the user to see the application and potentially download it. Otherwise, if none of the application's -formats is supported by the device, Android Market filters the application so +formats is supported by the device, Google Play filters the application so that it is not available for download. </p> <p>If an application does not declare any <code><supports-gl-texture></code> elements, -Android Market does not apply any filtering based on GL texture compression format.</p> +Google Play does not apply any filtering based on GL texture compression format.</p> </dl> diff --git a/docs/html/guide/topics/manifest/supports-screens-element.jd b/docs/html/guide/topics/manifest/supports-screens-element.jd index 81d6e27..ae14121 100644 --- a/docs/html/guide/topics/manifest/supports-screens-element.jd +++ b/docs/html/guide/topics/manifest/supports-screens-element.jd @@ -80,7 +80,7 @@ should not use it.</p> A small screen is defined as one with a smaller aspect ratio than the "normal" (traditional HVGA) screen. An application that does not support small screens <em>will not be available</em> for - small screen devices from external services (such as Android Market), because there is little + small screen devices from external services (such as Google Play), because there is little the platform can do to make such an application work on a smaller screen. This is {@code "true"} by default. </dd> @@ -156,8 +156,8 @@ smallest screen width qualifier</a> ({@code sw<N>dp}).</p> <p class="caution"><strong>Caution:</strong> The Android system does not pay attention to this attribute, so it does not affect how your application behaves at runtime. Instead, it is used -to enable filtering for your application on services such as Android Market. However, -<strong>Android Market currently does not support this attribute for filtering</strong> (on Android +to enable filtering for your application on services such as Google Play. However, +<strong>Google Play currently does not support this attribute for filtering</strong> (on Android 3.2), so you should continue using the other size attributes if your application does not support small screens.</p> diff --git a/docs/html/guide/topics/manifest/uses-feature-element.jd b/docs/html/guide/topics/manifest/uses-feature-element.jd index 9f80638..5f0a501 100644 --- a/docs/html/guide/topics/manifest/uses-feature-element.jd +++ b/docs/html/guide/topics/manifest/uses-feature-element.jd @@ -9,7 +9,7 @@ parent.link=manifest-intro.html <h2>In this document</h2> <ol> - <li><a href="#market-feature-filtering">Android Market and Feature-Based Filtering</a> + <li><a href="#market-feature-filtering">Google Play and Feature-Based Filtering</a> <ol> <li><a href="#declared">Filtering based on explicitly declared features</a></li> <li><a href="#implicit">Filtering based on implicit features</a></li> @@ -45,26 +45,26 @@ href="{@docRoot}guide/topics/manifest/manifest-element.html"><manifest></a <div class="sidebox-wrapper"> <img id="rule" src="{@docRoot}assets/images/grad-rule-qv.png"> <div id="qv-sub-rule"> - <img src="{@docRoot}assets/images/icon_market.jpg" style="float:left;margin:0;padding:0;"> - <p style="color:#669999;">Android Market and <code style="color:#669999;"><uses-feature></code> elements</p> - <p style="margin-top:1em;">Android Market filters the applications that are visible to users, so + <img src="{@docRoot}assets/images/icon_play.png" style="float:left;margin:0;padding:0;"> + <p style="color:#669999;padding-top:1em;">Google Play and <code style="color:#669999;"><uses-feature></code> elements</p> + <p style="margin-top:1em;">Google Play filters the applications that are visible to users, so that users can see and download only those applications that are compatible with their -devices. One of the ways Market filters applications is by feature compatibility.</p> +devices. One of the ways it filters applications is by feature compatibility.</p> -<p style="margin-top:1em;">To do this, Market checks the +<p style="margin-top:1em;">To do this, Google Play checks the <code><uses-feature></code> elements in each application's manifest, to -establish the app's feature needs. Market then shows or hides the application to +establish the app's feature needs. Google Play then shows or hides the application to each user, based on a comparison with the features available on the user's device. </p> <p style="margin-top:1em;">By specifying the features that your application requires, -you enable Android Market to present your application only to users whose +you enable Google Play to present your application only to users whose devices meet the application's feature requirements, rather than presenting it to all users. </p> <p style="margin-top:1em;" class="caution">For important information about how -Android Market uses features as the basis for filtering, please read <a -href="#market-feature-filtering">Android Market and Feature-Based Filtering</a>, +Google Play uses features as the basis for filtering, please read <a +href="#market-feature-filtering">Google Play and Feature-Based Filtering</a>, below.</p> </div> </div> @@ -106,7 +106,7 @@ application requires.</p> <p>Declared <code><uses-feature></code> elements are informational only, meaning that the Android system itself does not check for matching feature support on the device before installing an application. However, other services -(such as Android Market) or applications may check your application's +(such as Google Play) or applications may check your application's <code><uses-feature></code> declarations as part of handling or interacting with your application. For this reason, it's very important that you declare all of the features (from the list below) that your application uses. </p> @@ -207,22 +207,22 @@ can check at run-time whether a higher level of OpenGL ES is available.)</p> <li>{@link android.content.pm.FeatureInfo}</li> <li>{@link android.content.pm.ConfigurationInfo}</li> <li><a href="{@docRoot}guide/topics/manifest/uses-permission-element.html"><code><uses-permission></code></a></li> - <li><a href="{@docRoot}guide/appendix/market-filters.html">Android Market Filters</a></li> + <li><a href="{@docRoot}guide/appendix/market-filters.html">Filters on Google Play</a></li> </ul> </dd> </dl> -<h2 id="market-feature-filtering">Android Market and Feature-Based Filtering</h2> +<h2 id="market-feature-filtering">Google Play and Feature-Based Filtering</h2> -<p>Android Market filters the applications that are visible to users, so that +<p>Google Play filters the applications that are visible to users, so that users can see and download only those applications that are compatible with -their devices. One of the ways Market filters applications is by feature +their devices. One of the ways it filters applications is by feature compatibility.</p> <p>To determine an application's feature compatibility with a given user's -device, the Android Market service compares:</p> +device, Google Play compares:</p> <ul> <li>Features required by the application — an application declares features in @@ -238,14 +238,14 @@ are listed in the <a href="#features-reference">Features Reference</a> tables at the bottom of this document, and in the class documentation for {@link android.content.pm.PackageManager}.</p> -<p>When the user launches the Market application, the application queries the +<p>When the user launches Google Play, the application queries the Package Manager for the list of features available on the device by calling {@link android.content.pm.PackageManager#getSystemAvailableFeatures()}. The -Market application then passes the features list up to the Android Market -service when establishing the session for the user.</p> +Store application then passes the features list up to Google Play +when establishing the session for the user.</p> -<p>Each time you upload an application to the Android Market Publisher Site, -Android Market scans the application's manifest file. It looks for +<p>Each time you upload an application to the Google Play publisher site, +Google Play scans the application's manifest file. It looks for <code><uses-feature></code> elements and evaluates them in combination with other elements, in some cases, such as <code><uses-sdk></code> and <code><uses-permission></code> elements. After establishing the @@ -253,17 +253,17 @@ application's set of required features, it stores that list internally as metadata associated with the application <code>.apk</code> and the application version. </p> -<p>When a user searches or browses for applications using the Android Market +<p>When a user searches or browses for applications using the Google Play application, the service compares the features needed by each application with the features available on the user's device. If all of an application's required -features are present on the device, Android Market allows the user to see the +features are present on the device, Google Play allows the user to see the application and potentially download it. If any required feature is not -supported by the device, Android Market filters the application so that it is +supported by the device, Google Play filters the application so that it is not visible to the user and not available for download. </p> <p>Because the features you declare in <code><uses-feature></code> -elements directly affect how Android Market filters your application, it's -important to understand how Android Market evaluates the application's manifest +elements directly affect how Google Play filters your application, it's +important to understand how Google Play evaluates the application's manifest and establishes the set of required features. The sections below provide more information. </p> @@ -277,35 +277,35 @@ application absolutely requires the feature and cannot function properly without it (<code>"true"</code>), or whether the application prefers to use the feature if available, but is designed to run without it (<code>"false"</code>).</p> -<p>Android Market handles explicitly declared features in this way: </p> +<p>Google Play handles explicitly declared features in this way: </p> <ul> -<li>If a feature is explicitly declared as being required, Android Market adds +<li>If a feature is explicitly declared as being required, Google Play adds the feature to the list of required features for the application. It then filters the application from users on devices that do not provide that feature. For example: <pre><uses-feature android:name="android.hardware.camera" android:required="true" /></pre></li> -<li>If a feature is explicitly declared as <em>not</em> being required, Android -Market <em>does not</em> add the feature to the list of required features. For +<li>If a feature is explicitly declared as <em>not</em> being required, Google +Play <em>does not</em> add the feature to the list of required features. For that reason, an explicitly declared non-required feature is never considered when filtering the application. Even if the device does not provide the declared -feature, Android Market will still consider the application compatible with the +feature, Google Play will still consider the application compatible with the device and will show it to the user, unless other filtering rules apply. For example: <pre><uses-feature android:name="android.hardware.camera" android:required="false" /></pre></li> <li>If a feature is explicitly declared, but without an -<code>android:required</code> attribute, Android Market assumes that the feature +<code>android:required</code> attribute, Google Play assumes that the feature is required and sets up filtering on it. </li> </ul> <p>In general, if your application is designed to run on Android 1.6 and earlier versions, the <code>android:required</code> attribute is not available in the -API and Android Market assumes that any and all +API and Google Play assumes that any and all <code><uses-feature></code> declarations are required. </p> <p class="note"><strong>Note:</strong> By declaring a feature explicitly and including an <code>android:required="false"</code> attribute, you can -effectively disable all filtering on Android Market for the specified feature. +effectively disable all filtering on Google Play for the specified feature. </p> @@ -317,7 +317,7 @@ function properly, but which is <em>not</em> declared in a speaking, every application should <em>always</em> declare all features that it uses or requires, so the absence of a declaration for a feature used by an application should be considered an error. However, as a safeguard for users and -developers, Android Market looks for implicit features in each application and +developers, Google Play looks for implicit features in each application and sets up filters for those features, just as it would do for an explicitly declared feature. </p> @@ -337,25 +337,25 @@ element name or an unrecognized string value for the </li> </ul> -<p>To account for the cases above, Android Market attempts to discover an +<p>To account for the cases above, Google Play attempts to discover an application's implied feature requirements by examining <em>other elements</em> declared in the manifest file, specifically, <code><uses-permission></code> elements.</p> -<p>If an application requests hardware-related permissions, Android Market +<p>If an application requests hardware-related permissions, Google Play <em>assumes that the application uses the underlying hardware features and therefore requires those features</em>, even though there might be no corresponding to <code><uses-feature></code> declarations. For such -permissions, Android Market adds the underlying hardware features to the +permissions, Google Play adds the underlying hardware features to the metadata that it stores for the application and sets up filters for them.</p> <p>For example, if an application requests the <code>CAMERA</code> permission but does not declare a <code><uses-feature></code> element for -<code>android.hardware.camera</code>, Android Market considers that the +<code>android.hardware.camera</code>, Google Play considers that the application requires a camera and should not be shown to users whose devices do not offer a camera.</p> -<p>If you don't want Android Market to filter based on a specific implied +<p>If you don't want Google Play to filter based on a specific implied feature, you can disable that behavior. To do so, declare the feature explicitly in a <code><uses-feature></code> element and include an <code>android:required="false"</code> attribute. For example, to disable @@ -366,30 +366,30 @@ the feature as shown below.</p> <p class="caution">It's important to understand that the permissions that you request in <code><uses-permission></code> elements can directly affect how -Android Market filters your application. The reference section <a +Google Play filters your application. The reference section <a href="#permissions">Permissions that Imply Feature Requirements</a>, below, lists the full set of permissions that imply feature requirements and therefore trigger filtering.</p> <h3 id="bt-permission-handling">Special handling for Bluetooth feature</h3> -<p>Android Market applies slightly different rules than described above, when +<p>Google Play applies slightly different rules than described above, when determining filtering for Bluetooth.</p> <p>If an application declares a Bluetooth permission in a <code><uses-permission></code> element, but does not explicitly declare -the Bluetooth feature in a <code><uses-feature></code> element, Android -Market checks the version(s) of the Android platform on which the application is +the Bluetooth feature in a <code><uses-feature></code> element, Google +Play checks the version(s) of the Android platform on which the application is designed to run, as specified in the <code><uses-sdk></code> element. </p> -<p>As shown in the table below, Android Market enables filtering for the +<p>As shown in the table below, Google Play enables filtering for the Bluetooth feature only if the application declares its lowest or targeted -platform as Android 2.0 (API level 5) or higher. However, note that Android -market applies the normal rules for filtering when the application explicitly +platform as Android 2.0 (API level 5) or higher. However, note that Google +Play applies the normal rules for filtering when the application explicitly declares the Bluetooth feature in a <code><uses-feature></code> element. </p> -<p class="caption"><strong>Table 1.</strong> How Android Market determines the +<p class="caption"><strong>Table 1.</strong> How Google Play determines the Bluetooth feature requirement for an application that requests a Bluetooth permission but does not declare the Bluetooth feature in a <code><uses-feature></code> element.</p> @@ -403,14 +403,14 @@ permission but does not declare the Bluetooth feature in a <tr> <td><nobr><=4 (or uses-sdk is not declared)</nobr></td> <td><=4</td> -<td>Android Market <em>will not</em> filter the application from any devices +<td>Google Play <em>will not</em> filter the application from any devices based on their reported support for the <code>android.hardware.bluetooth</code> feature.</td> </tr> <tr> <td><=4</td> <td>>=5</td> -<td rowspan="2">Android Market filters the application from any devices that +<td rowspan="2">Google Play filters the application from any devices that do not support the <code>android.hardware.bluetooth</code> feature (including older releases).</td> </tr> @@ -421,13 +421,13 @@ older releases).</td> </table> <p>The examples below illustrate the different filtering effects, based on how -Android Market handles the Bluetooth feature. </p> +Google Play handles the Bluetooth feature. </p> <dl> <dt>In first example, an application that is designed to run on older API levels declares a Bluetooth permission, but does not declare the Bluetooth feature in a <code><uses-feature></code> element.</dt> -<dd><em>Result:</em> Android Market does not filter the application from any device.</dd> +<dd><em>Result:</em> Google Play does not filter the application from any device.</dd> </dl> <pre><manifest ...> @@ -439,7 +439,7 @@ declares a Bluetooth permission, but does not declare the Bluetooth feature in a <dl> <dt>In the second example, below, the same application also declares a target API level of "5". </dt> -<dd><em>Result:</em> Android Market now assumes that the feature is required and +<dd><em>Result:</em> Google Play now assumes that the feature is required and will filter the application from all devices that do not report Bluetooth support, including devices running older versions of the platform. </dd> </dl> @@ -465,7 +465,7 @@ including devices running older versions of the platform. </dd> <dl> <dt>Finally, in the case below, the same application adds an <code>android:required="false"</code> attribute.</dt> -<dd><em>Result:</em> Android Market disables filtering based on Bluetooth +<dd><em>Result:</em> Google Play disables filtering based on Bluetooth feature support, for all devices.</dd> </dl> @@ -481,10 +481,10 @@ feature support, for all devices.</dd> <h3 id="testing">Testing the features required by your application</h3> <p>You can use the <code>aapt</code> tool, included in the Android SDK, to -determine how Android Market will filter your application, based on its declared +determine how Google Play will filter your application, based on its declared features and permissions. To do so, run <code>aapt</code> with the <code>dump badging</code> command. This causes <code>aapt</code> to parse your -application's manifest and apply the same rules as used by Android Market to +application's manifest and apply the same rules as used by Google Play to determine the features that your application requires. </p> <p>To use the tool, follow these steps: </p> @@ -501,7 +501,7 @@ If you are using SDK Tools r8 or higher, you can find <code>aapt</code> in the <p class="note"><strong>Note:</strong> You must use the version of <code>aapt</code> that is provided for the latest Platform-Tools component available. If you do not have the latest Platform-Tools component, download it using the <a -href="{@docRoot}sdk/adding-components.html">Android SDK and AVD Manager</a>. +href="{@docRoot}sdk/adding-components.html">Android SDK Manager</a>. </p></li> <li>Run <code>aapt</code> using this syntax: </li> </ol> @@ -529,7 +529,7 @@ densities: '160' <h2 id=features-reference>Features Reference</h2> <p>The tables below provide reference information about hardware and software -features and the permissions that can imply them on Android Market. </p> +features and the permissions that can imply them on Google Play. </p> <h3 id="hw-features">Hardware features</h3> @@ -873,12 +873,12 @@ level 5). Because of this, some apps were able to use the API before they had the ability to declare that they require the API via the <code><uses-feature></code> system. </p> -<p>To prevent those apps from being made available unintentionally, Android -Market assumes that certain hardware-related permissions indicate that the +<p>To prevent those apps from being made available unintentionally, Google +Play assumes that certain hardware-related permissions indicate that the underlying hardware features are required by default. For instance, applications that use Bluetooth must request the <code>BLUETOOTH</code> permission in a -<code><uses-permission></code> element — for legacy apps, Android -Market assumes that the permission declaration means that the underlying +<code><uses-permission></code> element — for legacy apps, Google +Play assumes that the permission declaration means that the underlying <code>android.hardware.bluetooth</code> feature is required by the application and sets up filtering based on that feature. </p> diff --git a/docs/html/guide/topics/manifest/uses-library-element.jd b/docs/html/guide/topics/manifest/uses-library-element.jd index d94ad9f..2f8eb50 100644 --- a/docs/html/guide/topics/manifest/uses-library-element.jd +++ b/docs/html/guide/topics/manifest/uses-library-element.jd @@ -33,7 +33,7 @@ parent.link=manifest-intro.html </p> <p> This element also affects the installation of the application on a particular device and - the availability of the application in Android Market: + the availability of the application on Google Play: </p> <dl> <dt><em>Installation</em></dt> @@ -42,11 +42,11 @@ parent.link=manifest-intro.html {@code true}, the {@link android.content.pm.PackageManager} framework won't let the user install the application unless the library is present on the user's device. </dd> - <dt><em>Market</em></dt> + <dt><em>Google Play</em></dt> <dd> - Android Market filters applications based on the libraries installed on the + Google Play filters applications based on the libraries installed on the user's device. For more information about filtering, see the topic - <a href="{@docRoot}guide/appendix/market-filters.html">Market Filters</a>. + <a href="{@docRoot}guide/appendix/market-filters.html">Filters on Google Play</a>. </dd> </dl> <p> diff --git a/docs/html/guide/topics/manifest/uses-permission-element.jd b/docs/html/guide/topics/manifest/uses-permission-element.jd index 967fc5a..6c71fb4 100644 --- a/docs/html/guide/topics/manifest/uses-permission-element.jd +++ b/docs/html/guide/topics/manifest/uses-permission-element.jd @@ -8,21 +8,21 @@ parent.link=manifest-intro.html <div class="sidebox-wrapper"> <img id="rule" src="{@docRoot}assets/images/grad-rule-qv.png"> <div id="qv-sub-rule"> - <img src="{@docRoot}assets/images/icon_market.jpg" style="float:left;margin:0;padding:0;"> - <p style="color:#669999;"><code style="color:#669999;"><uses-permission></code> and filtering on Android Market. </p> + <img src="{@docRoot}assets/images/icon_play.png" style="float:left;margin:0;padding:0;"> + <p style="color:#669999;padding-top:1em;"><code style="color:#669999;"><uses-permission></code> and filtering on Google Play. </p> <p style="margin-top:1em;">In some cases, the permissions that you request through <code><uses-permission></code> can affect how -your application is filtered by Android Market.</p> +your application is filtered by Google Play.</p> <p style="margin-top:1em;">If you request a hardware-related permission — -<code>CAMERA</code>, for example — Android Market assumes that your +<code>CAMERA</code>, for example — Google Play assumes that your application requires the underlying hardware feature and filters the application from devices that do not offer it.</p> <p style="margin-top:1em;">To control filtering, always explicitly declare hardware features in <code><uses-feature></code> elements, rather than -relying on Android Market to "discover" the requirements in +relying on Google Play to "discover" the requirements in <code><uses-permission></code> elements. Then, if you want to disable filtering for a particular feature, you can add a <code>android:required="false"</code> attribute to the diff --git a/docs/html/guide/topics/manifest/uses-sdk-element.jd b/docs/html/guide/topics/manifest/uses-sdk-element.jd index b371f34..8fa39d1 100644 --- a/docs/html/guide/topics/manifest/uses-sdk-element.jd +++ b/docs/html/guide/topics/manifest/uses-sdk-element.jd @@ -33,16 +33,16 @@ major version or the sum of the major and minor versions).</p> <div class="sidebox-wrapper" xstyle="margin-bottom:2em;margin-top:.5em;width:90%;"> <img id="rule" src="{@docRoot}assets/images/grad-rule-qv.png"> <div id="qv-sub-rule"> - <img src="{@docRoot}assets/images/icon_market.jpg" style="float:left;margin:0;padding:0;"> - <p style="color:#669999;">Android Market and <uses-sdk> attributes</p> - <p>Android Market filters the applications that are visible to users, so + <img src="{@docRoot}assets/images/icon_play.png" style="float:left;margin:0;padding:0;"> + <p style="color:#669999;padding-top:1em;">Google Play and <uses-sdk> attributes</p> + <p style="padding-top:1em;">Google Play filters the applications that are visible to users, so that users can only see and download applications that are compatible with their -devices. One of the ways Market filters applications is by Android -version-compatibility. To do this, Market checks the <code><uses-sdk></code> +devices. One of the ways it filters applications is by Android +version-compatibility. To do this, Google Play checks the <code><uses-sdk></code> attributes in each application's manifest to establish its version-compatibility range, then shows or hides the application based on a comparison with the API Level of the user's Android system version. For more information, see <a -href="{@docRoot}guide/appendix/market-filters.html">Market Filters</a>.</p> +href="{@docRoot}guide/appendix/market-filters.html">Filters on Google Play</a>.</p> </div> </div> @@ -60,7 +60,7 @@ href="{@docRoot}guide/appendix/market-filters.html">Market Filters</a>.</p> attribute, the system assumes a default value of "1", which indicates that your application is compatible with all versions of Android. If your application is <em>not</em> compatible with all versions (for instance, it uses APIs introduced - in API Level 3) and you have not declared the proper <code>android:minSdkVersion</code>, + in API Level 3) and you have not declared the proper <code>minSdkVersion</code>, then when installed on a system with an API Level less than 3, the application will crash during runtime when attempting to access the unavailable APIs. For this reason, be certain to declare the appropriate API Level in the @@ -68,18 +68,32 @@ href="{@docRoot}guide/appendix/market-filters.html">Market Filters</a>.</p> </dd> <dt><a name="target"></a>{@code android:targetSdkVersion}</dt> - <dd>An integer designating the API Level that the application is targetting. - - <p>With this attribute set, the application says that it is able to run on - older versions (down to {@code minSdkVersion}), but was explicitly tested to - work with the version specified here. Specifying this target version allows the - platform to disable compatibility settings that are not required for the target - version (which may otherwise be turned on in order to maintain - forward-compatibility) or enable newer features that are not available to older - applications. This does not mean that you can program different features for - different versions of the platform—it simply informs the platform that you - have tested against the target version and the platform should not perform any - extra work to maintain forward-compatibility with the target version.</p> + <dd>An integer designating the API Level that the application targets. If not set, the default +value equals that given to {@code minSdkVersion}. + + <p>This attribute informs the system that you have tested against the target version and the +system should not enable any compatibility behaviors to maintain your app's forward-compatibility +with the target version. The application is still able to run on older versions (down to {@code +minSdkVersion}).</p> + + <p>As Android evolves with each new version, some behaviors and even appearances might change. +However, if the API level of the platform is higher than the version declared by your app's {@code +targetSdkVersion}, the system may enable compatibility behaviors to ensure that your app +continues to work the way you expect. You can disable such compatibility +behaviors by specifying {@code targetSdkVersion} to match the API +level of the platform on which it's running. For example, setting this value to "11" or higher +allows the system to apply a new default theme (Holo) to your app when running on Android 3.0 or +higher and also disables <a href="{@docRoot}guide/practices/screen-compat-mode.html">screen +compatibility mode</a> when running on larger screens (because support for API level 11 implicitly +supports larger screens).</p> + + <p>There are many compatibility behaviors that the system may enable based on the value you set +for this attribute. Several of these behaviors are described by the corresponding platform versions +in the {@link android.os.Build.VERSION_CODES} reference.</p> + + <p>To maintain your application along with each Android release, you should increase +the value of this attribute to match the latest API level, then thoroughly test your application on +the corresponding platform version.</p> <p>Introduced in: API Level 4</p> </dd> @@ -89,25 +103,25 @@ href="{@docRoot}guide/appendix/market-filters.html">Market Filters</a>.</p> designed to run. <p>In Android 1.5, 1.6, 2.0, and 2.0.1, the system checks the value of this - attribute when installing an application and when revalidating the application + attribute when installing an application and when re-validating the application after a system update. In either case, if the application's - <code>android:maxSdkVersion</code> attribute is lower than the API Level used by + <code>maxSdkVersion</code> attribute is lower than the API Level used by the system itself, then the system will not allow the application to be - installed. In the case of revalidation after system update, this effectively + installed. In the case of re-validation after system update, this effectively removes your application from the device. <p>To illustrate how this attribute can affect your application after system updates, consider the following example: </p> - <p>An application declaring <code>android:maxSdkVersion="5"</code> in its - manifest is published on Android Market. A user whose device is running Android + <p>An application declaring <code>maxSdkVersion="5"</code> in its + manifest is published on Google Play. A user whose device is running Android 1.6 (API Level 4) downloads and installs the app. After a few weeks, the user receives an over-the-air system update to Android 2.0 (API Level 5). After the update is installed, the system checks the application's - <code>android:maxSdkVersion</code> and successfully revalidates it. The + <code>maxSdkVersion</code> and successfully re-validates it. The application functions as normal. However, some time later, the device receives another system update, this time to Android 2.0.1 (API Level 6). After the - update, the system can no longer revalidate the application because the system's + update, the system can no longer re-validate the application because the system's own API Level (6) is now higher than the maximum supported by the application (5). The system prevents the application from being visible to the user, in effect removing it from the device.</p> @@ -120,7 +134,7 @@ href="{@docRoot}guide/appendix/market-filters.html">Market Filters</a>.</p> provided it uses only standard APIs and follows development best practices. Second, note that in some cases, declaring the attribute can <strong>result in your application being removed from users' devices after a system - update</strong> to a higher API Level. Most devices on which your appplication + update</strong> to a higher API Level. Most devices on which your application is likely to be installed will receive periodic system updates over the air, so you should consider their effect on your application before setting this attribute.</p> @@ -128,8 +142,8 @@ href="{@docRoot}guide/appendix/market-filters.html">Market Filters</a>.</p> <p style="margin-bottom:1em;">Introduced in: API Level 4</p> <div class="special">Future versions of Android (beyond Android 2.0.1) will no -longer check or enforce the <code>android:maxSdkVersion</code> attribute during -installation or revalidation. Android Market will continue to use the attribute +longer check or enforce the <code>maxSdkVersion</code> attribute during +installation or re-validation. Google Play will continue to use the attribute as a filter, however, when presenting users with applications available for download. </div> </dd> diff --git a/docs/html/guide/topics/media/camera.jd b/docs/html/guide/topics/media/camera.jd index b962f96..7d72491 100644 --- a/docs/html/guide/topics/media/camera.jd +++ b/docs/html/guide/topics/media/camera.jd @@ -131,11 +131,11 @@ for example: <p>For a list of camera features, see the manifest <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html#hw-features">Features Reference</a>.</p> - <p>Adding camera features to your manifest causes Android Market to prevent your application from + <p>Adding camera features to your manifest causes Google Play to prevent your application from being installed to devices that do not include a camera or do not support the camera features you -specify. For more information about using feature-based filtering with Android Market, see <a -href="{@docRoot}guide/topics/manifest/uses-feature-element.html#market-feature-filtering">Android -Market and Feature-Based Filtering</a>.</p> +specify. For more information about using feature-based filtering with Google Play, see <a +href="{@docRoot}guide/topics/manifest/uses-feature-element.html#market-feature-filtering">Google +Play and Feature-Based Filtering</a>.</p> <p>If your application <em>can use</em> a camera or camera feature for proper operation, but does not <em>require</em> it, you should specify this in the manifest by including the {@code android:required} attribute, and setting it to {@code false}:</p> @@ -442,7 +442,7 @@ use or does not exist will cause your application to be shut down by the system. the first, back-facing camera on a device with more than one camera.</p> <h3 id="check-camera-features">Checking camera features</h3> -<p>Once you obtain access to a camera, you can get further information about its capabilties using +<p>Once you obtain access to a camera, you can get further information about its capabilities using the {@link android.hardware.Camera#getParameters() Camera.getParameters()} method and checking the returned {@link android.hardware.Camera.Parameters} object for supported capabilities. When using API Level 9 or higher, use the {@link android.hardware.Camera#getCameraInfo(int, @@ -677,8 +677,8 @@ button {@link android.view.View.OnClickListener}.</p> <pre> // Add a listener to the Capture button Button captureButton = (Button) findViewById(id.button_capture); - captureButton.setOnClickListener( - new View.OnClickListener() { +captureButton.setOnClickListener( + new View.OnClickListener() { @Override public void onClick(View v) { // get an image from the camera @@ -1037,7 +1037,7 @@ private static Uri getOutputMediaFileUri(int type){ } /** Create a File for saving an image or video */ -private static Uri getOutputMediaFile(int type){ +private static File getOutputMediaFile(int type){ // To be safe, you should check that the SDCard is mounted // using Environment.getExternalStorageState() before doing this. @@ -1260,7 +1260,7 @@ supported.</p> <p>If your application requires certain camera features in order to function properly, you can require them through additions to your application manifest. When you declare the use of specific -camera features, such as flash and auto-focus, the Android Market restricts your application from +camera features, such as flash and auto-focus, Google Play restricts your application from being installed on devices which do not support these features. For a list of camera features that can be declared in your app manifest, see the manifest <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html#hw-features"> Features diff --git a/docs/html/guide/topics/media/mediaplayer.jd b/docs/html/guide/topics/media/mediaplayer.jd index b3ca7dd..002d113 100644 --- a/docs/html/guide/topics/media/mediaplayer.jd +++ b/docs/html/guide/topics/media/mediaplayer.jd @@ -251,7 +251,7 @@ href="{@docRoot}guide/topics/resources/runtime-changes.html">Handling Runtime Ch "background media" even when the user leaves your activity, much in the same way that the built-in Music application behaves. In this case, what you need is a {@link android.media.MediaPlayer MediaPlayer} controlled by a {@link android.app.Service}, as -discussed in <a href="mpandservices">Using a Service with MediaPlayer</a>.</p> +discussed in <a href="#mpandservices">Using a Service with MediaPlayer</a>.</p> <h2 id="mpandservices">Using a Service with MediaPlayer</h2> diff --git a/docs/html/guide/topics/network/sip.jd b/docs/html/guide/topics/network/sip.jd index 276adb6..600da78 100644 --- a/docs/html/guide/topics/network/sip.jd +++ b/docs/html/guide/topics/network/sip.jd @@ -147,7 +147,7 @@ href="{@docRoot}guide/topics/manifest/uses-sdk-element.html"><uses-sdk></a </ul> <p>To control how your application is filtered from devices that do not support -SIP (for example, in Android Market), add the following to your application's +SIP (for example, on Google Play), add the following to your application's manifest:</p> <ul> diff --git a/docs/html/guide/topics/nfc/nfc.jd b/docs/html/guide/topics/nfc/nfc.jd index 175bc7c..834656a 100644 --- a/docs/html/guide/topics/nfc/nfc.jd +++ b/docs/html/guide/topics/nfc/nfc.jd @@ -318,8 +318,8 @@ other two intents, giving the user a better experience.</p> </pre> </li> - <li>The <code>uses-feature</code> element so that your application shows up in the Android -Market only for devices that have NFC hardware: + <li>The <code>uses-feature</code> element so that your application shows up in Google +Play only for devices that have NFC hardware: <pre> <uses-feature android:name="android.hardware.nfc" android:required="true" /> </pre> @@ -660,13 +660,13 @@ certainty that your application is started when an NFC tag is scanned. An AAR ha of an application embedded inside an NDEF record. You can add an AAR to any NDEF record of your NDEF message, because Android searches the entire NDEF message for AARs. If it finds an AAR, it starts the application based on the package name inside the AAR. If the application is not present on the device, -Android Market is launched to download the application.</p> +Google Play is launched to download the application.</p> <p>AARs are useful if you want to prevent other applications from filtering for the same intent and potentially handling specific tags that you have deployed. AARs are only supported at the application level, because of the package name constraint, and not at the Activity level as with intent filtering. If you want to handle an intent at the Activity level, <a -href="filtering-intents">use intent filters</a>. +href="#filtering-intents">use intent filters</a>. </p> @@ -678,7 +678,7 @@ the intent also matches the AAR, start the Activity.</li> <li>If the Activity that filters for the intent does not match the AAR, if multiple Activities can handle the intent, or if no Activity handles the intent, start the application specified by the AAR.</li> - <li>If no application can start with the AAR, go to the Android Market to download the + <li>If no application can start with the AAR, go to Google Play to download the application based on the AAR.</li> </ol> @@ -795,8 +795,8 @@ depending on what the user is doing in your application.</p> <p>The following sample shows how a simple activity calls {@link android.nfc.NfcAdapter.CreateNdefMessageCallback} in the <code>onCreate()</code> method of an -activity (see <a href="{@docRoot}resources/samples/AndroidBeam/index.html"></a> for the -complete sample). This example also has methods to help you create a MIME record:</p> +activity (see <a href="{@docRoot}resources/samples/AndroidBeamDemo/index.html">AndroidBeamDemo</a> +for the complete sample). This example also has methods to help you create a MIME record:</p> <pre id="code-example"> package com.example.android.beam; @@ -897,7 +897,7 @@ public class Beam extends Activity implements CreateNdefMessageCallback { <p>Note that this code comments out an AAR, which you can remove. If you enable the AAR, the application specified in the AAR always receives the Android Beam message. If the application is not -present, the Android Market is started to download the application. Therefore, the following intent +present, Google Play launches to download the application. Therefore, the following intent filter is not technically necessary for Android 4.0 devices or later if the AAR is used: </p> diff --git a/docs/html/guide/topics/providers/content-provider-basics.jd b/docs/html/guide/topics/providers/content-provider-basics.jd new file mode 100644 index 0000000..de89568 --- /dev/null +++ b/docs/html/guide/topics/providers/content-provider-basics.jd @@ -0,0 +1,1215 @@ +page.title=Content Provider Basics +@jd:body +<div id="qv-wrapper"> +<div id="qv"> + + + <!-- In this document --> +<h2>In this document</h2> +<ol> + <li> + <a href="#Basics">Overview</a> + <ol> + <li> + <a href="#ClientProvider">Accessing a provider</a> + </li> + <li> + <a href="#ContentURIs">Content URIs</a> + </li> + </ol> + </li> + <li> + <a href="#SimpleQuery">Retrieving Data from the Provider</a> + <ol> + <li> + <a href="#RequestPermissions">Requesting read access permission</a> + </li> + <li> + <a href="#Query">Constructing the query</a> + </li> + <li> + <a href="#DisplayResults">Displaying query results</a> + </li> + <li> + <a href="#GettingResults">Getting data from query results</a> + </li> + </ol> + </li> + <li> + <a href="#Permissions">Content Provider Permissions</a> + </li> + <li> + <a href="#Modifications">Inserting, Updating, and Deleting Data</a> + <ol> + <li> + <a href="#Inserting">Inserting data</a> + </li> + <li> + <a href="#Updating">Updating data</a> + </li> + <li> + <a href="#Deleting">Deleting data</a> + </li> + </ol> + </li> + <li> + <a href="#DataTypes">Provider Data Types</a> + </li> + <li> + <a href="#AltForms">Alternative Forms of Provider Access</a> + <ol> + <li> + <a href="#Batch">Batch access</a> + </li> + <li> + <a href="#Intents">Data access via intents</a> + </li> + </ol> + </li> + <li> + <a href="#ContractClasses">Contract Classes</a> + </li> + <li> + <a href="#MIMETypeReference">MIME Type Reference</a> + </li> +</ol> + + <!-- Key Classes --> +<h2>Key classes</h2> + <ol> + <li> + {@link android.content.ContentProvider} + </li> + <li> + {@link android.content.ContentResolver} + </li> + <li> + {@link android.database.Cursor} + </li> + <li> + {@link android.net.Uri} + </li> + </ol> + + <!-- Related Samples --> +<h2>Related Samples</h2> + <ol> + <li> + <a + href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/view/List2.html"> + Cursor (People)</a> + </li> + <li> + <a + href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/view/List7.html"> + Cursor (Phones)</a> + </li> + </ol> + + <!-- See also --> +<h2>See also</h2> + <ol> + <li> + <a href="{@docRoot}guide/topics/providers/content-provider-creating.html"> + Creating a Content Provider</a> + </li> + <li> + <a href="{@docRoot}guide/topics/providers/calendar-provider.html"> + Calendar Provider</a> + </li> + </ol> +</div> +</div> + + <!-- Intro paragraphs --> +<p> + A content provider manages access to a central repository of data. A provider + is part of an Android application, which often provides its own UI for working with + the data. However, content providers are primarily intended to be used by other + applications, which access the provider using a provider client object. Together, providers + and provider clients offer a consistent, standard interface to data that also handles + inter-process communication and secure data access. +</p> +<p> + This topic describes the basics of the following: +</p> + <ul> + <li>How content providers work.</li> + <li>The API you use retrieve data from a content provider.</li> + <li>The API you use to insert, update, or delete data in a content provider.</li> + <li>Other API features that facilitate working with providers.</li> + </ul> + + <!-- Basics --> +<h2 id="Basics">Overview</h2> +<p> + A content provider presents data to external applications as one or more tables that are + similar to the tables found in a relational database. A row represents an instance of some type + of data the provider collects, and each row in the column represents an individual piece of + data collected for an instance. +</p> +<p> + For example, one of the built-in providers in the Android platform is the user dictionary, which + stores the spellings of non-standard words that the user wants to keep. Table 1 illustrates what + the data might look like in this provider's table: +</p> +<p class="table-caption"> + <strong>Table 1:</strong> Sample user dictionary table. +</p> +<table id="table1" style="width: 50%;"> + <tr> + <th style="width:20%" align="center" scope="col">word</th> + <th style="width:20%" align="center" scope="col">app id</th> + <th style="width:20%" align="center" scope="col">frequency</th> + <th style="width:20%" align="center" scope="col">locale</th> + <th style="width:20%" align="center" scope="col">_ID</th> + </tr> + <tr> + <td align="center" scope="row">mapreduce</td> + <td align="center">user1</td> + <td align="center">100</td> + <td align="center">en_US</td> + <td align="center">1</td> + </tr> + <tr> + <td align="center" scope="row">precompiler</td> + <td align="center">user14</td> + <td align="center">200</td> + <td align="center">fr_FR</td> + <td align="center">2</td> + </tr> + <tr> + <td align="center" scope="row">applet</td> + <td align="center">user2</td> + <td align="center">225</td> + <td align="center">fr_CA</td> + <td align="center">3</td> + </tr> + <tr> + <td align="center" scope="row">const</td> + <td align="center">user1</td> + <td align="center">255</td> + <td align="center">pt_BR</td> + <td align="center">4</td> + </tr> + <tr> + <td align="center" scope="row">int</td> + <td align="center">user5</td> + <td align="center">100</td> + <td align="center">en_UK</td> + <td align="center">5</td> + </tr> +</table> +<p> + In table 1, each row represents an instance of a word that might not be + found in a standard dictionary. Each column represents some data for that word, such as the + locale in which it was first encountered. The column headers are column names that are stored in + the provider. To refer to a row's locale, you refer to its <code>locale</code> column. For + this provider, the <code>_ID</code> column serves as a "primary key" column that + the provider automatically maintains. +</p> +<p class="note"> + <strong>Note:</strong> A provider isn't required to have a primary key, and it isn't required + to use <code>_ID</code> as the column name of a primary key if one is present. However, + if you want to bind data from a provider to a {@link android.widget.ListView}, one of the + column names has to be <code>_ID</code>. This requirement is explained in more detail in the + section <a href="#DisplayResults">Displaying query results</a>. +</p> +<h3 id="ClientProvider">Accessing a provider</h3> +<p> + An application accesses the data from a content provider with + a {@link android.content.ContentResolver} client object. This object has methods that call + identically-named methods in the provider object, an instance of one of the concrete + subclasses of {@link android.content.ContentProvider}. The + {@link android.content.ContentResolver} methods provide the basic + "CRUD" (create, retrieve, update, and delete) functions of persistent storage. +</p> +<p> + The {@link android.content.ContentResolver} object in the client application's + process and the {@link android.content.ContentProvider} object in the application that owns + the provider automatically handle inter-process communication. + {@link android.content.ContentProvider} also acts as an abstraction layer between its + repository of data and the external appearance of data as tables. +</p> +<p class="note"> + <strong>Note:</strong> To access a provider, your application usually has to request specific + permissions in its manifest file. This is described in more detail in the section + <a href="#Permissions">Content Provider Permissions</a> +</p> +<p> + For example, to get a list of the words and their locales from the User Dictionary Provider, + you call {@link android.content.ContentResolver#query(Uri, String[], String, String[], String) + ContentResolver.query()}. + The {@link android.content.ContentResolver#query(Uri, String[], String, String[], String) + query()} method calls the + {@link android.content.ContentProvider#query(Uri, String[], String, String[], String) + ContentProvider.query()} method defined by the User Dictionary Provider. The following lines + of code show a + {@link android.content.ContentResolver#query(Uri, String[], String, String[], String) + ContentResolver.query()} call: +<p> +<pre> +// Queries the user dictionary and returns results +mCursor = getContentResolver().query( + UserDictionary.Words.CONTENT_URI, // The content URI of the words table + mProjection, // The columns to return for each row + mSelectionClause // Selection criteria + mSelectionArgs, // Selection criteria + mSortOrder); // The sort order for the returned rows +</pre> +<p> + Table 2 shows how the arguments to + {@link android.content.ContentResolver#query(Uri, String[], String, String[], String) + query(Uri,projection,selection,selectionArgs,sortOrder)} match an SQL SELECT statement: +</p> +<p class="table-caption"> + <strong>Table 2:</strong> Query() compared to SQL query. +</p> +<table id="table2" style="width: 75%;"> + <tr> + <th style="width:25%" align="center" scope="col">query() argument</th> + <th style="width:25%" align="center" scope="col">SELECT keyword/parameter</th> + <th style="width:50%" align="center" scope="col">Notes</th> + </tr> + <tr> + <td align="center"><code>Uri</code></td> + <td align="center"><code>FROM <em>table_name</em></code></td> + <td><code>Uri</code> maps to the table in the provider named <em>table_name</em>.</td> + </tr> + <tr> + <td align="center"><code>projection</code></td> + <td align="center"><code><em>col,col,col,...</em></code></td> + <td> + <code>projection</code> is an array of columns that should be included for each row + retrieved. + </td> + </tr> + <tr> + <td align="center"><code>selection</code></td> + <td align="center"><code>WHERE <em>col</em> = <em>value</em></code></td> + <td><code>selection</code> specifies the criteria for selecting rows.</td> + </tr> + <tr> + <td align="center"><code>selectionArgs</code></td> + <td align="center"> + (No exact equivalent. Selection arguments replace <code>?</code> placeholders in the + selection clause.) + </td> + </tr> + <tr> + <td align="center"><code>sortOrder</code></td> + <td align="center"><code>ORDER BY <em>col,col,...</em></code></td> + <td> + <code>sortOrder</code> specifies the order in which rows appear in the returned + {@link android.database.Cursor}. + </td> + </tr> +</table> +<h3 id="ContentURIs">Content URIs</h3> +<p> + A <strong>content URI</strong> is a URI that identifies data in a provider. Content URIs + include the symbolic name of the entire provider (its <strong>authority</strong>) and a + name that points to a table (a <strong>path</strong>). When you call + a client method to access a table in a provider, the content URI for the table is one of + the arguments. +</p> +<p> + In the preceding lines of code, the constant + {@link android.provider.UserDictionary.Words#CONTENT_URI} contains the content URI of + the user dictionary's "words" table. The {@link android.content.ContentResolver} + object parses out the URI's authority, and uses it to "resolve" the provider by + comparing the authority to a system table of known providers. The + {@link android.content.ContentResolver} can then dispatch the query arguments to the correct + provider. +</p> +<p> + The {@link android.content.ContentProvider} uses the path part of the content URI to choose the + table to access. A provider usually has a <strong>path</strong> for each table it exposes. +</p> +<p> + In the previous lines of code, the full URI for the "words" table is: +</p> +<pre> +content://user_dictionary/words +</pre> +<p> + where the <code>user_dictionary</code> string is the provider's authority, and + <code>words</code> string is the table's path. The string + <code>content://</code> (the <strong>scheme</strong>) is always present, + and identifies this as a content URI. +</p> +<p> + Many providers allow you to access a single row in a table by appending an ID value + to the end of the URI. For example, to retrieve a row whose <code>_ID</code> is + <code>4</code> from user dictionary, you can use this content URI: +</p> +<pre> +Uri singleUri = ContentUri.withAppendedId(UserDictionary.Words.CONTENT_URI,4); +</pre> +<p> + You often use id values when you've retrieved a set of rows and then want to update or delete + one of them. +</p> +<p class="note"> + <strong>Note:</strong> The {@link android.net.Uri} and {@link android.net.Uri.Builder} classes + contain convenience methods for constructing well-formed Uri objects from strings. The + {@link android.content.ContentUris} contains convenience methods for appending id values to + a URI. The previous snippet uses {@link android.content.ContentUris#withAppendedId(Uri, long) + withAppendedId()} to append an id to the UserDictionary content URI. +</p> + + + <!-- Retrieving Data from the Provider --> +<h2 id="SimpleQuery">Retrieving Data from the Provider</h2> +<p> + This section describes how to retrieve data from a provider, using the User Dictionary Provider + as an example. +</p> +<p class="note"> + For the sake of clarity, the code snippets in this section call + {@link android.content.ContentResolver#query(Uri, String[], String, String[], String) + ContentResolver.query()} on the "UI thread"". In actual code, however, you should + do queries asynchronously on a separate thread. One way to do this is to use the + {@link android.content.CursorLoader} class, which is described + in more detail in the <a href="{@docRoot}guide/topics/fundamentals/loaders.html"> + Loaders</a> guide. Also, the lines of code are snippets only; they don't show a complete + application. +</p> +<p> + To retrieve data from a provider, follow these basic steps: +</p> +<ol> + <li> + Request the read access permission for the provider. + </li> + <li> + Define the code that sends a query to the provider. + </li> +</ol> +<h3 id="RequestPermissions">Requesting read access permission</h3> +<p> + To retrieve data from a provider, your application needs "read access permission" for the + provider. You can't request this permission at run-time; instead, you have to specify that + you need this permission in your manifest, using the + <code><a href="{@docRoot}guide/topics/manifest/uses-permission-element.html"> + <uses-permission></a></code> element and the exact permission name defined by the + provider. When you specify this element in your manifest, you are in effect "requesting" this + permission for your application. When users install your application, they implicitly grant + this request. +</p> +<p> + To find the exact name of the read access permission for the provider you're using, as well + as the names for other access permissions used by the provider, look in the provider's + documentation. +</p> +<p> + The role of permissions in accessing providers is described in more detail in the section + <a href="#Permissions">Content Provider Permissions</a>. +</p> +<p> + The User Dictionary Provider defines the permission + <code>android.permission.READ_USER_DICTIONARY</code> in its manifest file, so an + application that wants to read from the provider must request this permission. +</p> +<!-- Constructing the query --> +<h3 id="Query">Constructing the query</h3> +<p> + The next step in retrieving data a provider is to construct a query. This first snippet + defines some variables for accessing the User Dictionary Provider: +</p> +<pre class="prettyprint"> + +// A "projection" defines the columns that will be returned for each row +String[] mProjection = +{ + UserDictionary.Words._ID, // Contract class constant for the _ID column name + UserDictionary.Words.WORD, // Contract class constant for the word column name + UserDictionary.Words.LOCALE // Contract class constant for the locale column name +}; + +// Defines a string to contain the selection clause +String mSelectionClause = null; + +// Initializes an array to contain selection arguments +String[] mSelectionArgs = {""}; + +</pre> +<p> + The next snippet shows how to use + {@link android.content.ContentResolver#query(Uri, String[], String, String[], String) + ContentResolver.query()}, using the User Dictionary Provider as an example. + A provider client query is similar to an SQL query, and it contains a set of columns to return, + a set of selection criteria, and a sort order. +</p> +<p> + The set of columns that the query should return is called a <strong>projection</strong> + (the variable <code>mProjection</code>). +</p> +<p> + The expression that specifies the rows to retrieve is split into a selection clause and + selection arguments. The selection clause is a combination of logical and Boolean expressions, + column names, and values (the variable <code>mSelection</code>). If you specify the replaceable + parameter <code>?</code> instead of a value, the query method retrieves the value from the + selection arguments array (the variable <code>mSelectionArgs</code>). +</p> +<p> + In the next snippet, if the user doesn't enter a word, the selection clause is set to + <code>null</code>, and the query returns all the words in the provider. If the user enters + a word, the selection clause is set to <code>UserDictionary.Words.Word + " = ?"</code> and + the first element of selection arguments array is set to the word the user enters. +</p> +<pre class="prettyprint"> +/* + * This defines a one-element String array to contain the selection argument. + */ +String[] mSelectionArgs = {""}; + +// Gets a word from the UI +mSearchString = mSearchWord.getText().toString(); + +// Remember to insert code here to check for invalid or malicious input. + +// If the word is the empty string, gets everything +if (TextUtils.isEmpty(mSearchString)) { + // Setting the selection clause to null will return all words + mSelectionClause = null; + mSelectionArgs[0] = ""; + +} else { + // Constructs a selection clause that matches the word that the user entered. + mSelectionClause = " = ?"; + + // Moves the user's input string to the selection arguments. + mSelectionArgs[0] = mSearchString; + +} + +// Does a query against the table and returns a Cursor object +mCursor = getContentResolver().query( + UserDictionary.Words.CONTENT_URI, // The content URI of the words table + mProjection, // The columns to return for each row + mSelectionClause // Either null, or the word the user entered + mSelectionArgs, // Either empty, or the string the user entered + mSortOrder); // The sort order for the returned rows + +// Some providers return null if an error occurs, others throw an exception +if (null == mCursor) { + /* + * Insert code here to handle the error. Be sure not to use the cursor! You may want to + * call android.util.Log.e() to log this error. + * + */ +// If the Cursor is empty, the provider found no matches +} else if (mCursor.getCount() < 1) { + + /* + * Insert code here to notify the user that the search was unsuccessful. This isn't necessarily + * an error. You may want to offer the user the option to insert a new row, or re-type the + * search term. + */ + +} else { + // Insert code here to do something with the results + +} +</pre> +<p> + This query is analogous to the SQL statement: +</p> +<pre> +SELECT _ID, word, frequency, locale FROM words WHERE word = <userinput> ORDER BY word ASC; +</pre> +<p> + In this SQL statement, the actual column names are used instead of contract class constants. +</p> +<h4 id="Injection">Protecting against malicious input</h4> +<p> + If the data managed by the content provider is in an SQL database, including external untrusted + data into raw SQL statements can lead to SQL injection. +</p> +<p> + Consider this selection clause: +</p> +<pre> +// Constructs a selection clause by concatenating the user's input to the column name +String mSelectionClause = "var = " + mUserInput; +</pre> +<p> + If you do this, you're allowing the user to concatenate malicious SQL onto your SQL statement. + For example, the user could enter "nothing; DROP TABLE *;" for <code>mUserInput</code>, which + would result in the selection clause <code>var = nothing; DROP TABLE *;</code>. Since the + selection clause is treated as an SQL statement, this might cause the provider to erase all of + the tables in the underlying SQLite database (unless the provider is set up to catch + <a href="http://en.wikipedia.org/wiki/SQL_injection">SQL injection</a> attempts). +</p> +<p> + To avoid this problem, use a selection clause that uses <code>?</code> as a replaceable + parameter and a separate array of selection arguments. When you do this, the user input + is bound directly to the query rather than being interpreted as part of an SQL statement. + Because it's not treated as SQL, the user input can't inject malicious SQL. Instead of using + concatenation to include the user input, use this selection clause: +</p> +<pre> +// Constructs a selection clause with a replaceable parameter +String mSelectionClause = "var = ?"; +</pre> +<p> + Set up the array of selection arguments like this: +</p> +<pre> +// Defines an array to contain the selection arguments +String[] selectionArgs = {""}; +</pre> +<p> + Put a value in the selection arguments array like this: +</p> +<pre> +// Sets the selection argument to the user's input +selectionArgs[0] = mUserInput; +</pre> +<p> + A selection clause that uses <code>?</code> as a replaceable parameter and an array of + selection arguments array are preferred way to specify a selection, even if the provider isn't + based on an SQL database. +</p> +<!-- Displaying the results --> +<h3 id="DisplayResults">Displaying query results</h3> +<p> + The {@link android.content.ContentResolver#query(Uri, String[], String, String[], String) + ContentResolver.query()} client method always returns a {@link android.database.Cursor} + containing the columns specified by the query's projection for the rows that match the query's + selection criteria. A {@link android.database.Cursor} object provides random read access to the + rows and columns it contains. Using {@link android.database.Cursor} methods, + you can iterate over the rows in the results, determine the data type of each column, get the + data out of a column, and examine other properties of the results. Some + {@link android.database.Cursor} implementations automatically update the object when the + provider's data changes, or trigger methods in an observer object when the + {@link android.database.Cursor} changes, or both. +</p> +<p class="note"> + <strong>Note:</strong> A provider may restrict access to columns based on the nature of the + object making the query. For example, the Contacts Provider restricts access for some columns to + sync adapters, so it won't return them to an activity or service. +</p> +<p> + If no rows match the selection criteria, the provider + returns a {@link android.database.Cursor} object for which + {@link android.database.Cursor#getCount() Cursor.getCount()} is 0 (an empty cursor). +</p> +<p> + If an internal error occurs, the results of the query depend on the particular provider. It may + choose to return <code>null</code>, or it may throw an {@link java.lang.Exception}. +</p> +<p> + Since a {@link android.database.Cursor} is a "list" of rows, a good way to display the + contents of a {@link android.database.Cursor} is to link it to a {@link android.widget.ListView} + via a {@link android.widget.SimpleCursorAdapter}. +</p> +<p> + The following snippet continues the code from the previous snippet. It creates a + {@link android.widget.SimpleCursorAdapter} object containing the {@link android.database.Cursor} + retrieved by the query, and sets this object to be the adapter for a + {@link android.widget.ListView}: +</p> +<pre class="prettyprint"> +// Defines a list of columns to retrieve from the Cursor and load into an output row +String[] mWordListColumns = +{ + UserDictionary.Words.WORD, // Contract class constant containing the word column name + UserDictionary.Words.LOCALE // Contract class constant containing the locale column name +}; + +// Defines a list of View IDs that will receive the Cursor columns for each row +int[] mWordListItems = { R.id.dictWord, R.id.locale}; + +// Creates a new SimpleCursorAdapter +mCursorAdapter = new SimpleCursorAdapter( + getApplicationContext(), // The application's Context object + R.layout.wordlistrow, // A layout in XML for one row in the ListView + mCursor, // The result from the query + mWordListColumns, // A string array of column names in the cursor + mWordListItems, // An integer array of view IDs in the row layout + 0); // Flags (usually none are needed) + +// Sets the adapter for the ListView +mWordList.setAdapter(mCursorAdapter); +</pre> +<p class="note"> + <strong>Note:</strong> To back a {@link android.widget.ListView} with a + {@link android.database.Cursor}, the cursor must contain a column named <code>_ID</code>. + Because of this, the query shown previously retrieves the <code>_ID</code> column for the + "words" table, even though the {@link android.widget.ListView} doesn't display it. + This restriction also explains why most providers have a <code>_ID</code> column for each of + their tables. +</p> + + <!-- Getting data from query results --> +<h3 id="GettingResults">Getting data from query results</h3> +<p> + Rather than simply displaying query results, you can use them for other tasks. For + example, you can retrieve spellings from the user dictionary and then look them up in + other providers. To do this, you iterate over the rows in the {@link android.database.Cursor}: +</p> +<pre class="prettyprint"> + +// Determine the column index of the column named "word" +int index = mCursor.getColumnIndex(UserDictionary.Words.WORD); + +/* + * Only executes if the cursor is valid. The User Dictionary Provider returns null if + * an internal error occurs. Other providers may throw an Exception instead of returning null. + */ + +if (mCursor != null) { + /* + * Moves to the next row in the cursor. Before the first movement in the cursor, the + * "row pointer" is -1, and if you try to retrieve data at that position you will get an + * exception. + */ + while (mCursor.moveToNext()) { + + // Gets the value from the column. + newWord = mCursor.getString(index); + + // Insert code here to process the retrieved word. + + ... + + // end of while loop + } +} else { + + // Insert code here to report an error if the cursor is null or the provider threw an exception. +} +</pre> +<p> + {@link android.database.Cursor} implementations contain several "get" methods for + retrieving different types of data from the object. For example, the previous snippet + uses {@link android.database.Cursor#getString(int) getString()}. They also have a + {@link android.database.Cursor#getType(int) getType()} method that returns a value indicating + the data type of the column. +</p> + + + <!-- Requesting permissions --> +<h2 id="Permissions">Content Provider Permissions</h2> +<p> + A provider's application can specify permissions that other applications must have in order to + access the provider's data. These permissions ensure that the user knows what data + an application will try to access. Based on the provider's requirements, other applications + request the permissions they need in order to access the provider. End users see the requested + permissions when they install the application. +</p> +<p> + If a provider's application doesn't specify any permissions, then other applications have no + access to the provider's data. However, components in the provider's application always have + full read and write access, regardless of the specified permissions. +</p> +<p> + As noted previously, the User Dictionary Provider requires the + <code>android.permission.READ_USER_DICTIONARY</code> permission to retrieve data from it. + The provider has the separate <code>android.permission.WRITE_USER_DICTIONARY</code> + permission for inserting, updating, or deleting data. +</p> +<p> + To get the permissions needed to access a provider, an application requests them with a + <code><a href="{@docRoot}guide/topics/manifest/uses-permission-element.html"> + <uses-permission></a></code> element in its manifest file. + When the Android Package Manager installs the application, a user must approve all of the + permissions the application requests. If the user approves all of them, Package Manager + continues the installation; if the user doesn't approve them, Package Manager + aborts the installation. +</p> +<p> + The following + <code><a href="{@docRoot}guide/topics/manifest/uses-permission-element.html"> + <uses-permission></a></code> element requests read access to the User Dictionary Provider: +</p> +<pre> + <uses-permission android:name="android.permission.READ_USER_DICTIONARY"> +</pre> +<p> + The impact of permissions on provider access is explained in more detail in the + <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a> guide. +</p> + + +<!-- Inserting, Updating, and Deleting Data --> +<h2 id="Modifications">Inserting, Updating, and Deleting Data</h2> +<p> + In the same way that you retrieve data from a provider, you also use the interaction between + a provider client and the provider's {@link android.content.ContentProvider} to modify data. + You call a method of {@link android.content.ContentResolver} with arguments that are passed to + the corresponding method of {@link android.content.ContentProvider}. The provider and provider + client automatically handle security and inter-process communication. +</p> +<h3 id="Inserting">Inserting data</h3> +<p> + To insert data into a provider, you call the + {@link android.content.ContentResolver#insert(Uri,ContentValues) ContentResolver.insert()} + method. This method inserts a new row into the provider and returns a content URI for that row. + This snippet shows how to insert a new word into the User Dictionary Provider: +</p> +<pre class="prettyprint"> +// Defines a new Uri object that receives the result of the insertion +Uri mNewUri; + +... + +// Defines an object to contain the new values to insert +ContentValues mNewValues = new ContentValues(); + +/* + * Sets the values of each column and inserts the word. The arguments to the "put" + * method are "column name" and "value" + */ +mNewValues.put(UserDictionary.Words.APP_ID, "example.user"); +mNewValues.put(UserDictionary.Words.LOCALE, "en_US"); +mNewValues.put(UserDictionary.Words.WORD, "insert"); +mNewValues.put(UserDictionary.Words.FREQUENCY, "100"); + +mNewUri = getContentResolver().insert( + UserDictionary.Word.CONTENT_URI, // the user dictionary content URI + mNewValues // the values to insert +); +</pre> +<p> + The data for the new row goes into a single {@link android.content.ContentValues} object, which + is similar in form to a one-row cursor. The columns in this object don't need to have the + same data type, and if you don't want to specify a value at all, you can set a column + to <code>null</code> using {@link android.content.ContentValues#putNull(String) + ContentValues.putNull()}. +</p> +<p> + The snippet doesn't add the <code>_ID</code> column, because this column is maintained + automatically. The provider assigns a unique value of <code>_ID</code> to every row that is + added. Providers usually use this value as the table's primary key. +</p> +<p> + The content URI returned in <code>newUri</code> identifies the newly-added row, with + the following format: +</p> +<pre> +content://user_dictionary/words/<id_value> +</pre> +<p> + The <code><id_value></code> is the contents of <code>_ID</code> for the new row. + Most providers can detect this form of content URI automatically and then perform the requested + operation on that particular row. +</p> +<p> + To get the value of <code>_ID</code> from the returned {@link android.net.Uri}, call + {@link android.content.ContentUris#parseId(Uri) ContentUris.parseId()}. +</p> +<h3 id="Updating">Updating data</h3> +<p> + To update a row, you use a {@link android.content.ContentValues} object with the updated + values just as you do with an insertion, and selection criteria just as you do with a query. + The client method you use is + {@link android.content.ContentResolver#update(Uri, ContentValues, String, String[]) + ContentResolver.update()}. You only need to add values to the + {@link android.content.ContentValues} object for columns you're updating. If you want to clear + the contents of a column, set the value to <code>null</code>. +</p> +<p> + The following snippet changes all the rows whose locale has the language "en" to a + have a locale of <code>null</code>. The return value is the number of rows that were updated: +</p> +<pre> +// Defines an object to contain the updated values +ContentValues mUpdateValues = new ContentValues(); + +// Defines selection criteria for the rows you want to update +String mSelectionClause = UserDictionary.Words.LOCALE + "LIKE ?"; +String[] mSelectionArgs = {"en_%"}; + +// Defines a variable to contain the number of updated rows +int mRowsUpdated = 0; + +... + +/* + * Sets the updated value and updates the selected words. + */ +mUpdateValues.putNull(UserDictionary.Words.LOCALE); + +mRowsUpdated = getContentResolver().update( + UserDictionary.Words.CONTENT_URI, // the user dictionary content URI + mUpdateValues // the columns to update + mSelectionClause // the column to select on + mSelectionArgs // the value to compare to +); +</pre> +<p> + You should also sanitize user input when you call + {@link android.content.ContentResolver#update(Uri, ContentValues, String, String[]) + ContentResolver.update()}. To learn more about this, read the section + <a href="#Injection">Protecting against malicious input</a>. +</p> +<h3 id="Deleting">Deleting data</h3> +<p> + Deleting rows is similar to retrieving row data: you specify selection criteria for the rows + you want to delete and the client method returns the number of deleted rows. + The following snippet deletes rows whose appid matches "user". The method returns the + number of deleted rows. +</p> +<pre> + +// Defines selection criteria for the rows you want to delete +String mSelectionClause = UserDictionary.Words.APP_ID + " LIKE ?"; +String[] mSelectionArgs = {"user"}; + +// Defines a variable to contain the number of rows deleted +int mRowsDeleted = 0; + +... + +// Deletes the words that match the selection criteria +mRowsDeleted = getContentResolver().delete( + UserDictionary.Words.CONTENT_URI, // the user dictionary content URI + mSelectionClause // the column to select on + mSelectionArgs // the value to compare to +); +</pre> +<p> + You should also sanitize user input when you call + {@link android.content.ContentResolver#delete(Uri, String, String[]) + ContentResolver.delete()}. To learn more about this, read the section + <a href="#Injection">Protecting against malicious input</a>. +</p> +<!-- Provider Data Types --> +<h2 id="DataTypes">Provider Data Types</h2> +<p> + Content providers can offer many different data types. The User Dictionary Provider offers only + text, but providers can also offer the following formats: +</p> + <ul> + <li> + integer + </li> + <li> + long integer (long) + </li> + <li> + floating point + </li> + <li> + long floating point (double) + </li> + </ul> +<p> + Another data type that providers often use is Binary Large OBject (BLOB) implemented as a + 64KB byte array. You can see the available data types by looking at the + {@link android.database.Cursor} class "get" methods. +</p> +<p> + The data type for each column in a provider is usually listed in its documentation. + The data types for the User Dictionary Provider are listed in the reference documentation + for its contract class {@link android.provider.UserDictionary.Words} (contract classes are + described in the section <a href="#ContractClasses">Contract Classes</a>). + You can also determine the data type by calling {@link android.database.Cursor#getType(int) + Cursor.getType()}. +</p> +<p> + Providers also maintain MIME data type information for each content URI they define. You can + use the MIME type information to find out if your application can handle data that the + provider offers, or to choose a type of handling based on the MIME type. You usually need the + MIME type when you are working with a provider that contains complex + data structures or files. For example, the {@link android.provider.ContactsContract.Data} + table in the Contacts Provider uses MIME types to label the type of contact data stored in each + row. To get the MIME type corresponding to a content URI, call + {@link android.content.ContentResolver#getType(Uri) ContentResolver.getType()}. +</p> +<p> + The section <a href="#MIMETypeReference">MIME Type Reference</a> describes the + syntax of both standard and custom MIME types. +</p> + + +<!-- Alternative Forms of Provider Access --> +<h2 id="AltForms">Alternative Forms of Provider Access</h2> +<p> + Three alternative forms of provider access are important in application development: +</p> +<ul> + <li> + <a href="#Batch">Batch access</a>: You can create a batch of access calls with methods in + the {@link android.content.ContentProviderOperation} class, and then apply them with + {@link android.content.ContentResolver#applyBatch(String, ArrayList) + ContentResolver.applyBatch()}. + </li> + <li> + Asynchronous queries: You should do queries in a separate thread. One way to do this is to + use a {@link android.content.CursorLoader} object. The examples in the + <a href="{@docRoot}guide/topics/fundamentals/loaders.html">Loaders</a> guide demonstrate + how to do this. + </li> + <li> + <a href="#Intents">Data access via intents</a>: Although you can't send an intent + directly to a provider, you can send an intent to the provider's application, which is + usually the best-equipped to modify the provider's data. + </li> +</ul> +<p> + Batch access and modification via intents are described in the following sections. +</p> +<h3 id="Batch">Batch access</h3> +<p> + Batch access to a provider is useful for inserting a large number of rows, or for inserting + rows in multiple tables in the same method call, or in general for performing a set of + operations across process boundaries as a transaction (an atomic operation). +</p> +<p> + To access a provider in "batch mode", + you create an array of {@link android.content.ContentProviderOperation} objects and then + dispatch them to a content provider with + {@link android.content.ContentResolver#applyBatch(String, ArrayList) + ContentResolver.applyBatch()}. You pass the content provider's <em>authority</em> to this + method, rather than a particular content URI, which allows each + {@link android.content.ContentProviderOperation} object in the array to work against a + different table. A call to {@link android.content.ContentResolver#applyBatch(String, ArrayList) + ContentResolver.applyBatch()} returns an array of results. +</p> +<p> + The description of the {@link android.provider.ContactsContract.RawContacts} contract class + includes a code snippet that demonstrates batch insertion. The + <a href="{@docRoot}resources/samples/ContactManager/index.html">Contact Manager</a> + sample application contains an example of batch access in its <code>ContactAdder.java</code> + source file. +</p> +<div class="sidebox-wrapper"> +<div class="sidebox"> +<h2>Displaying data using a helper app</h2> +<p> + If your application <em>does</em> have access permissions, you still may want to use an + intent to display data in another application. For example, the Calendar application accepts an + {@link android.content.Intent#ACTION_VIEW} intent, which displays a particular date or event. + This allows you to display calendar information without having to create your own UI. + To learn more about this feature, see the + <a href="{@docRoot}guide/topics/providers/calendar-provider.html">Calendar Provider</a> guide. +</p> +<p> + The application to which you send the intent doesn't have to be the application + associated with the provider. For example, you can retrieve a contact from the + Contact Provider, then send an {@link android.content.Intent#ACTION_VIEW} intent + containing the content URI for the contact's image to an image viewer. +</p> +</div> +</div> +<h3 id="Intents">Data access via intents</h3> +<p> + Intents can provide indirect access to a content provider. You allow the user to access + data in a provider even if your application doesn't have access permissions, either by + getting a result intent back from an application that has permissions, or by activating an + application that has permissions and letting the user do work in it. +</p> +<h4>Getting access with temporary permissions</h4> +<p> + You can access data in a content provider, even if you don't have the proper access + permissions, by sending an intent to an application that does have the permissions and + receiving back a result intent containing "URI" permissions. + These are permissions for a specific content URI that last until the activity that receives + them is finished. The application that has permanent permissions grants temporary + permissions by setting a flag in the result intent: +</p> +<ul> + <li> + <strong>Read permission:</strong> + {@link android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION} + </li> + <li> + <strong>Write permission:</strong> + {@link android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION} + </li> +</ul> +<p class="note"> + <strong>Note:</strong> These flags don't give general read or write access to the provider + whose authority is contained in the content URI. The access is only for the URI itself. +</p> +<p> + A provider defines URI permissions for content URIs in its manifest, using the + <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#gprmsn"> + android:grantUriPermission</a></code> + attribute of the + {@code <a href="guide/topics/manifest/provider-element.html"><provider></a>} + element, as well as the + {@code <a href="guide/topics/manifest/grant-uri-permission-element.html"> + <grant-uri-permission></a>} child element of the + {@code <a href="guide/topics/manifest/provider-element.html"><provider></a>} + element. The URI permissions mechanism is explained in more detail in the + <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a> guide, + in the section "URI Permissions". +</p> +<p> + For example, you can retrieve data for a contact in the Contacts Provider, even if you don't + have the {@link android.Manifest.permission#READ_CONTACTS} permission. You might want to do + this in an application that sends e-greetings to a contact on his or her birthday. Instead of + requesting {@link android.Manifest.permission#READ_CONTACTS}, which gives you access to all of + the user's contacts and all of their information, you prefer to let the user control which + contacts are used by your application. To do this, you use the following process: +</p> +<ol> + <li> + Your application sends an intent containing the action + {@link android.content.Intent#ACTION_PICK} and the "contacts" MIME type + {@link android.provider.ContactsContract.RawContacts#CONTENT_ITEM_TYPE}, using the + method {@link android.app.Activity#startActivityForResult(Intent, int) + startActivityForResult()}. + </li> + <li> + Because this intent matches the intent filter for the + People app's "selection" activity, the activity will come to the foreground. + </li> + <li> + In the selection activity, the user selects a + contact to update. When this happens, the selection activity calls + {@link android.app.Activity#setResult(int, Intent) setResult(resultcode, intent)} + to set up a intent to give back to your application. The intent contains the content URI + of the contact the user selected, and the "extras" flags + {@link android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION}. These flags grant URI + permission to your app to read data for the contact pointed to by the + content URI. The selection activity then calls {@link android.app.Activity#finish()} to + return control to your application. + </li> + <li> + Your activity returns to the foreground, and the system calls your activity's + {@link android.app.Activity#onActivityResult(int, int, Intent) onActivityResult()} + method. This method receives the result intent created by the selection activity in + the People app. + </li> + <li> + With the content URI from the result intent, you can read the contact's data + from the Contacts Provider, even though you didn't request permanent read access permission + to the provider in your manifest. You can then get the contact's birthday information + or his or her email address and then send the e-greeting. + </li> +</ol> +<h4>Using another application</h4> +<p> + A simple way to allow the user to modify data to which you don't have access permissions is to + activate an application that has permissions and let the user do the work there. +</p> +<p> + For example, the Calendar application accepts an + {@link android.content.Intent#ACTION_INSERT} intent, which allows you to activate the + application's insert UI. You can pass "extras" data in this intent, which the application + uses to pre-populate the UI. Because recurring events have a complex syntax, the preferred + way of inserting events into the Calendar Provider is to activate the Calendar app with an + {@link android.content.Intent#ACTION_INSERT} and then let the user insert the event there. +</p> +<!-- Contract Classes --> +<h2 id="ContractClasses">Contract Classes</h2> +<p> + A contract class defines constants that help applications work with the content URIs, column + names, intent actions, and other features of a content provider. Contract classes are not + included automatically with a provider; the provider's developer has to define them and then + make them available to other developers. Many of the providers included with the Android + platform have corresponding contract classes in the package {@link android.provider}. +</p> +<p> + For example, the User Dictionary Provider has a contract class + {@link android.provider.UserDictionary} containing content URI and column name constants. The + content URI for the "words" table is defined in the constant + {@link android.provider.UserDictionary.Words#CONTENT_URI UserDictionary.Words.CONTENT_URI}. + The {@link android.provider.UserDictionary.Words} class also contains column name constants, + which are used in the example snippets in this guide. For example, a query projection can be + defined as: +</p> +<pre> +String[] mProjection = +{ + UserDictionary.Words._ID, + UserDictionary.Words.WORD, + UserDictionary.Words.LOCALE +}; +</pre> +<p> + Another contract class is {@link android.provider.ContactsContract} for the Contacts Provider. + The reference documentation for this class includes example code snippets. One of its + subclasses, {@link android.provider.ContactsContract.Intents.Insert}, is a contract + class that contains constants for intents and intent data. +</p> + + +<!-- MIME Type Reference --> +<h2 id="MIMETypeReference">MIME Type Reference</h2> +<p> + Content providers can return standard MIME media types, or custom MIME type strings, or both. +</p> +<p> + MIME types have the format +</p> +<pre> +<em>type</em>/<em>subtype</em> +</pre> +<p> + For example, the well-known MIME type <code>text/html</code> has the <code>text</code> type and + the <code>html</code> subtype. If the provider returns this type for a URI, it means that a + query using that URI will return text containing HTML tags. +</p> +<p> + Custom MIME type strings, also called "vendor-specific" MIME types, have more + complex <em>type</em> and <em>subtype</em> values. The <em>type</em> value is always +</p> +<pre> +vnd.android.cursor.<strong>dir</strong> +</pre> +<p> + for multiple rows, or +</p> +<pre> +vnd.android.cursor.<strong>item</strong> +</pre> +<p> + for a single row. +</p> +<p> + The <em>subtype</em> is provider-specific. The Android built-in providers usually have a simple + subtype. For example, the when the Contacts application creates a row for a telephone number, + it sets the following MIME type in the row: +</p> +<pre> +vnd.android.cursor.item/phone_v2 +</pre> +<p> + Notice that the subtype value is simply <code>phone_v2</code>. +</p> +<p> + Other provider developers may create their own pattern of subtypes based on the provider's + authority and table names. For example, consider a provider that contains train timetables. + The provider's authority is <code>com.example.trains</code>, and it contains the tables + Line1, Line2, and Line3. In response to the content URI +</p> +<p> +<pre> +content://com.example.trains/Line1 +</pre> +<p> + for table Line1, the provider returns the MIME type +</p> +<pre> +vnd.android.cursor.<strong>dir</strong>/vnd.example.line1 +</pre> +<p> + In response to the content URI +</p> +<pre> +content://com.example.trains/Line2/5 +</pre> +<p> + for row 5 in table Line2, the provider returns the MIME type +</p> +<pre> +vnd.android.cursor.<strong>item</strong>/vnd.example.line2 +</pre> +<p> + Most content providers define contract class constants for the MIME types they use. The + Contacts Provider contract class {@link android.provider.ContactsContract.RawContacts}, + for example, defines the constant + {@link android.provider.ContactsContract.RawContacts#CONTENT_ITEM_TYPE} for the MIME type of + a single raw contact row. +</p> +<p> + Content URIs for single rows are described in the section + <a href="#ContentURIs">Content URIs</a>. +</p> diff --git a/docs/html/guide/topics/providers/content-provider-creating.jd b/docs/html/guide/topics/providers/content-provider-creating.jd new file mode 100644 index 0000000..4ebdb50 --- /dev/null +++ b/docs/html/guide/topics/providers/content-provider-creating.jd @@ -0,0 +1,1215 @@ +page.title=Creating a Content Provider +@jd:body +<div id="qv-wrapper"> +<div id="qv"> + + +<h2>In this document</h2> +<ol> + <li> + <a href="#DataStorage">Designing Data Storage</a> + </li> + <li> + <a href="#ContentURI">Designing Content URIs</a> + </li> + <li> + <a href="#ContentProvider">Implementing the ContentProvider Class</a> + <ol> + <li> + <a href="#RequiredAccess">Required Methods</a> + </li> + <li> + <a href="#Query">Implementing the query() method</a> + </li> + <li> + <a href="#Insert">Implementing the insert() method</a> + </li> + <li> + <a href="#Delete">Implementing the delete() method</a> + </li> + <li> + <a href="#Update">Implementing the update() method</a> + </li> + <li> + <a href="#OnCreate">Implementing the onCreate() method</a> + </li> + </ol> + </li> + <li> + <a href="#MIMETypes">Implementing Content Provider MIME Types</a> + <ol> + <li> + <a href="#TableMIMETypes">MIME types for tables</a> + </li> + <li> + <a href="#FileMIMETypes">MIME types for files</a> + </li> + </ol> + </li> + <li> + <a href="#ContractClass">Implementing a Contract Class</a> + </li> + <li> + <a href="#Permissions">Implementing Content Provider Permissions</a> + </li> + <li> + <a href="#ProviderElement">The <provider> Element</a> + </li> + <li> + <a href="#Intents">Intents and Data Access</a> + </li> +</ol> +<h2>Key classes</h2> + <ol> + <li> + {@link android.content.ContentProvider} + </li> + <li> + {@link android.database.Cursor} + </li> + <li> + {@link android.net.Uri} + </li> + </ol> +<h2>Related Samples</h2> + <ol> + <li> + <a + href="{@docRoot}resources/samples/NotePad/index.html"> + Note Pad sample application + </a> + </li> + </ol> +<h2>See also</h2> + <ol> + <li> + <a href="{@docRoot}guide/topics/providers/content-provider-basics.html"> + Content Provider Basics</a> + </li> + <li> + <a href="{@docRoot}guide/topics/providers/calendar-provider.html"> + Calendar Provider</a> + </li> + </ol> +</div> +</div> + + +<p> + A content provider manages access to a central repository of data. You implement a + provider as one or more classes in an Android application, along with elements in + the manifest file. One of your classes implements a subclass + {@link android.content.ContentProvider}, which is the interface between your provider and + other applications. Although content providers are meant to make data available to other + applications, you may of course have activities in your application that allow the user + to query and modify the data managed by your provider. +</p> +<p> + The rest of this topic is a basic list of steps for building a content provider and a list + of APIs to use. +</p> + + +<!-- Before You Start Building --> +<h2 id="BeforeYouStart">Before You Start Building</h2> +<p> + Before you start building a provider, do the following: +</p> +<ol> + <li> + <strong>Decide if you need a content provider</strong>. You need to build a content + provider if you want to provide one or more of the following features: + <ul> + <li>You want to offer complex data or files to other applications.</li> + <li>You want to allow users to copy complex data from your app into other apps.</li> + <li>You want to provide custom search suggestions using the search framework.</li> + </ul> + <p> + You <em>don't</em> need a provider to use an SQLite database if the use is entirely within + your own application. + </p> + </li> + <li> + If you haven't done so already, read the topic + <a href="{@docRoot}guide/topics/providers/content-provider-basics.html"> + Content Provider Basics</a> to learn more about providers. + </li> +</ol> +<p> + Next, follow these steps to build your provider: +</p> +<ol> + <li> + Design the raw storage for your data. A content provider offers data in two ways: + <dl> + <dt> + File data + </dt> + <dd> + Data that normally goes into files, such as + photos, audio, or videos. Store the files in your application's private + space. In response to a request for a file from another application, your + provider can offer a handle to the file. + </dd> + <dt> + "Structured" data + </dt> + <dd> + Data that normally goes into a database, array, or similar structure. + Store the data in a form that's compatible with tables of rows and columns. A row + represents an entity, such as a person or an item in inventory. A column represents + some data for the entity, such a person's name or an item's price. A common way to + store this type of data is in an SQLite database, but you can use any type of + persistent storage. To learn more about the storage types available in the + Android system, see the section <a href="#DataStorage"> + Designing Data Storage</a>. + </dd> + </dl> + </li> + <li> + Define a concrete implementation of the {@link android.content.ContentProvider} class and + its required methods. This class is the interface between your data and the rest of the + Android system. For more information about this class, see the section + <a href="#ContentProvider">Implementing the ContentProvider Class</a>. + </li> + <li> + Define the provider's authority string, its content URIs, and column names. If you want + the provider's application to handle intents, also define intent actions, extras data, + and flags. Also define the permissions that you will require for applications that want + to access your data. You should consider defining all of these values as constants in a + separate contract class; later, you can expose this class to other developers. For more + information about content URIs, see the + section <a href="#ContentURI">Designing Content URIs</a>. + For more information about intents, see the + section <a href="#Intents">Intents and Data Access</a>. + </li> + <li> + Add other optional pieces, such as sample data or an implementation + of {@link android.content.AbstractThreadedSyncAdapter} that can synchronize data between + the provider and cloud-based data. + </li> +</ol> + + +<!-- Designing Data Storage --> +<h2 id="DataStorage">Designing Data Storage</h2> +<p> + A content provider is the interface to data saved in a structured format. Before you create + the interface, you must decide how to store the data. You can store the data in any form you + like, and then design the interface to read and write the data as necessary. +</p> +<p> + These are some of the data storage technologies that are available in Android: +</p> +<ul> + <li> + The Android system includes an SQLite database API that Android's own providers use + to store table-oriented data. The + {@link android.database.sqlite.SQLiteOpenHelper} class helps you create databases, and the + {@link android.database.sqlite.SQLiteDatabase} class is the base class for accessing + databases. + <p> + Remember that you don't have to use a database to implement your repository. A provider + appears externally as a set of tables, similar to a relational database, but this is + not a requirement for the provider's internal implementation. + </p> + </li> + <li> + For storing file data, Android has a variety of file-oriented APIs. + To learn more about file storage, read the topic + <a href="{@docRoot}guide/topics/data/data-storage.html">Data Storage</a>. If you're + designing a provider that offers media-related data such as music or videos, you can + have a provider that combines table data and files. + </li> + <li> + For working with network-based data, use classes in {@link java.net} and + {@link android.net}. You can also synchronize network-based data to a local data + store such as a database, and then offer the data as tables or files. + The <a href="{@docRoot}resources/samples/SampleSyncAdapter/index.html"> + Sample Sync Adapter</a> sample application demonstrates this type of synchronization. + </li> +</ul> +<h3 id="DataDesign"> + Data design considerations +</h3> +<p> + Here are some tips for designing your provider's data structure: +</p> +<ul> + <li> + Table data should always have a "primary key" column that the provider maintains + as a unique numeric value for each row. You can use this value to link the row to related + rows in other tables (using it as a "foreign key"). Although you can use any name + for this column, using {@link android.provider.BaseColumns#_ID BaseColumns._ID} is the best + choice, because linking the results of a provider query to a + {@link android.widget.ListView} requires one of the retrieved columns to have the name + <code>_ID</code>. + </li> + <li> + If you want to provide bitmap images or other very large pieces of file-oriented data, store + the data in a file and then provide it indirectly rather than storing it directly in a + table. If you do this, you need to tell users of your provider that they need to use a + {@link android.content.ContentResolver} file method to access the data. + </li> + <li> + Use the Binary Large OBject (BLOB) data type to store data that varies in size or has a + varying structure. For example, you can use a BLOB column to store a + <a href="http://code.google.com/p/protobuf">protocol buffer</a> or + <a href="http://www.json.org">JSON structure</a>. + <p> + You can also use a BLOB to implement a <em>schema-independent</em> table. In + this type of table, you define a primary key column, a MIME type column, and one or + more generic columns as BLOB. The meaning of the data in the BLOB columns is indicated + by the value in the MIME type column. This allows you to store different row types in + the same table. The Contacts Provider's "data" table + {@link android.provider.ContactsContract.Data} is an example of a schema-independent + table. + </p> + </li> +</ul> +<!-- Designing Content URIs --> +<h2 id="ContentURI">Designing Content URIs</h2> +<p> + A <strong>content URI</strong> is a URI that identifies data in a provider. Content URIs include + the symbolic name of the entire provider (its <strong>authority</strong>) and a + name that points to a table or file (a <strong>path</strong>). The optional id part points to + an individual row in a table. Every data access method of + {@link android.content.ContentProvider} has a content URI as an argument; this allows you to + determine the table, row, or file to access. +</p> +<p> + The basics of content URIs are described in the topic + <a href="{@docRoot}guide/topics/providers/content-provider-basics.html"> + Content Provider Basics</a>. +</p> +<h3>Designing an authority</h3> +<p> + A provider usually has a single authority, which serves as its Android-internal name. To + avoid conflicts with other providers, you should use Internet domain ownership (in reverse) + as the basis of your provider authority. Because this recommendation is also true for Android + package names, you can define your provider authority as an extension of the name + of the package containing the provider. For example, if your Android package name is + <code>com.example.<appname></code>, you should give your provider the + authority <code>com.example.<appname>.provider</code>. +</p> +<h3>Designing a path structure</h3> +<p> + Developers usually create content URIs from the authority by appending paths that point to + individual tables. For example, if you have two tables <em>table1</em> and + <em>table2</em>, you combine the authority from the previous example to yield the + content URIs + <code>com.example.<appname>.provider/table1</code> and + <code>com.example.<appname>.provider/table2</code>. Paths aren't + limited to a single segment, and there doesn't have to be a table for each level of the path. +</p> +<h3>Handling content URI IDs</h3> +<p> + By convention, providers offer access to a single row in a table by accepting a content URI + with an ID value for the row at the end of the URI. Also by convention, providers match the + ID value to the table's <code>_ID</code> column, and perform the requested access against the + row that matches. +</p> +<p> + This convention facilitates a common design pattern for apps accessing a provider. The app + does a query against the provider and displays the resulting {@link android.database.Cursor} + in a {@link android.widget.ListView} using a {@link android.widget.CursorAdapter}. + The definition of {@link android.widget.CursorAdapter} requires one of the columns in the + {@link android.database.Cursor} to be <code>_ID</code> +</p> +<p> + The user then picks one of the displayed rows from the UI in order to look at or modify the + data. The app gets the corresponding row from the {@link android.database.Cursor} backing the + {@link android.widget.ListView}, gets the <code>_ID</code> value for this row, appends it to + the content URI, and sends the access request to the provider. The provider can then do the + query or modification against the exact row the user picked. +</p> +<h3>Content URI patterns</h3> +<p> + To help you choose which action to take for an incoming content URI, the provider API includes + the convenience class {@link android.content.UriMatcher}, which maps content URI "patterns" to + integer values. You can use the integer values in a <code>switch</code> statement that + chooses the desired action for the content URI or URIs that match a particular pattern. +</p> +<p> + A content URI pattern matches content URIs using wildcard characters: +</p> + <ul> + <li> + <strong><code>*</code>:</strong> Matches a string of any valid characters of any length. + </li> + <li> + <strong><code>#</code>:</strong> Matches a string of numeric characters of any length. + </li> + </ul> +<p> + As an example of designing and coding content URI handling, consider a provider with the + authority <code>com.example.app.provider</code> that recognizes the following content URIs + pointing to tables: +</p> +<ul> + <li> + <code>content://com.example.app.provider/table1</code>: A table called <code>table1</code>. + </li> + <li> + <code>content://com.example.app.provider/table2/dataset1</code>: A table called + <code>dataset1</code>. + </li> + <li> + <code>content://com.example.app.provider/table2/dataset2</code>: A table called + <code>dataset2</code>. + </li> + <li> + <code>content://com.example.app.provider/table3</code>: A table called <code>table3</code>. + </li> +</ul> +<p> + The provider also recognizes these content URIs if they have a row ID appended to them, as + for example <code>content://com.example.app.provider/table3/1</code> for the row identified by + <code>1</code> in <code>table3</code>. +</p> +<p> + The following content URI patterns would be possible: +</p> +<dl> + <dt> + <code>content://com.example.app.provider/*</code> + </dt> + <dd> + Matches any content URI in the provider. + </dd> + <dt> + <code>content://com.example.app.provider/table2/*</code>: + </dt> + <dd> + Matches a content URI for the tables <code>dataset1</code> + and <code>dataset2</code>, but doesn't match content URIs for <code>table1</code> or + <code>table3</code>. + </dd> + <dt> + <code>content://com.example.app.provider/table3/#</code>: Matches a content URI + for single rows in <code>table3</code>, such as + <code>content://com.example.app.provider/table3/6</code> for the row identified by + <code>6</code>. + </dt> +</dl> +<p> + The following code snippet shows how the methods in {@link android.content.UriMatcher} work. + This code handles URIs for an entire table differently from URIs for a + single row, by using the content URI pattern + <code>content://<authority>/<path></code> for tables, and + <code>content://<authority>/<path>/<id></code> for single rows. +</p> +<p> + The method {@link android.content.UriMatcher#addURI(String, String, int) addURI()} maps an + authority and path to an integer value. The method android.content.UriMatcher#match(Uri) + match()} returns the integer value for a URI. A <code>switch</code> statement + chooses between querying the entire table, and querying for a single record: +</p> +<pre class="prettyprint"> +public class ExampleProvider extends ContentProvider { +... + // Creates a UriMatcher object. + private static final UriMatcher sUriMatcher; +... + /* + * The calls to addURI() go here, for all of the content URI patterns that the provider + * should recognize. For this snippet, only the calls for table 3 are shown. + */ +... + /* + * Sets the integer value for multiple rows in table 3 to 1. Notice that no wildcard is used + * in the path + */ + sUriMatcher.addURI("com.example.app.provider", "table3", 1); + + /* + * Sets the code for a single row to 2. In this case, the "#" wildcard is + * used. "content://com.example.app.provider/table3/3" matches, but + * "content://com.example.app.provider/table3 doesn't. + */ + sUriMatcher.addURI("com.example.app.provider", "table3/#", 2); +... + // Implements ContentProvider.query() + public Cursor query( + Uri uri, + String[] projection, + String selection, + String[] selectionArgs, + String sortOrder) { +... + /* + * Choose the table to query and a sort order based on the code returned for the incoming + * URI. Here, too, only the statements for table 3 are shown. + */ + switch (sUriMatcher.match(uri)) { + + + // If the incoming URI was for all of table3 + case 1: + + if (TextUtils.isEmpty(sortOrder)) sortOrder = "_ID ASC"; + break; + + // If the incoming URI was for a single row + case 2: + + /* + * Because this URI was for a single row, the _ID value part is + * present. Get the last path segment from the URI; this is the _ID value. + * Then, append the value to the WHERE clause for the query + */ + selection = selection + "_ID = " uri.getLastPathSegment(); + break; + + default: + ... + // If the URI is not recognized, you should do some error handling here. + } + // call the code to actually do the query + } +</pre> +<p> + Another class, {@link android.content.ContentUris}, provides convenience methods for working + with the <code>id</code> part of content URIs. The classes {@link android.net.Uri} and + {@link android.net.Uri.Builder} include convenience methods for parsing existing + {@link android.net.Uri} objects and building new ones. +</p> + +<!-- Implementing the ContentProvider class --> +<h2 id="ContentProvider">Implementing the ContentProvider Class</h2> +<p> + The {@link android.content.ContentProvider} instance manages access + to a structured set of data by handling requests from other applications. All forms + of access eventually call {@link android.content.ContentResolver}, which then calls a concrete + method of {@link android.content.ContentProvider} to get access. +</p> +<h3 id="RequiredAccess">Required methods</h3> +<p> + The abstract class {@link android.content.ContentProvider} defines six abstract methods that + you must implement as part of your own concrete subclass. All of these methods except + {@link android.content.ContentProvider#onCreate() onCreate()} are called by a client application + that is attempting to access your content provider: +</p> +<dl> + <dt> + {@link android.content.ContentProvider#query(Uri, String[], String, String[], String) + query()} + </dt> + <dd> + Retrieve data from your provider. Use the arguments to select the table to + query, the rows and columns to return, and the sort order of the result. + Return the data as a {@link android.database.Cursor} object. + </dd> + <dt> + {@link android.content.ContentProvider#insert(Uri, ContentValues) insert()} + </dt> + <dd> + Insert a new row into your provider. Use the arguments to select the + destination table and to get the column values to use. Return a content URI for the + newly-inserted row. + </dd> + <dt> + {@link android.content.ContentProvider#update(Uri, ContentValues, String, String[]) + update()} + </dt> + <dd> + Update existing rows in your provider. Use the arguments to select the table and rows + to update and to get the updated column values. Return the number of rows updated. + </dd> + <dt> + {@link android.content.ContentProvider#delete(Uri, String, String[]) delete()} + </dt> + <dd> + Delete rows from your provider. Use the arguments to select the table and the rows to + delete. Return the number of rows deleted. + </dd> + <dt> + {@link android.content.ContentProvider#getType(Uri) getType()} + </dt> + <dd> + Return the MIME type corresponding to a content URI. This method is described in more + detail in the section <a href="#MIMETypes">Implementing Content Provider MIME Types</a>. + </dd> + <dt> + {@link android.content.ContentProvider#onCreate() onCreate()} + </dt> + <dd> + Initialize your provider. The Android system calls this method immediately after it + creates your provider. Notice that your provider is not created until a + {@link android.content.ContentResolver} object tries to access it. + </dd> +</dl> +<p> + Notice that these methods have the same signature as the identically-named + {@link android.content.ContentResolver} methods. +</p> +<p> + Your implementation of these methods should account for the following: +</p> +<ul> + <li> + All of these methods except {@link android.content.ContentProvider#onCreate() onCreate()} + can be called by multiple threads at once, so they must be thread-safe. To learn + more about multiple threads, see the topic + <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html"> + Processes and Threads</a>. + </li> + <li> + Avoid doing lengthy operations in {@link android.content.ContentProvider#onCreate() + onCreate()}. Defer initialization tasks until they are actually needed. + The section <a href="#OnCreate">Implementing the onCreate() method</a> + discusses this in more detail. + </li> + <li> + Although you must implement these methods, your code does not have to do anything except + return the expected data type. For example, you may want to prevent other applications + from inserting data into some tables. To do this, you can ignore the call to + {@link android.content.ContentProvider#insert(Uri, ContentValues) insert()} and return + 0. + </li> +</ul> +<h3 id="Query">Implementing the query() method</h3> +<p> + The + {@link android.content.ContentProvider#query(Uri, String[], String, String[], String) + ContentProvider.query()} method must return a {@link android.database.Cursor} object, or if it + fails, throw an {@link java.lang.Exception}. If you are using an SQLite database as your data + storage, you can simply return the {@link android.database.Cursor} returned by one of the + <code>query()</code> methods of the {@link android.database.sqlite.SQLiteDatabase} class. + If the query does not match any rows, you should return a {@link android.database.Cursor} + instance whose {@link android.database.Cursor#getCount()} method returns 0. + You should return <code>null</code> only if an internal error occurred during the query process. +</p> +<p> + If you aren't using an SQLite database as your data storage, use one of the concrete subclasses + of {@link android.database.Cursor}. For example, the {@link android.database.MatrixCursor} class + implements a cursor in which each row is an array of {@link java.lang.Object}. With this class, + use {@link android.database.MatrixCursor#addRow(Object[]) addRow()} to add a new row. +</p> +<p> + Remember that the Android system must be able to communicate the {@link java.lang.Exception} + across process boundaries. Android can do this for the following exceptions that may be useful + in handling query errors: +</p> +<ul> + <li> + {@link java.lang.IllegalArgumentException} (You may choose to throw this if your provider + receives an invalid content URI) + </li> + <li> + {@link java.lang.NullPointerException} + </li> +</ul> +<h3 id="Insert">Implementing the insert() method</h3> +<p> + The {@link android.content.ContentProvider#insert(Uri, ContentValues) insert()} method adds a + new row to the appropriate table, using the values in the {@link android.content.ContentValues} + argument. If a column name is not in the {@link android.content.ContentValues} argument, you + may want to provide a default value for it either in your provider code or in your database + schema. +</p> +<p> + This method should return the content URI for the new row. To construct this, append the new + row's <code>_ID</code> (or other primary key) value to the table's content URI, using + {@link android.content.ContentUris#withAppendedId(Uri, long) withAppendedId()}. +</p> +<h3 id="Delete">Implementing the delete() method</h3> +<p> + The {@link android.content.ContentProvider#delete(Uri, String, String[]) delete()} method + does not have to physically delete rows from your data storage. If you are using a sync adapter + with your provider, you should consider marking a deleted row + with a "delete" flag rather than removing the row entirely. The sync adapter can + check for deleted rows and remove them from the server before deleting them from the provider. +</p> +<h3 id="Update">Implementing the update() method</h3> +<p> + The {@link android.content.ContentProvider#update(Uri, ContentValues, String, String[]) + update()} method takes the same {@link android.content.ContentValues} argument used by + {@link android.content.ContentProvider#insert(Uri, ContentValues) insert()}, and the + same <code>selection</code> and <code>selectionArgs</code> arguments used by + {@link android.content.ContentProvider#delete(Uri, String, String[]) delete()} and + {@link android.content.ContentProvider#query(Uri, String[], String, String[], String) + ContentProvider.query()}. This may allow you to re-use code between these methods. +</p> +<h3 id="OnCreate">Implementing the onCreate() method</h3> +<p> + The Android system calls {@link android.content.ContentProvider#onCreate() + onCreate()} when it starts up the provider. You should perform only fast-running initialization + tasks in this method, and defer database creation and data loading until the provider actually + receives a request for the data. If you do lengthy tasks in + {@link android.content.ContentProvider#onCreate() onCreate()}, you will slow down your + provider's startup. In turn, this will slow down the response from the provider to other + applications. +</p> +<p> + For example, if you are using an SQLite database you can create + a new {@link android.database.sqlite.SQLiteOpenHelper} object in + {@link android.content.ContentProvider#onCreate() ContentProvider.onCreate()}, + and then create the SQL tables the first time you open the database. To facilitate this, the + first time you call {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase + getWritableDatabase()}, it automatically calls the + {@link android.database.sqlite.SQLiteOpenHelper#onCreate(SQLiteDatabase) + SQLiteOpenHelper.onCreate()} method. +</p> +<p> + The following two snippets demonstrate the interaction between + {@link android.content.ContentProvider#onCreate() ContentProvider.onCreate()} and + {@link android.database.sqlite.SQLiteOpenHelper#onCreate(SQLiteDatabase) + SQLiteOpenHelper.onCreate()}. The first snippet is the implementation of + {@link android.content.ContentProvider#onCreate() ContentProvider.onCreate()}: +</p> +<pre class="prettyprint"> +public class ExampleProvider extends ContentProvider + + /* + * Defines a handle to the database helper object. The MainDatabaseHelper class is defined + * in a following snippet. + */ + private MainDatabaseHelper mOpenHelper; + + // Defines the database name + private static final String DBNAME = "mydb"; + + // Holds the database object + private SQLiteDatabase db; + + public boolean onCreate() { + + /* + * Creates a new helper object. This method always returns quickly. + * Notice that the database itself isn't created or opened + * until SQLiteOpenHelper.getWritableDatabase is called + */ + mOpenHelper = new SQLiteOpenHelper( + getContext(), // the application context + DBNAME, // the name of the database) + null, // uses the default SQLite cursor + 1 // the version number + ); + + return true; + } + + ... + + // Implements the provider's insert method + public Cursor insert(Uri uri, ContentValues values) { + // Insert code here to determine which table to open, handle error-checking, and so forth + + ... + + /* + * Gets a writeable database. This will trigger its creation if it doesn't already exist. + * + */ + db = mOpenHelper.getWritableDatabase(); + } +} +</pre> +<p> + The next snippet is the implementation of + {@link android.database.sqlite.SQLiteOpenHelper#onCreate(SQLiteDatabase) + SQLiteOpenHelper.onCreate()}, including a helper class: +</p> +<pre class="prettyprint"> +... +// A string that defines the SQL statement for creating a table +private static final String SQL_CREATE_MAIN = "CREATE TABLE " + + "main " + // Table's name + "(" + // The columns in the table + " _ID INTEGER PRIMARY KEY, " + + " WORD TEXT" + " FREQUENCY INTEGER " + + " LOCALE TEXT )"; +... +/** + * Helper class that actually creates and manages the provider's underlying data repository. + */ +protected static final class MainDatabaseHelper extends SQLiteOpenHelper { + + /* + * Instantiates an open helper for the provider's SQLite data repository + * Do not do database creation and upgrade here. + */ + MainDatabaseHelper(Context context) { + super(context, DBNAME, null, 1); + } + + /* + * Creates the data repository. This is called when the provider attempts to open the + * repository and SQLite reports that it doesn't exist. + */ + public void onCreate(SQLiteDatabase db) { + + // Creates the main table + db.execSQL(SQL_CREATE_MAIN); + } +} +</pre> + + +<!-- Implementing ContentProvider MIME Types --> +<h2 id="MIMETypes">Implementing ContentProvider MIME Types</h2> +<p> + The {@link android.content.ContentProvider} class has two methods for returning MIME types: +</p> +<dl> + <dt> + {@link android.content.ContentProvider#getType(Uri) getType()} + </dt> + <dd> + One of the required methods that you must implement for any provider. + </dd> + <dt> + {@link android.content.ContentProvider#getStreamTypes(Uri, String) getStreamTypes()} + </dt> + <dd> + A method that you're expected to implement if your provider offers files. + </dd> +</dl> +<h3 id="TableMIMETypes">MIME types for tables</h3> +<p> + The {@link android.content.ContentProvider#getType(Uri) getType()} method returns a + {@link java.lang.String} in MIME format that describes the type of data returned by the content + URI argument. The {@link android.net.Uri} argument can be a pattern rather than a specific URI; + in this case, you should return the type of data associated with content URIs that match the + pattern. +</p> +<p> + For common types of data such as as text, HTML, or JPEG, + {@link android.content.ContentProvider#getType(Uri) getType()} should return the standard + MIME type for that data. A full list of these standard types is available on the + <a href="http://www.iana.org/assignments/media-types/index.htm">IANA MIME Media Types</a> + website. +</p> +<p> + For content URIs that point to a row or rows of table data, + {@link android.content.ContentProvider#getType(Uri) getType()} should return + a MIME type in Android's vendor-specific MIME format: +</p> +<ul> + <li> + Type part: <code>vnd</code> + </li> + <li> + Subtype part: + <ul> + <li> + If the URI pattern is for a single row: <code>android.cursor.<strong>item</strong>/</code> + </li> + <li> + If the URI pattern is for more than one row: <code>android.cursor.<strong>dir</strong>/</code> + </li> + </ul> + </li> + <li> + Provider-specific part: <code>vnd.<name></code>.<code><type></code> + <p> + You supply the <code><name></code> and <code><type></code>. + The <code><name></code> value should be globally unique, + and the <code><type></code> value should be unique to the corresponding URI + pattern. A good choice for <code><name></code> is your company's name or + some part of your application's Android package name. A good choice for the + <code><type></code> is a string that identifies the table associated with the + URI. + </p> + + </li> +</ul> +<p> + For example, if a provider's authority is + <code>com.example.app.provider</code>, and it exposes a table named + <code>table1</code>, the MIME type for multiple rows in <code>table1</code> is: +</p> +<pre> +vnd.android.cursor.<strong>dir</strong>/vnd.com.example.provider.table1 +</pre> +<p> + For a single row of <code>table1</code>, the MIME type is: +</p> +<pre> +vnd.android.cursor.<strong>item</strong>/vnd.com.example.provider.table1 +</pre> +<h3 id="FileMIMETypes">MIME types for files</h3> +<p> + If your provider offers files, implement + {@link android.content.ContentProvider#getStreamTypes(Uri, String) getStreamTypes()}. + The method returns a {@link java.lang.String} array of MIME types for the files your provider + can return for a given content URI. You should filter the MIME types you offer by the MIME type + filter argument, so that you return only those MIME types that the client wants to handle. +</p> +<p> + For example, consider a provider that offers photo images as files in <code>.jpg</code>, + <code>.png</code>, and <code>.gif</code> format. + If an application calls {@link android.content.ContentResolver#getStreamTypes(Uri, String) + ContentResolver.getStreamTypes()} with the filter string <code>image/*</code> (something that + is an "image"), + then the {@link android.content.ContentProvider#getStreamTypes(Uri, String) + ContentProvider.getStreamTypes()} method should return the array: +</p> +<pre> +{ "image/jpeg", "image/png", "image/gif"} +</pre> +<p> + If the app is only interested in <code>.jpg</code> files, then it can call + {@link android.content.ContentResolver#getStreamTypes(Uri, String) + ContentResolver.getStreamTypes()} with the filter string <code>*\/jpeg</code>, and + {@link android.content.ContentProvider#getStreamTypes(Uri, String) + ContentProvider.getStreamTypes()} should return: +<pre> +{"image/jpeg"} +</pre> +<p> + If your provider doesn't offer any of the MIME types requested in the filter string, + {@link android.content.ContentProvider#getStreamTypes(Uri, String) getStreamTypes()} + should return <code>null</code>. +</p> + + +<!-- Implementing a Contract Class --> +<h2 id="ContractClass">Implementing a Contract Class</h2> +<p> + A contract class is a <code>public final</code> class that contains constant definitions for the + URIs, column names, MIME types, and other meta-data that pertain to the provider. The class + establishes a contract between the provider and other applications by ensuring that the provider + can be correctly accessed even if there are changes to the actual values of URIs, column names, + and so forth. +</p> +<p> + A contract class also helps developers because it usually has mnemonic names for its constants, + so developers are less likely to use incorrect values for column names or URIs. Since it's a + class, it can contain Javadoc documentation. Integrated development environments such as + Eclipse can auto-complete constant names from the contract class and display Javadoc for the + constants. +</p> +<p> + Developers can't access the contract class's class file from your application, but they can + statically compile it into their application from a <code>.jar</code> file you provide. +</p> +<p> + The {@link android.provider.ContactsContract} class and its nested classes are examples of + contract classes. +</p> +<h2 id="Permissions">Implementing Content Provider Permissions</h2> +<p> + Permissions and access for all aspects of the Android system are described in detail in the + topic <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a>. + The topic <a href="{@docRoot}guide/topics/data/data-storage.html">Data Storage</a> also + described the security and permissions in effect for various types of storage. + In brief, the important points are: +</p> +<ul> + <li> + By default, data files stored on the device's internal storage are private to your + application and provider. + </li> + <li> + {@link android.database.sqlite.SQLiteDatabase} databases you create are private to your + application and provider. + </li> + <li> + By default, data files that you save to external storage are <em>public</em> and + <em>world-readable</em>. You can't use a content provider to restrict access to files in + external storage, because other applications can use other API calls to read and write them. + </li> + <li> + The method calls for opening or creating files or SQLite databases on your device's internal + storage can potentially give both read and write access to all other applications. If you + use an internal file or database as your provider's repository, and you give it + "world-readable" or "world-writeable" access, the permissions you set for your provider in + its manifest won't protect your data. The default access for files and databases in + internal storage is "private", and for your provider's repository you shouldn't change this. + </li> +</ul> +<p> + If you want to use content provider permissions to control access to your data, then you should + store your data in internal files, SQLite databases, or the "cloud" (for example, + on a remote server), and you should keep files and databases private to your application. +</p> +<h3>Implementing permissions</h3> +<p> + All applications can read from or write to your provider, even if the underlying data is + private, because by default your provider does not have permissions set. To change this, + set permissions for your provider in your manifest file, using attributes or child + elements of the <code><a href="{@docRoot}guide/topics/manifest/provider-element.html"> + <provider></a></code> element. You can set permissions that apply to the entire provider, + or to certain tables, or even to certain records, or all three. +</p> +<p> + You define permissions for your provider with one or more + <code><a href="{@docRoot}guide/topics/manifest/permission-element.html"> + <permission></a></code> elements in your manifest file. To make the + permission unique to your provider, use Java-style scoping for the + <code><a href="{@docRoot}guide/topics/manifest/permission-element.html#nm"> + android:name</a></code> attribute. For example, name the read permission + <code>com.example.app.provider.permission.READ_PROVIDER</code>. + +</p> +<p> + The following list describes the scope of provider permissions, starting with the + permissions that apply to the entire provider and then becoming more fine-grained. + More fine-grained permissions take precedence over ones with larger scope: +</p> +<dl> + <dt> + Single read-write provider-level permission + </dt> + <dd> + One permission that controls both read and write access to the entire provider, specified + with the <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#prmsn"> + android:permission</a></code> attribute of the + <code><a href="{@docRoot}guide/topics/manifest/provider-element.html"> + <provider></a></code> element. + </dd> + <dt> + Separate read and write provider-level permission + </dt> + <dd> + A read permission and a write permission for the entire provider. You specify them + with the <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#rprmsn"> + android:readPermission</a></code> and + <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#wprmsn"> + android:writePermission</a></code> attributes of the + <code><a href="{@docRoot}guide/topics/manifest/provider-element.html"> + <provider></a></code> element. They take precedence over the permission required by + <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#prmsn"> + android:permission</a></code>. + </dd> + <dt> + Path-level permission + </dt> + <dd> + Read, write, or read/write permission for a content URI in your provider. You specify + each URI you want to control with a + <code><a href="{@docRoot}guide/topics/manifest/path-permission-element.html"> + <path-permission></a></code> child element of the + <code><a href="{@docRoot}guide/topics/manifest/provider-element.html"> + <provider></a></code> element. For each content URI you specify, you can specify a + read/write permission, a read permission, or a write permission, or all three. The read and + write permissions take precedence over the read/write permission. Also, path-level + permission takes precedence over provider-level permissions. + </dd> + <dt> + Temporary permission + </dt> + <dd> + A permission level that grants temporary access to an application, even if the application + doesn't have the permissions that are normally required. The temporary + access feature reduces the number of permissions an application has to request in + its manifest. When you turn on temporary permissions, the only applications that need + "permanent" permissions for your provider are ones that continually access all + your data. + <p> + Consider the permissions you need to implement an email provider and app, when you + want to allow an outside image viewer application to display photo attachments from your + provider. To give the image viewer the necessary access without requiring permissions, + set up temporary permissions for content URIs for photos. Design your email app so + that when the user wants to display a photo, the app sends an intent containing the + photo's content URI and permission flags to the image viewer. The image viewer can + then query your email provider to retrieve the photo, even though the viewer doesn't + have the normal read permission for your provider. + </p> + <p> + To turn on temporary permissions, either set the + <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#gprmsn"> + android:grantUriPermissions</a></code> attribute of the + <code><a href="{@docRoot}guide/topics/manifest/provider-element.html"> + <provider></a></code> element, or add one or more + <code><a href="{@docRoot}guide/topics/manifest/grant-uri-permission-element.html"> + <grant-uri-permission></a></code> child elements to your + <code><a href="{@docRoot}guide/topics/manifest/provider-element.html"> + <provider></a></code> element. If you use temporary permissions, you have to call + {@link android.content.Context#revokeUriPermission(Uri, int) + Context.revokeUriPermission()} whenever you remove support for a content URI from your + provider, and the content URI is associated with a temporary permission. + </p> + <p> + The attribute's value determines how much of your provider is made accessible. + If the attribute is set to <code>true</code>, then the system will grant temporary + permission to your entire provider, overriding any other permissions that are required + by your provider-level or path-level permissions. + </p> + <p> + If this flag is set to <code>false</code>, then you must add + <code><a href="{@docRoot}guide/topics/manifest/grant-uri-permission-element.html"> + <grant-uri-permission></a></code> child elements to your + <code><a href="{@docRoot}guide/topics/manifest/provider-element.html"> + <provider></a></code> element. Each child element specifies the content URI or + URIs for which temporary access is granted. + </p> + <p> + To delegate temporary access to an application, an intent must contain + the {@link android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION} or the + {@link android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION} flags, or both. These + are set with the {@link android.content.Intent#setFlags(int) setFlags()} method. + </p> + <p> + If the <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#gprmsn"> + android:grantUriPermissions</a></code> attribute is not present, it's assumed to be + <code>false</code>. + </p> + </dd> +</dl> + + + +<!-- The Provider Element --> +<h2 id="ProviderElement">The <provider> Element</h2> +<p> + Like {@link android.app.Activity} and {@link android.app.Service} components, + a subclass of {@link android.content.ContentProvider} + must be defined in the manifest file for its application, using the + <code><a href="{@docRoot}guide/topics/manifest/provider-element.html"> + <provider></a></code> element. The Android system gets the following information from + the element: +<dl> + <dt> + Authority + (<a href="{@docRoot}guide/topics/manifest/provider-element.html#auth">{@code + android:authorities}</a>) + </dt> + <dd> + Symbolic names that identify the entire provider within the system. This + attribute is described in more detail in the section + <a href="#ContentURI">Designing Content URIs</a>. + </dd> + <dt> + Provider class name + (<code> +<a href="{@docRoot}guide/topics/manifest/provider-element.html#nm">android:name</a> + </code>) + </dt> + <dd> + The class that implements {@link android.content.ContentProvider}. This class is + described in more detail in the section + <a href="#ContentProvider">Implementing the ContentProvider Class</a>. + </dd> + <dt> + Permissions + </dt> + <dd> + Attributes that specify the permissions that other applications must have in order to access + the provider's data: + <ul> + <li> + <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#gprmsn"> + android:grantUriPermssions</a></code>: Temporary permission flag. + </li> + <li> + <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#prmsn"> + android:permission</a></code>: Single provider-wide read/write permission. + </li> + <li> + <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#rprmsn"> + android:readPermission</a></code>: Provider-wide read permission. + </li> + <li> + <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#wprmsn"> + android:writePermission</a></code>: Provider-wide write permission. + </li> + </ul> + <p> + Permissions and their corresponding attributes are described in more + detail in the section + <a href="#Permissions">Implementing Content Provider Permissions</a>. + </p> + </dd> + <dt> + Startup and control attributes + </dt> + <dd> + These attributes determine how and when the Android system starts the provider, the + process characteristics of the provider, and other run-time settings: + <ul> + <li> + <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#enabled"> + android:enabled</a></code>: Flag allowing the system to start the provider. + </li> + <li> + <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#exported"> + android:exported</a></code>: Flag allowing other applications to use this provider. + </li> + <li> + <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#init"> + android:initOrder</a></code>: The order in which this provider should be started, + relative to other providers in the same process. + </li> + <li> + <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#multi"> + android:multiProcess</a></code>: Flag allowing the system to start the provider + in the same process as the calling client. + </li> + <li> + <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#proc"> + android:process</a></code>: The name of the process in which the provider should + run. + </li> + <li> + <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#sync"> + android:syncable</a></code>: Flag indicating that the provider's data is to be + sync'ed with data on a server. + </li> + </ul> + <p> + The attributes are fully documented in the dev guide topic for the + <code><a href="{@docRoot}guide/topics/manifest/provider-element.html"> + <provider></a></code> + element. + </p> + </dd> + <dt> + Informational attributes + </dt> + <dd> + An optional icon and label for the provider: + <ul> + <li> + <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#icon"> + android:icon</a></code>: A drawable resource containing an icon for the provider. + The icon appears next to the provider's label in the list of apps in + <em>Settings</em> > <em>Apps</em> > <em>All</em>. + </li> + <li> + <code><a href="{@docRoot}guide/topics/manifest/provider-element.html#label"> + android:label</a></code>: An informational label describing the provider or its + data, or both. The label appears in the list of apps in + <em>Settings</em> > <em>Apps</em> > <em>All</em>. + </li> + </ul> + <p> + The attributes are fully documented in the dev guide topic for the + <code><a href="{@docRoot}guide/topics/manifest/provider-element.html"> + <provider></a></code> element. + </p> + </dd> +</dl> + +<!-- Intent Access --> +<h2 id="Intents">Intents and Data Access</h2> +<p> + Applications can access a content provider indirectly with an {@link android.content.Intent}. + The application does not call any of the methods of {@link android.content.ContentResolver} or + {@link android.content.ContentProvider}. Instead, it sends an intent that starts an activity, + which is often part of the provider's own application. The destination activity is in charge of + retrieving and displaying the data in its UI. Depending on the action in the intent, the + destination activity may also prompt the user to make modifications to the provider's data. + An intent may also contain "extras" data that the destination activity displays + in the UI; the user then has the option of changing this data before using it to modify the + data in the provider. +</p> +<p> + +</p> +<p> + You may want to use intent access to help ensure data integrity. Your provider may depend + on having data inserted, updated, and deleted according to strictly defined business logic. If + this is the case, allowing other applications to directly modify your data may lead to + invalid data. If you want developers to use intent access, be sure to document it thoroughly. + Explain to them why intent access using your own application's UI is better than trying to + modify the data with their code. +</p> +<p> + Handling an incoming intent that wishes to modify your provider's data is no different from + handling other intents. You can learn more about using intents by reading the topic + <a href="{@docRoot}guide/topics/intents/intents-filters.html">Intents and Intent Filters</a>. +</p> diff --git a/docs/html/guide/topics/providers/content-providers.jd b/docs/html/guide/topics/providers/content-providers.jd index 95331ce..1707f03 100644 --- a/docs/html/guide/topics/providers/content-providers.jd +++ b/docs/html/guide/topics/providers/content-providers.jd @@ -1,922 +1,96 @@ page.title=Content Providers @jd:body - <div id="qv-wrapper"> <div id="qv"> -<h2>In this document</h2> -<ol> -<li><a href="#basics">Content provider basics</a></li> -<li><a href="#querying">Querying a content provider</a></li> -<li><a href="#modifying">Modifying data in a provider</a></li> -<li><a href="#creating">Creating a content provider</a></li> -<li><a href="#urisum">Content URI summary</a></li> -</ol> -<h2>Key classes</h2> +<!-- In this document --> +<h2>Topics</h2> <ol> -<li>{@link android.content.ContentProvider}</li> -<li>{@link android.content.ContentResolver}</li> -<li>{@link android.database.Cursor}</li> + <li> + <a href="{@docRoot}guide/topics/providers/content-provider-basics.html"> + Content Provider Basics</a> + </li> + <li> + <a href="{@docRoot}guide/topics/providers/content-provider-creating.html"> + Creating a Content Provider</a> + </li> + <li> + <a href="{@docRoot}guide/topics/providers/calendar-provider.html">Calendar Provider</a> + </li> </ol> -<h2>See also</h2> -<ol> - <li><a href="{@docRoot}guide/topics/providers/calendar-provider.html">Calendar Provider</a></li> -</ol> + <!-- Related Samples --> +<h2>Related Samples</h2> + <ol> + <li> + <a href="{@docRoot}resources/samples/ContactManager/index.html"> + Contact Manager</a> application + </li> + <li> + <a + href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/view/List2.html"> + "Cursor (People)" + </a> + </li> + <li> + <a + href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/view/List7.html"> + "Cursor (Phones)"</a> + </li> + </ol> </div> </div> - -<p> -Content providers store and retrieve data and make it accessible to all -applications. They're the only way to share data across applications; there's -no common storage area that all Android packages can access. -</p> - -<p> -Android ships with a number of content providers for common data types -(audio, video, images, personal contact information, and so on). You can -see some of them listed in the {@link android.provider android.provider} -package. You can query these providers for the data they contain (although, -for some, you must acquire the proper permission to read the data). -</p> - -<p class="note"><strong>Note:</strong> Android 4.0 introduces the Calendar -Provider. For more information, see <a -href="{@docRoot}guide/topics/providers/calendar-provider.html">Calendar -Provider</a>.</p> -<p> -If you want to make your own data public, you have two options: You can -create your own content provider (a {@link android.content.ContentProvider} -subclass) or you can add the data to an existing provider — if there's -one that controls the same type of data and you have permission to write to it. -</p> - -<p> -This document is an introduction to using content providers. After a -brief discussion of the fundamentals, it explores how to query a content -provider, how to modify data controlled by a provider, and how to create -a content provider of your own. -</p> - - -<h2><a name="basics"></a>Content Provider Basics</h2> - -<p> -How a content provider actually stores its data under the covers is -up to its designer. But all content providers implement a common interface -for querying the provider and returning results — as well as for -adding, altering, and deleting data. -</p> - -<p> -It's an interface that clients use indirectly, most generally through -{@link android.content.ContentResolver} objects. You get a ContentResolver -by calling <code>{@link android.content.Context#getContentResolver -getContentResolver()}</code> from within the implementation of an Activity -or other application component: -</p> - -<pre>ContentResolver cr = getContentResolver();</pre> - -<p> -You can then use the ContentResolver's methods to interact with whatever -content providers you're interested in. -</p> - -<p> -When a query is initiated, the Android system identifies the content provider -that's the target of the query and makes sure that it is up and running. -The system instantiates all ContentProvider objects; you never need to do it -on your own. In fact, you never deal directly with ContentProvider objects -at all. Typically, there's just a single instance of each type of -ContentProvider. But it can communicate with multiple ContentResolver objects -in different applications and processes. The interaction between processes is -handled by the ContentResolver and ContentProvider classes. -</p> - - -<h3>The data model</h3> - -<p> -Content providers expose their data as a simple table on a database model, -where each row is a record and each column is data of a particular type -and meaning. For example, information about people and their phone numbers -might be exposed as follows: -</p> - -<table> - <tr> - <th scope="col">_ID</th> - <th scope="col">NUMBER</th> - <th scope="col">NUMBER_KEY</th> - <th scope="col">LABEL</th> - <th scope="col">NAME</th> - <th scope="col">TYPE</th> - </tr> - <tr> - <td>13</td> - <td>(425) 555 6677</td> - <td>425 555 6677</td> - <td>Kirkland office</td> - <td>Bully Pulpit</td> - <td>{@code TYPE_WORK}</td> - </tr> - <tr> - <td>44</td> - <td>(212) 555-1234</td> - <td>212 555 1234</td> - <td>NY apartment</td> - <td>Alan Vain</td> - <td>{@code TYPE_HOME}</td> - </tr> - <tr> - <td>45</td> - <td>(212) 555-6657</td> - <td>212 555 6657</td> - <td>Downtown office</td> - <td>Alan Vain</td> - <td>{@code TYPE_MOBILE}</td> - </tr> - <tr> - <td>53</td> - <td>201.555.4433</td> - <td>201 555 4433</td> - <td>Love Nest</td> - <td>Rex Cars</td> - <td>{@code TYPE_HOME}</td> - </tr> -</table> - -<p> -Every record includes a numeric {@code _ID} field that uniquely identifies -the record within the table. IDs can be used to match records in related -tables — for example, to find a person's phone number in one table -and pictures of that person in another. -</p> - -<p> -A query returns a {@link android.database.Cursor} object that can move from -record to record and column to column to read the contents of each field. -It has specialized methods for reading each type of data. So, to read a field, -you must know what type of data the field contains. (There's more on query -results and Cursor objects later.) -</p> - - -<h3><a name="uri"></a>URIs</h3> - -<p> -Each content provider exposes a public URI (wrapped as a {@link android.net.Uri} -object) that uniquely identifies its data set. A content provider that controls -multiple data sets (multiple tables) exposes a separate URI for each one. All -URIs for providers begin with the string "{@code content://}". The {@code content:} -scheme identifies the data as being controlled by a content provider. -</p> - -<p> -If you're defining a content provider, it's a good idea to also define a -constant for its URI, to simplify client code and make future updates cleaner. -Android defines {@code CONTENT_URI} constants for all the providers that come -with the platform. For example, the URI for the table that matches -phone numbers to people and the URI for the table that holds pictures of -people (both controlled by the Contacts content provider) are: -</p> - -<p> -<p style="margin-left: 2em">{@code android.provider.Contacts.Phones.CONTENT_URI} -<br/>{@code android.provider.Contacts.Photos.CONTENT_URI} -</p> - -<p> -The URI constant is used in all interactions with the content provider. -Every {@link android.content.ContentResolver} method takes the URI -as its first argument. It's what identifies which provider the ContentResolver -should talk to and which table of the provider is being targeted. -</p> - - -<h2><a name="querying"></a>Querying a Content Provider</h2> - -<p> -You need three pieces of information to query a content provider: -</p> - -<ul> -<li>The URI that identifies the provider</li> -<li>The names of the data fields you want to receive</li> -<li>The data types for those fields</li> -</ul> - -<p> -If you're querying a particular record, you also need the ID for that record. -</p> - - -<h3>Making the query</h3> - -<p> -To query a content provider, you can use either the -<code>{@link android.content.ContentResolver#query ContentResolver.query()}</code> -method or the <code>{@link android.app.Activity#managedQuery -Activity.managedQuery()}</code> method. -Both methods take the same set of arguments, and both return a -Cursor object. However, {@code managedQuery()} -causes the activity to manage the life cycle of the Cursor. A managed Cursor -handles all of the niceties, such as unloading itself when the activity pauses, -and requerying itself when the activity restarts. You can ask an Activity to -begin managing an unmanaged Cursor object for you by calling -<code>{@link android.app.Activity#startManagingCursor -Activity.startManagingCursor()}</code>. -</p> - -<p> -The first argument to either <code>{@link android.content.ContentResolver#query query()}</code> -or <code>{@link android.app.Activity#managedQuery managedQuery()}</code> is the provider URI -— the {@code CONTENT_URI} constant that identifies a particular -ContentProvider and data set (see <a href="#uri">URIs</a> earlier). -</p> - -<p> -To restrict a query to just one record, you can append the {@code _ID} value for -that record to the URI — that is, place a string matching the ID as the -last segment of the path part of the URI. For example, if the ID is 23, -the URI would be: -</p> - -<p style="margin-left: 2em">{@code content://. . . ./23}</p> - -<p> -There are some helper methods, particularly -<code>{@link android.content.ContentUris#withAppendedId -ContentUris.withAppendedId()}</code> and <code>{@link -android.net.Uri#withAppendedPath Uri.withAppendedPath()}</code>, -that make it easy to append an ID to a URI. Both are static methods that return -a Uri object with the ID added. So, for example, if you were looking for record -23 in the database of people contacts, you might construct a query as follows: -</p> - -<pre> -import android.provider.Contacts.People; -import android.content.ContentUris; -import android.net.Uri; -import android.database.Cursor; - -// Use the ContentUris method to produce the base URI for the contact with _ID == 23. -Uri myPerson = ContentUris.withAppendedId(People.CONTENT_URI, 23); - -// Alternatively, use the Uri method to produce the base URI. -// It takes a string rather than an integer. -Uri myPerson = Uri.withAppendedPath(People.CONTENT_URI, "23"); - -// Then query for this specific record: -Cursor cur = managedQuery(myPerson, null, null, null, null); -</pre> - -<p> -The other arguments to the <code>{@link android.content.ContentResolver#query query()}</code> -and <code>{@link android.app.Activity#managedQuery managedQuery()}</code> methods delimit -the query in more detail. They are: -</p> - -<ul> -<li>The names of the data columns that should be returned. A {@code null} -value returns all columns. Otherwise, only columns that are listed by name -are returned. All the content providers that come with the platform define -constants for their columns. For example, the -{@link android.provider.Contacts.Phones android.provider.Contacts.Phones} class -defines constants for the names of the columns in the phone table illustrated -earlier — {@code _ID}, {@code NUMBER}, {@code NUMBER_KEY}, {@code NAME}, -and so on.</li> - -<li><p>A filter detailing which rows to return, formatted as an SQL {@code WHERE} -clause (excluding the {@code WHERE} itself). A {@code null} value returns -all rows (unless the URI limits the query to a single record).</p></li> - -<li><p>Selection arguments.</p></li> - -<li><p>A sorting order for the rows that are returned, formatted as an SQL -{@code ORDER BY} clause (excluding the {@code ORDER BY} itself). A {@code null} -value returns the records in the default order for the table, which may be -unordered.</p></li> -</ul> - -<p> -Let's look at an example query to retrieve a list of contact names and their -primary phone numbers: -</p> - -<pre> -import android.provider.Contacts.People; -import android.database.Cursor; - -// Form an array specifying which columns to return. -String[] projection = new String[] { - People._ID, - People._COUNT, - People.NAME, - People.NUMBER - }; - -// Get the base URI for the People table in the Contacts content provider. -Uri contacts = People.CONTENT_URI; - -// Make the query. -Cursor managedCursor = managedQuery(contacts, - projection, // Which columns to return - null, // Which rows to return (all rows) - null, // Selection arguments (none) - // Put the results in ascending order by name - People.NAME + " ASC"); -</pre> - -<p> -This query retrieves data from the People table of the Contacts content -provider. It gets the name, primary phone number, and unique record ID for -each contact. It also reports the number of records that are returned as -the {@code _COUNT} field of each record. -</p> - -<p> -The constants for the names of the columns are defined in various interfaces -— {@code _ID} and {@code _COUNT} in -{@link android.provider.BaseColumns BaseColumns}, {@code NAME} in {@link android.provider.Contacts.PeopleColumns PeopleColumns}, and {@code NUMBER} -in {@link android.provider.Contacts.PhonesColumns PhoneColumns}. The -{@link android.provider.Contacts.People Contacts.People} class implements -each of these interfaces, which is why the code example above could refer -to them using just the class name. -</p> - - -<h3>What a query returns</h3> - -<p> -A query returns a set of zero or more database records. The names of the -columns, their default order, and their data types are specific to each -content provider. -But every provider has an {@code _ID} column, which holds a unique numeric -ID for each record. Every provider can also report the number -of records returned as the {@code _COUNT} column; its value -is the same for all rows. -</p> - -<p> -Here is an example result set for the query in the previous section: -</p> - -<table border="1"> - <tbody> - <tr> - <th scope="col">_ID</th> - <th scope="col">_COUNT</th> - <th scope="col">NAME</th> - <th scope="col">NUMBER</th> - </tr> - <tr> - <td>44</td> - <td>3</td> - <td>Alan Vain</td> - <td>212 555 1234</td> - </tr> - <tr> - <td>13</td> - <td>3</td> - <td>Bully Pulpit</td> - <td>425 555 6677</td> - </tr> - <tr> - <td>53</td> - <td>3</td> - <td>Rex Cars</td> - <td>201 555 4433</td> - </tr> - </tbody> -</table> - -<p> -The retrieved data is exposed by a {@link android.database.Cursor Cursor} -object that can be used to iterate backward or forward through the result -set. You can use this object only to read the data. To add, modify, or -delete data, you must use a ContentResolver object. -</p> - - -<h3>Reading retrieved data</h3> - -<p> -The Cursor object returned by a query provides access to a recordset of -results. If you have queried for a specific record by ID, this set will -contain only one value. Otherwise, it can contain multiple values. -(If there are no matches, it can also be empty.) You -can read data from specific fields in the record, but you must know the -data type of the field, because the Cursor object has a separate method -for reading each type of data — such as <code>{@link -android.database.Cursor#getString getString()}</code>, <code>{@link -android.database.Cursor#getInt getInt()}</code>, and <code>{@link -android.database.Cursor#getFloat getFloat()}</code>. -(However, for most types, if you call the method for reading strings, -the Cursor object will give you the String representation of the data.) -The Cursor lets you request the column name from the index of the column, -or the index number from the column name. -</p> - -<p> -The following snippet demonstrates reading names and phone numbers from -the query illustrated earlier: -</p> - -<pre> -import android.provider.Contacts.People; - -private void getColumnData(Cursor cur){ - if (cur.moveToFirst()) { - - String name; - String phoneNumber; - int nameColumn = cur.getColumnIndex(People.NAME); - int phoneColumn = cur.getColumnIndex(People.NUMBER); - String imagePath; - - do { - // Get the field values - name = cur.getString(nameColumn); - phoneNumber = cur.getString(phoneColumn); - - // Do something with the values. - ... - - } while (cur.moveToNext()); - - } -} -</pre> - -<p> -If a query can return binary data, such as an image or sound, the data -may be directly entered in the table or the table entry for that data may be -a string specifying a {@code content:} URI that you can use to get the data. -In general, smaller amounts of data (say, from 20 to 50K or less) are most often -directly entered in the table and can be read by calling -<code>{@link android.database.Cursor#getBlob Cursor.getBlob()}</code>. -It returns a byte array. -</p> - -<p> -If the table entry is a {@code content:} URI, you should never try to open -and read the file directly (for one thing, permissions problems can make this -fail). Instead, you should call -<code>{@link android.content.ContentResolver#openInputStream -ContentResolver.openInputStream()}</code> to get an -{@link java.io.InputStream} object that you can use to read the data. -</p> - - -<h2><a name="modifying"></a>Modifying Data</h2> - -<p> -Data kept by a content provider can be modified by: -</p> - -<ul> -<p><li>Adding new records</li> -<li>Adding new values to existing records</li> -<li>Batch updating existing records</li> -<li>Deleting records</li> -</ul> - -<p> -All data modification is accomplished using {@link android.content.ContentResolver} -methods. Some content providers require a more restrictive permission for writing -data than they do for reading it. If you don't have permission to write to a -content provider, the ContentResolver methods will fail. -</p> - - -<h3>Adding records</h3> - -<p> -To add a new record to a content provider, first set up a map of key-value pairs -in a {@link android.content.ContentValues} object, where each key matches -the name of a column in the content provider and the value is the desired -value for the new record in that column. Then call <code>{@link -android.content.ContentResolver#insert ContentResolver.insert()}</code> and pass -it the URI of the provider and the ContentValues map. This method returns -the full URI of the new record — that is, the provider's URI with -the appended ID for the new record. You can then use this URI to query and -get a Cursor over the new record, and to further modify the record. -Here's an example: -</p> - -<pre> -import android.provider.Contacts.People; -import android.content.ContentResolver; -import android.content.ContentValues; - -ContentValues values = new ContentValues(); - -// Add Abraham Lincoln to contacts and make him a favorite. -values.put(People.NAME, "Abraham Lincoln"); -// 1 = the new contact is added to favorites -// 0 = the new contact is not added to favorites -values.put(People.STARRED, 1); - -Uri uri = getContentResolver().insert(People.CONTENT_URI, values); -</pre> - - -<h3>Adding new values</h3> - -<p> -Once a record exists, you can add new information to it or modify -existing information. For example, the next step in the example above would -be to add contact information — like a phone number or an IM or e-mail -address — to the new entry. -</p> - -<p> -The best way to add to a record in the Contacts database is to append -the name of the table where the new data goes to the URI for the -record, then use the amended URI to add the new data values. Each -Contacts table exposes a name for this purpose as a {@code -CONTENT_DIRECTORY} constant. The following code continues the previous -example by adding a phone number and e-mail address for the record -just created: -</p> - -<pre> -Uri phoneUri = null; -Uri emailUri = null; - -// Add a phone number for Abraham Lincoln. Begin with the URI for -// the new record just returned by insert(); it ends with the _ID -// of the new record, so we don't have to add the ID ourselves. -// Then append the designation for the phone table to this URI, -// and use the resulting URI to insert the phone number. -phoneUri = Uri.withAppendedPath(uri, People.Phones.CONTENT_DIRECTORY); - -values.clear(); -values.put(People.Phones.TYPE, People.Phones.TYPE_MOBILE); -values.put(People.Phones.NUMBER, "1233214567"); -getContentResolver().insert(phoneUri, values); - -// Now add an email address in the same way. -emailUri = Uri.withAppendedPath(uri, People.ContactMethods.CONTENT_DIRECTORY); - -values.clear(); -// ContactMethods.KIND is used to distinguish different kinds of -// contact methods, such as email, IM, etc. -values.put(People.ContactMethods.KIND, Contacts.KIND_EMAIL); -values.put(People.ContactMethods.DATA, "test@example.com"); -values.put(People.ContactMethods.TYPE, People.ContactMethods.TYPE_HOME); -getContentResolver().insert(emailUri, values); -</pre> - -<p> -You can place small amounts of binary data into a table by calling -the version of <code>{@link android.content.ContentValues#put -ContentValues.put()}</code> that takes a byte array. -That would work for a small icon-like image or a short audio clip, for example. -However, if you have a large amount of binary data to add, such as a photograph -or a complete song, put a {@code content:} URI for the data in the table and call -<code>{@link android.content.ContentResolver#openOutputStream -ContentResolver.openOutputStream()}</code> -with the file's URI. (That causes the content provider to store the data -in a file and record the file path in a hidden field of the record.) -</p> - -<p> -In this regard, the {@link android.provider.MediaStore} content -provider, the main provider that dispenses image, audio, and video -data, employs a special convention: The same URI that is used with -{@code query()} or {@code managedQuery()} to get meta-information -about the binary data (such as, the caption of a photograph or the -date it was taken) is used with {@code openInputStream()} -to get the data itself. Similarly, the same URI that is used with -{@code insert()} to put meta-information into a MediaStore record -is used with {@code openOutputStream()} to place the binary data there. -The following code snippet illustrates this convention: -</p> - -<pre> -import android.provider.MediaStore.Images.Media; -import android.content.ContentValues; -import java.io.OutputStream; - -// Save the name and description of an image in a ContentValues map. -ContentValues values = new ContentValues(3); -values.put(Media.DISPLAY_NAME, "road_trip_1"); -values.put(Media.DESCRIPTION, "Day 1, trip to Los Angeles"); -values.put(Media.MIME_TYPE, "image/jpeg"); - -// Add a new record without the bitmap, but with the values just set. -// insert() returns the URI of the new record. -Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values); - -// Now get a handle to the file for that record, and save the data into it. -// Here, sourceBitmap is a Bitmap object representing the file to save to the database. -try { - OutputStream outStream = getContentResolver().openOutputStream(uri); - sourceBitmap.compress(Bitmap.CompressFormat.JPEG, 50, outStream); - outStream.close(); -} catch (Exception e) { - Log.e(TAG, "exception while writing image", e); -} -</pre> - - -<h3>Batch updating records</h3> - -<p> -To batch update a group of records (for example, to change "NY" to "New York" -in all fields), call the <code>{@link -android.content.ContentResolver#update ContentResolver.update()}</code> -method with the columns and values to change. -</p> - - -<h3><a name="deletingrecord"></a>Deleting a record</h3> - -<p> -To delete a single record, call {<code>{@link -android.content.ContentResolver#delete ContentResolver.delete()}</code> -with the URI of a specific row. -</p> - <p> -To delete multiple rows, call <code>{@link -android.content.ContentResolver#delete ContentResolver.delete()}</code> -with the URI of the type of record to delete (for example, {@code android.provider.Contacts.People.CONTENT_URI}) and an SQL {@code WHERE} -clause defining which rows to delete. (<i><b>Caution</b>: -Be sure to include a valid {@code WHERE} clause if you're deleting a general -type, or you risk deleting more records than you intended!</i>). -</p> - - -<h2><a name="creating"></a>Creating a Content Provider</h2> - -<p> -To create a content provider, you must: -</p> - -<ul> -<li>Set up a system for storing the data. Most content providers -store their data using Android's file storage methods or SQLite databases, -but you can store your data any way you want. Android provides the -{@link android.database.sqlite.SQLiteOpenHelper SQLiteOpenHelper} -class to help you create a database and {@link -android.database.sqlite.SQLiteDatabase SQLiteDatabase} to manage it.</li> - -<li><p>Extend the {@link android.content.ContentProvider} class to provide -access to the data.</p></li> - -<li><p>Declare the content provider in the manifest file for your -application (AndroidManifest.xml).</p></li> -</ul> - -<p> -The following sections have notes on the last two of these tasks. -</p> - - -<h3>Extending the ContentProvider class</h3> - -<p> -You define a {@link android.content.ContentProvider} subclass to -expose your data to others using the conventions expected by -ContentResolver and Cursor objects. Principally, this means -implementing six abstract methods declared in the ContentProvider class: -</p> - -<p style="margin-left: 2em">{@code query()} -<br/>{@code insert()} -<br/>{@code update()} -<br/>{@code delete()} -<br/>{@code getType()} -<br/>{@code onCreate()}</p> - -<p> -The {@code query()} method must return a {@link android.database.Cursor} object -that can iterate over the requested data. Cursor itself is an interface, but -Android provides some ready-made Cursor objects that you can use. For example, -{@link android.database.sqlite.SQLiteCursor} can iterate over data stored in -an SQLite database. You get the Cursor object by calling any of the {@link -android.database.sqlite.SQLiteDatabase SQLiteDatabase} class's {@code query()} -methods. There are other Cursor implementations — such as {@link -android.database.MatrixCursor} — for data not stored in a database. -</p> - -<p> -Because these ContentProvider methods can be called from -various ContentResolver objects in different processes and threads, -they must be implemented in a thread-safe manner. -</p> - -<p> -As a courtesy, you might also want to call <code>{@link android.content.ContentResolver#notifyChange(android.net.Uri,android.database.ContentObserver) -ContentResolver.notifyChange()}</code> to notify listeners when there are -modifications to the data. -</p> - -<p> -Beyond defining the subclass itself, there are other steps you should take -to simplify the work of clients and make the class more accessible: -</p> - -<ul> -<li>Define a {@code public static final} {@link android.net.Uri} -named {@code CONTENT_URI}. This is the string that represents the full -{@code content:} URI that your content provider handles. You must define a -unique string for this value. The best solution is to use the fully-qualified -class name of the content provider (made lowercase). So, for example, the -URI for a TransportationProvider class could be defined as follows: - -<pre>public static final Uri CONTENT_URI = - Uri.parse("content://com.example.codelab.transportationprovider");</pre> - -<p> -If the provider has subtables, also define {@code CONTENT_URI} constants for -each of the subtables. These URIs should all have the same authority (since -that identifies the content provider), and be distinguished only by their paths. -For example: -</p> - -<p style="margin-left: 2em">{@code content://com.example.codelab.transportationprovider/train} -<br/>{@code content://com.example.codelab.transportationprovider/air/domestic} -<br/>{@code content://com.example.codelab.transportationprovider/air/international}</p> - -<p> -For an overview of {@code content:} URIs, see the <a href="#urisum">Content URI -Summary</a> at the end of this document. -</p></li> - -<li><p>Define the column names that the content provider will return to clients. -If you are using an underlying database, these column names are typically -identical to the SQL database column names they represent. Also define -{@code public static} String constants that clients can use to specify -the columns in queries and other instructions. -</p> - -<p> -Be sure to include an integer column named "{@code _id}" -(with the constant {@code _ID}) for -the IDs of the records. You should have this field whether or not you have -another field (such as a URL) that is also unique among all records. If -you're using the SQLite database, the {@code _ID} field should be the -following type: -</p> - -<p style="margin-left: 2em">{@code INTEGER PRIMARY KEY AUTOINCREMENT}</p> - -<p> -The {@code AUTOINCREMENT} descriptor is optional. But without it, SQLite -increments an ID counter field to the next number above the largest -existing number in the column. If you delete the last row, the next row added -will have the same ID as the deleted row. {@code AUTOINCREMENT} avoids this -by having SQLite increment to the next largest value whether deleted or not. -</p> -</li> - -<li><p>Carefully document the data type of each column. Clients need this -information to read the data.</p></li> - -<li><p>If you are handling a new data type, you must define a new MIME type -to return in your implementation of <code>{@link -android.content.ContentProvider#getType ContentProvider.getType()}</code>. -The type depends in part on whether or not the {@code content:} URI submitted -to {@code getType()} limits the request to a specific record. There's one -form of the MIME type for a single record and another for multiple records. -Use the {@link android.net.Uri Uri} methods to help determine what is being -requested. Here is the general format for each type:</p></li> - -<ul> -<li><p>For a single record: {@code vnd.android.cursor.item/vnd.<em>yourcompanyname.contenttype</em>}</p> - -<p>For example, a request for train record 122, like this URI,</p> -<p style="margin-left: 2em">{@code content://com.example.transportationprovider/trains/122}</p> - -<p>might return this MIME type:</p> -<p style="margin-left: 2em">{@code vnd.android.cursor.item/vnd.example.rail}</p> -</li> - -<li><p>For multiple records: {@code vnd.android.cursor.dir/vnd.<em>yourcompanyname.contenttype</em>}</p> - -<p>For example, a request for all train records, like the following URI,</p> -<p style="margin-left: 2em">{@code content://com.example.transportationprovider/trains}</p> - -<p>might return this MIME type:</p> -<p style="margin-left: 2em">{@code vnd.android.cursor.dir/vnd.example.rail}</p> -</li> -</ul> - -<li><p>If you are exposing byte data that's too big to put in the table itself -— such as a large bitmap file — the field that exposes the -data to clients should actually contain a {@code content:} URI string. -This is the field that gives clients access to the data file. The record -should also have another field, named "{@code _data}" that lists the exact file -path on the device for that file. This field is not intended to be read by -the client, but by the ContentResolver. The client will call <code>{@link -android.content.ContentResolver#openInputStream ContentResolver.openInputStream()}</code> -on the user-facing field holding the URI for the item. The ContentResolver -will request the "{@code _data}" field for that record, and because -it has higher permissions than a client, it should be able to access -that file directly and return a read wrapper for the file to the client.</p></li> - -</ul> - -<p> -For an example of a private content provider implementation, see the -NodePadProvider class in the Notepad sample application that ships with the SDK. -</p> - - -<h3>Declaring the content provider</h3> - -<p> -To let the Android system know about the content provider you've developed, -declare it with a {@code <provider>} element in the application's -AndroidManifest.xml file. Content providers that are not declared in the -manifest are not visible to the Android system -</p> - -<p> -The {@code name} attribute is the fully qualified name of the ContentProvider -subclass. The {@code authorities} attribute is the authority part of the -{@code content:} URI that identifies the provider. -For example if the ContentProvider subclass is AutoInfoProvider, the -{@code <provider>} element might look like this: -</p> - -<pre> -<provider android:name="com.example.autos.AutoInfoProvider" - android:authorities="com.example.autos.autoinfoprovider" - . . . /> -</provider> -</pre> - -<p> -Note that the {@code authorities} attribute omits the path part of a -{@code content:} URI. For example, if AutoInfoProvider controlled subtables -for different types of autos or different manufacturers, -</p> - -<p style="margin-left: 2em">{@code content://com.example.autos.autoinfoprovider/honda} -<br/>{@code content://com.example.autos.autoinfoprovider/gm/compact} -<br/>{@code content://com.example.autos.autoinfoprovider/gm/suv}</p> - -<p> -those paths would not be declared in the manifest. The authority is what -identifies the provider, not the path; your provider can interpret the path -part of the URI in any way you choose. -</p> - -<p> -Other {@code <provider>} attributes can set permissions to read and -write data, provide for an icon and text that can be displayed to users, -enable and disable the provider, and so on. Set the {@code multiprocess} -attribute to "{@code true}" if data does not need to be synchronized between -multiple running versions of the content provider. This permits an instance -of the provider to be created in each client process, eliminating the need -to perform IPC. -</p> - - -<h2><a name="urisum"></a>Content URI Summary</h2> - -<p> -Here is a recap of the important parts of a content URI: -</p> - -<p> -<img src="{@docRoot}images/content_uri.png" alt="Elements of a content URI" -height="80" width="528"> -</p> - -<ol type="A"> -<li>Standard prefix indicating that the data is controlled by a -content provider. It's never modified.</li> - -<li><p>The authority part of the URI; it identifies the content provider. -For third-party applications, this should be a fully-qualified class name -(reduced to lowercase) to ensure uniqueness. The authority is declared in -the {@code <provider>} element's {@code authorities} attribute:</p> - -<pre><provider android:name=".TransportationProvider" - android:authorities="com.example.transportationprovider" - . . . ></pre></li> - -<li><p>The path that the content provider uses to determine what kind of data is -being requested. This can be zero or more segments long. If the content provider -exposes only one type of data (only trains, for example), it can be absent. -If the provider exposes several types, including subtypes, it can be several -segments long — for example, "{@code land/bus}", "{@code land/train}", -"{@code sea/ship}", and "{@code sea/submarine}" to give four possibilities.</p></li> - -<li><p>The ID of the specific record being requested, if any. This is the -{@code _ID} value of the requested record. If the request is not limited to -a single record, this segment and the trailing slash are omitted:</p> - -<p style="margin-left: 2em">{@code content://com.example.transportationprovider/trains}</p> -</li> -</ol> - - + Content providers manage access to a structured set of data. They encapsulate the + data, and provide mechanisms for defining data security. Content providers are the standard + interface that connects data in one process with code running in another process. +</p> +<p> + When you want to access data in a content provider, you use the + {@link android.content.ContentResolver} object in your + application's {@link android.content.Context} to communicate with the provider as a client. + The {@link android.content.ContentResolver} object communicates with the provider object, an + instance of a class that implements {@link android.content.ContentProvider}. The provider + object receives data requests from clients, performs the requested action, and + returns the results. +</p> +<p> + You don't need to develop your own provider if you don't intend to share your data with + other applications. However, you do need your own provider to provide custom search + suggestions in your own application. You also need your own provider if you want to copy and + paste complex data or files from your application to other applications. +</p> +<p> + Android itself includes content providers that manage data such as audio, video, images, and + personal contact information. You can see some of them listed in the reference + documentation for the + <code><a href="{@docRoot}reference/android/provider/package-summary.html">android.provider</a> + </code> package. With some restrictions, these providers are accessible to any Android + application. +</p><p> + The following topics describe content providers in more detail: +</p> +<dl> + <dt> + <strong><a href="{@docRoot}guide/topics/providers/content-provider-basics.html"> + Content Provider Basics</a></strong> + </dt> + <dd> + How to access data in a content provider when the data is organized in tables. + </dd> + <dt> + <strong><a href="{@docRoot}guide/topics/providers/content-provider-creating.html"> + Creating a Content Provider</a></strong> + </dt> + <dd> + How to create your own content provider. + </dd> + <dt> + <strong><a href="{@docRoot}guide/topics/providers/calendar-provider.html"> + Calendar Provider</a></strong> + </dt> + <dd> + How to access the Calendar Provider that is part of the Android platform. + </dd> +</dl> diff --git a/docs/html/guide/topics/renderscript/compute.jd b/docs/html/guide/topics/renderscript/compute.jd index 8f08f59..e827f00 100644 --- a/docs/html/guide/topics/renderscript/compute.jd +++ b/docs/html/guide/topics/renderscript/compute.jd @@ -1,38 +1,253 @@ page.title=Compute -parent.title=RenderScript +parent.title=Renderscript parent.link=index.html + @jd:body - <div id="qv-wrapper"> - <div id="qv"> +<div id="qv-wrapper"> + <div id="qv"> + <h2>In this document</h2> + + <ol> + <li> + <a href="#creating">Creating a Compute Renderscript</a> + + <ol> + <li><a href="#creating-renderscript">Creating the Renderscript file</a></li> - <h2>Related Samples</h2> + <li><a href="#calling">Calling the Renderscript code</a></li> + </ol> + </li> + </ol> - <ol> - <li><a href="{@docRoot}resources/samples/RenderScript/HelloCompute/index.html">Hello - Compute</a></li> - <li><a href="{@docRoot}resources/samples/RenderScript/Balls/index.html">Balls</a></li> - </ol> - </div> + <h2>Related Samples</h2> + + <ol> + <li><a href="{@docRoot}resources/samples/RenderScript/HelloCompute/index.html">Hello + Compute</a></li> + + <li><a href="{@docRoot}resources/samples/RenderScript/Balls/index.html">Balls</a></li> + </ol> </div> +</div> + +<p>Renderscript exposes a set of compute APIs that you can use to do intensive computational +operations. You can use the compute APIs in the context of a graphics Renderscript such as +calculating the positions of many objects in a scene. You can also create standalone compute +Renderscripts such as one that does image processing for a photo editor application.</p> + +<p>Compute Renderscripts scale to the amount of +processing cores available on the device. This is enabled through a function named +<code>rsForEach()</code> (or the <code>forEach_root()</code> method at the Android framework level). +that automatically partitions work across available processing cores on the device. +For now, compute Renderscripts can only take advantage of CPU +cores, but in the future, they can potentially run on other types of processors such as GPUs and +DSPs.</p> + +<h2 id="creating-renderscript">Creating a Compute Renderscript</h2> + +<p>Implementing a compute Renderscript creating a <code>.rs</code> file that contains +your Renderscript code and calling it at the Android framework level with the +<code>forEach_root()</code> or at the Renderscript runtime level with the +<code>rsForEach()</code> function. The following diagram describes how a typical compute +Renderscript is set up:</p><img src="{@docRoot}images/rs_compute.png"> + +<p class="img-caption"><strong>Figure 1.</strong> Compute Renderscript overview</p> + +<p>The following sections describe how to create a simple compute Renderscript and use it in an +Android application. This example uses the <a href= +"{@docRoot}resources/samples/RenderScript/HelloCompute/index.html">HelloCompute Renderscript +sample</a> that is provided in the SDK as a guide (some code has been modified from its original +form for simplicity).</p> + +<h3 id="creating-renderscript">Creating the Renderscript file</h3> + +<p>Your Renderscript code resides in <code>.rs</code> and <code>.rsh</code> files in the +<code><project_root>/src/</code> directory. This code contains the compute logic +and declares all necessary variables and pointers. +Every compute <code>.rs</code> file generally contains the following items:</p> + +<ul> + <li>A pragma declaration (<code>#pragma rs java_package_name(<em>package.name</em>)</code>) + that declares the package name of the <code>.java</code> reflection of this Renderscript.</li> + + <li>A pragma declaration (<code>#pragma version(1)</code>) that declares the version of + Renderscript that you are using (1 is the only value for now).</li> + + <li>A <code>root()</code> function that is the main worker function. The root function is + called by the <code>rsForEach</code> function, which allows the Renderscript code to be called and + executed on multiple cores if they are available. The <code>root()</code> function must return + <code>void</code> and accept the following arguments: + + <ul> + <li>Pointers to memory allocations that are used for the input and output of the compute + Renderscript. Both of these pointers are required for Android 3.2 (API level 13) platform + versions or older. Android 4.0 (API level 14) and later requires one or both of these + allocations.</li> + </ul> + + <p>The following arguments are optional, but both must be supplied if you choose to use + them:</p> + + <ul> + <li>A pointer for user-defined data that the Renderscript might need to carry out + computations in addition to the necessary allocations. This can be a pointer to a simple + primitive or a more complex struct.</li> + + <li>The size of the user-defined data.</li> + </ul> + </li> + + <li>An optional <code>init()</code> function. This allows you to do any initialization + before the <code>root()</code> function runs, such as initializing variables. This + function runs once and is called automatically when the Renderscript starts, before anything + else in your Renderscript.</li> + + <li>Any variables, pointers, and structures that you wish to use in your Renderscript code (can + be declared in <code>.rsh</code> files if desired)</li> +</ul> + +<p>The following code shows how the <a href= +"{@docRoot}resources/samples/RenderScript/HelloCompute/src/com/example/android/rs/hellocompute/mono.html"> +mono.rs</a> file is implemented:</p> +<pre> +#pragma version(1) +#pragma rs java_package_name(com.example.android.rs.hellocompute) + +//multipliers to convert a RGB colors to black and white +const static float3 gMonoMult = {0.299f, 0.587f, 0.114f}; + +void root(const uchar4 *v_in, uchar4 *v_out) { + //unpack a color to a float4 + float4 f4 = rsUnpackColor8888(*v_in); + //take the dot product of the color and the multiplier + float3 mono = dot(f4.rgb, gMonoMult); + //repack the float to a color + *v_out = rsPackColorTo8888(mono); +} +</pre> + +<h3 id="calling">Calling the Renderscript code</h3> + +<p>You can do Renderscript to Renderscript calls with <code>rsForEach</code> in situations +such as when a graphics Renderscript needs to do a lot of computational operations. The Renderscript +<a href="{@docRoot}resources/samples/RenderScript/Balls/index.html">Balls</a> sample shows how +this is setup. The <a href= +"resources/samples/RenderScript/Balls/src/com/example/android/rs/balls/balls.html">balls.rs</a> +graphics Renderscript calls the <a href= +"resources/samples/RenderScript/Balls/src/com/example/android/rs/balls/balls.html">balls_physics.rs</a> +compute Renderscript to calculate the location of the balls that are rendered to the screen.</p> + +<p>Another way to use a compute Renderscript is to call it from your Android framework code by +creating a Renderscript object by instantiating the (<code>ScriptC_<em>script_name</em></code>) +class. This class contains a method, <code>forEach_root()</code>, that lets you invoke +<code>rsForEach</code>. You give it the same parameters that you would if you were invoking it +at the Renderscript runtime level. This technique allows your Android application to offload +intensive mathematical calculations to Renderscript. See the <a href= +"{@docRoot}resources/samples/RenderScript/HelloCompute/index.html">HelloCompute</a> sample to see +how a simple Android application can utilize a compute Renderscript.</p> + +<p>To call a compute Renderscript at the Android framework level:</p> + +<ol> + <li>Allocate memory that is needed by the compute Renderscript in your Android framework code. + You need an input and output {@link android.renderscript.Allocation} for Android 3.2 (API level + 13) platform versions and older. The Android 4.0 (API level 14) platform version requires only + one or both {@link android.renderscript.Allocation}s.</li> + + <li>Create an instance of the <code>ScriptC_<em>script_name</em></code> class.</li> + + <li>Call <code>forEach_root()</code>, passing in the allocations, the + Renderscript, and any optional user-defined data. The output allocation will contain the output + of the compute Renderscript.</li> +</ol> + +<p>In the following example, taken from the <a href= +"{@docRoot}resources/samples/RenderScript/HelloCompute/index.html">HelloCompute</a> sample, processes +a bitmap and outputs a black and white version of it. The +<code>createScript()</code> method carries out the steps described previously. This method the compute +Renderscript, <code>mono.rs</code>, passing in memory allocations that store the bitmap to be processed +as well as the eventual output bitmap. It then displays the processed bitmap onto the screen:</p> +<pre> +package com.example.android.rs.hellocompute; + +import android.app.Activity; +import android.os.Bundle; +import android.graphics.BitmapFactory; +import android.graphics.Bitmap; +import android.renderscript.RenderScript; +import android.renderscript.Allocation; +import android.widget.ImageView; + +public class HelloCompute extends Activity { + private Bitmap mBitmapIn; + private Bitmap mBitmapOut; + + private RenderScript mRS; + private Allocation mInAllocation; + private Allocation mOutAllocation; + private ScriptC_mono mScript; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.main); + + mBitmapIn = loadBitmap(R.drawable.data); + mBitmapOut = Bitmap.createBitmap(mBitmapIn.getWidth(), mBitmapIn.getHeight(), + mBitmapIn.getConfig()); + + ImageView in = (ImageView) findViewById(R.id.displayin); + in.setImageBitmap(mBitmapIn); + + ImageView out = (ImageView) findViewById(R.id.displayout); + out.setImageBitmap(mBitmapOut); + + createScript(); + } + private void createScript() { + mRS = RenderScript.create(this); + mInAllocation = Allocation.createFromBitmap(mRS, mBitmapIn, + Allocation.MipmapControl.MIPMAP_NONE, + Allocation.USAGE_SCRIPT); + mOutAllocation = Allocation.createTyped(mRS, mInAllocation.getType()); + mScript = new ScriptC_mono(mRS, getResources(), R.raw.mono); + mScript.forEach_root(mInAllocation, mOutAllocation); + mOutAllocation.copyTo(mBitmapOut); + } + + private Bitmap loadBitmap(int resource) { + final BitmapFactory.Options options = new BitmapFactory.Options(); + options.inPreferredConfig = Bitmap.Config.ARGB_8888; + return BitmapFactory.decodeResource(getResources(), resource, options); + } +} +</pre> + +<p>To call a compute Renderscript from another Renderscript file:</p> +<ol> + <li>Allocate memory that is needed by the compute Renderscript in your Android framework code. + You need an input and output {@link android.renderscript.Allocation} for Android 3.2 (API level + 13) platform versions and older. The Android 4.0 (API level 14) platform version requires only + one or both {@link android.renderscript.Allocation}s.</li> + + <li>Call <code>rsForEach()</code>, passing in the allocations and any optional user-defined data. + The output allocation will contain the output of the compute Renderscript.</li> +</ol> +<p>The following example, taken from the <a href= +"{@docRoot}resources/samples/RenderScript/Balls/src/com/example/android/rs/balls/balls.html">Renderscript +Balls sample</a>, demonstrates how to do make a script to script call:</p> +<pre> +rs_script script; +rs_allocation in_allocation; +rs_allocation out_allocation; +UserData_t data; +... +rsForEach(script, in_allocation, out_allocation, &data, sizeof(data)); +</pre> - <p>RenderScript exposes a set of compute APIs that you can use to do intensive computational operations. - You can use the compute APIs in the context of a graphics RenderScript such as calculating the - transformation of many geometric objects in a scene. You can also create a standalone compute RenderScript that does not - draw anything to the screen such as bitmap image processing for a photo editor application. - The RenderScript compute APIs are mainly defined in the <code>rs_cl.rsh</code> header</p> - - <p>Compute RenderScripts are simpler to setup and implement as there is no graphics rendering involved. - You can offload computational aspects of your application to RenderScript by creating a native RenderScript - file (.rs) and using the generated reflected layer class to call functions in the <code>.rs</code> file. - - <p>See the <a href="{@docRoot}resources/samples/RenderScript/HelloCompute/index.html">HelloCompute</a> - sample in the Android SDK for more - information on how to create a simple compute RenderScript.</p> - <p> - See the <a href="{@docRoot}resources/samples/RenderScript/Balls/index.html">Balls</a> - sample in the Android SDK for more - information on how to create a compute RenderScript that is used in a graphics RenderScript. - The compute RenderScript is contained in - <a href="{@docRoot}resources/samples/RenderScript/Balls/src/com/example/android/rs/balls/ball_physics.html">balls_physics.rs</a>. - </p>
\ No newline at end of file +<p>In this example, assume that the script and memory allocations have already been +allocated and bound at the Android framework level and that <code>UserData_t</code> is a struct +declared previously. Passing a pointer to a struct and the size of the struct to <code>rsForEach</code> +is optional, but useful if your compute Renderscript requires additional information other than +the necessary memory allocations.</p> diff --git a/docs/html/guide/topics/renderscript/graphics.jd b/docs/html/guide/topics/renderscript/graphics.jd index 2fefecc..462a990 100644 --- a/docs/html/guide/topics/renderscript/graphics.jd +++ b/docs/html/guide/topics/renderscript/graphics.jd @@ -1,6 +1,7 @@ -page.title=3D Graphics -parent.title=RenderScript +page.title=Graphics +parent.title=Renderscript parent.link=index.html + @jd:body <div id="qv-wrapper"> @@ -11,16 +12,16 @@ parent.link=index.html <li> <a href="#creating-graphics-rs">Creating a Graphics Renderscript</a> <ol> - <li><a href="#creating-native">Creating the native Renderscript file</a></li> + <li><a href="#creating-native">Creating the Renderscript file</a></li> <li><a href="#creating-entry">Creating the Renderscript entry point class</a></li> - <li><a href="#creating-view">Creating the surface view</a></li> - <li><a href="#creating-activity">Creating the activity</a></li> + <li><a href="#creating-view">Creating the view class</a></li> + <li><a href="#creating-activity">Creating the activity class</a></li> </ol> </li> <li> <a href="#drawing">Drawing</a> <ol> - <li><a href="#drawing-rsg">Drawing using the rsgDraw functions</a></li> + <li><a href="#drawing-rsg">Simple drawing</a></li> <li><a href="#drawing-mesh">Drawing with a mesh</a></li> </ol> </li> @@ -31,6 +32,9 @@ parent.link=index.html <li><a href="#shader-sampler">Defining a sampler</a></li> </ol> </li> + <li> + <a href="#fbo">Rendering to a Framebuffer Object</a> + </li> </ol> <h2>Related Samples</h2> @@ -40,8 +44,9 @@ parent.link=index.html <li><a href="{@docRoot}resources/samples/RenderScript/Fountain/index.html">Fountain</a></li> - <li><a href="{@docRoot}resources/samples/RenderScript/HelloWorld/index.html">Hello - World</a></li> + <li><a href="{@docRoot}resources/samples/RenderScript/FountainFbo/index.html">FountainFbo</a></li> + + <li><a href="{@docRoot}resources/samples/RenderScript/HelloWorld/index.html">Hello World</a></li> <li><a href="{@docRoot}resources/samples/RenderScript/MiscSamples/index.html">Misc Samples</a></li> @@ -49,310 +54,476 @@ href="{@docRoot}resources/samples/RenderScript/MiscSamples/index.html">Misc Samp </div> </div> - <p>RenderScript provides a number of graphics APIs for 3D rendering, both at the Android - framework level as well as at the native level. For instance, the Android framework APIs let you + <p>Renderscript provides a number of graphics APIs for rendering, both at the Android + framework level as well as at the Renderscript runtime level. For instance, the Android framework APIs let you create meshes and define shaders to customize the graphical rendering pipeline. The native - RenderScript graphics APIs lets you draw the actual meshes to render your scene. In general, you - will need to be familiar with APIs to appropriately render 3D graphics on an Android-powered - device.</p> + Renderscript graphics APIs let you draw the actual meshes to render your scene. You need to + be familiar with both APIs to appropriately render graphics on an Android-powered device.</p> - <h2 id="creating-graphics-rs">Creating a Graphics RenderScript</h2> + <h2 id="creating-graphics-rs">Creating a Graphics Renderscript</h2> - <p>Because of the various layers of code when writing a RenderScript application, it is useful to - create the following files for a scene that you want to render:</p> + <p>Renderscript applications require various layers of code, so it is useful to create the following + files to help keep your application organized:</p> - <ul> - <li>The native RenderScript <code>.rs</code> file. This file contains the logic to do the - graphics rendering.</li> + <dl> + <dt>The Renderscript <code>.rs</code> file</dt> + + <dd>This file contains the logic to do the graphics rendering.</dd> - <li>The RenderScript entry point class that allows your view to interact with the code defined - in the <code>.rs</code> file. This class contains a RenderScript object(instance of + <dt>The Renderscript entry point <code>.java</code> class</dt> + + <dd>This class allows the view class to interact with the code defined in the <code>.rs</code> + file. This class contains a Renderscript object (instance of <code>ScriptC_<em>renderscript_file</em></code>), which allows your Android framework code to - call the native RenderScript code. This class also creates the {@link - android.renderscript.RenderScriptGL} context object, which contains the current rendering state - of the RenderScript such as programs (vertex and fragment shaders, for example) that you want - to define and bind to the graphics pipeline. The context object attaches to the RenderScript - object (instance of <code><em>ScriptC_renderscript_file</em></code>) that does the rendering. - Our example names this class <code>HelloWorldRS</code>.</li> - - <li>Create a class that extends {@link android.renderscript.RSSurfaceView} to provide a surface - to render on. If you want to implement callbacks from events inherited from {@link + call the Renderscript code. In general, this class does much of the setup for Renderscript + such as shader and mesh building and memory allocation and binding. The SDK samples follow the + convention of naming this file ActivityRS.java, + where Activity is the name of your main activity class.</dd> + + <dt>The view <code>.java</code> class</dt> + + <dd>This class extends {@link android.renderscript.RSSurfaceView} or {@link + android.renderscript.RSTextureView} to provide a surface to render on. A {@link + android.renderscript.RSSurfaceView} consumes a whole window, but a {@link + android.renderscript.RSTextureView} allows you to draw Renderscript graphics inside of a + view and add it to a {@link android.view.ViewGroup} alongside + other views. In this class, you create a {@link android.renderscript.RenderScriptGL} context object + with a call to {@link android.renderscript.RSSurfaceView#createRenderScriptGL + RSSurfaceView.createRenderscriptGL()} or {@link android.renderscript.RSTextureView#createRenderScriptGL + RSTextureView.createRenderscriptGL()}. The {@link android.renderscript.RenderScriptGL} context object + contains information about the current rendering state of Renderscript such as the vertex and + fragment shaders. You pass this context object to the Renderscript entry point class, so that + class can modify the rendering context if needed and bind the Renderscript code to the context. Once bound, + the view class can use the Renderscript code to display graphics. + The view class should also implement callbacks for events inherited from {@link android.view.View}, such as {@link android.view.View#onTouchEvent onTouchEvent()} and {@link - android.view.View#onKeyDown onKeyDown()}, do so in this class as well.</li> + android.view.View#onKeyDown onKeyDown()} if you want to detect these types of user interactions. + The SDK samples follow the convention of naming this file ActivityView.java, + where Activity is the name of your main activity class</dd> - <li>Create a class that is the main Activity class, like you would with any Android - application. This class sets your {@link android.renderscript.RSSurfaceView} as the content - view for this Activity.</li> - </ul> + <dt>The activity <code>.java</code> class</dt> + + <dd>This class is the main activity class and sets your {@link android.renderscript.RSSurfaceView} as the main content + view for this activity or uses the {@link android.renderscript.RSTextureView} alongside other views.</dd> + </dl> + <p>Figure 1 describes how these classes interact with one another in a graphics Renderscript:</p> + + <img src="{@docRoot}images/rs_graphics.png"> + <p class="img-caption"><strong>Figure 1.</strong> Graphics Renderscript overview</p> - <p>The following sections describe how to implement these three classes by using the HelloWorld - RenderScript sample that is provided in the SDK as a guide (some code has been modified from its - original form for simplicity).</p> - <h3 id="creating-native">Creating the native RenderScript file</h3> + <p>The following sections describe how to create an application that uses a graphics Renderscript by using + the <a href="{@docRoot}resources/samples/RenderScript/Fountain/index.html">Renderscript Fountain + sample</a> that is provided in the SDK as a guide (some code has been modified from its original + form for simplicity).</p> - <p>Your native RenderScript code resides in a <code>.rs</code> file in the - <code><project_root>/src/</code> directory. You can also define <code>.rsh</code> header - files. This code contains the logic to render your graphics and declares all necessary variables + <h3 id="creating-native">Creating the Renderscript file</h3> + + <p>Your Renderscript code resides in <code>.rs</code> and <code>.rsh</code> (headers) files in the + <code><project_root>/src/</code> directory. This code contains the logic to render your + graphics and declares all other necessary items such as variables, structs, and pointers. Every graphics <code>.rs</code> file generally contains the following items:</p> <ul> - <li>A pragma (<code>#pragma rs java_package_name(<em>package.name</em>)</code>) that declares - the package name of the <code>.java</code> reflection of this RenderScript.</li> + <li>A pragma declaration (<code>#pragma rs java_package_name(<em>package.name</em>)</code>) that declares + the package name of the <code>.java</code> reflection of this Renderscript.</li> - <li>A pragma (<code>#pragma version(1)</code>) that declares the version of RenderScript that + <li>A pragma declaration (<code>#pragma version(1)</code>) that declares the version of Renderscript that you are using (1 is the only value for now).</li> - <li>A <code>#include</code> of the rs_graphics.rsh header file.</li> + <li>A <code>#include "rs_graphics.rsh"</code> declaration.</li> - <li>A <code>root()</code> function. This is the main worker function for your RenderScript and - calls RenderScript graphics APIs to draw meshes to the surface. This function is called every - time a frame refresh occurs, which is specified as its return value. A <code>0</code> specified - for the return value says to only render the frame when a property of the scene that you are + <li>A <code>root()</code> function. This is the main worker function for your Renderscript and + calls Renderscript graphics functions to render scenes. This function is called every time a + frame refresh occurs, which is specified as its return value. A <code>0</code> (zero) specified for + the return value says to only render the frame when a property of the scene that you are rendering changes. A non-zero positive integer specifies the refresh rate of the frame in milliseconds. - <p class="note"><strong>Note:</strong> The RenderScript runtime makes its best effort to + <p class="note"><strong>Note:</strong> The Renderscript runtime makes its best effort to refresh the frame at the specified rate. For example, if you are creating a live wallpaper - and set the return value to 50, the runtime renders the wallpaper at 20fps if it has just - enough or more resources to do so, and renders as fast as it can if it does not.</p> - - <p>For more - information on using the RenderScript graphics functions, see the <a href= + and set the return value to 20, the Renderscript runtime renders the wallpaper at 50fps if it has just + enough or more resources to do so. It renders as fast as it can if not enough resources + are available.</p> + + <p>For more information on using the Renderscript graphics functions, see the <a href= "#drawing">Drawing</a> section.</p> </li> - <li>An <code>init()</code> function. This allows you to do any initialization of your - RenderScript before the <code>root()</code> function runs, such as initializing variables. This - function runs once and is called automatically when the RenderScript starts, before anything - else in your RenderScript. Creating this function is optional.</li> + <li>An <code>init()</code> function. This allows you to do initialization of your + Renderscript before the <code>root()</code> function runs, such as assigning values to variables. This + function runs once and is called automatically when the Renderscript starts, before anything + else in your Renderscript. Creating this function is optional.</li> - <li>Any variables, pointers, and structures that you wish to use in your RenderScript code (can + <li>Any variables, pointers, and structures that you wish to use in your Renderscript code (can be declared in <code>.rsh</code> files if desired)</li> </ul> - <p>The following code shows how the <code>helloworld.rs</code> file is implemented:</p> + <p>The following code shows how the <code>fountain.rs</code> file is implemented:</p> <pre> #pragma version(1) // Tell which java package name the reflected files should belong to -#pragma rs java_package_name(com.android.rs.helloworld) +#pragma rs java_package_name(com.example.android.rs.fountain) -// Built-in header with graphics APIs +//declare shader binding +#pragma stateFragment(parent) + +// header with graphics APIs, must include explicitly #include "rs_graphics.rsh" -// gTouchX and gTouchY are variables that are reflected for use -// by the Android framework API. This RenderScript uses them to be notified of touch events. -int gTouchX; -int gTouchY; +static int newPart = 0; + +// the mesh to render +rs_mesh partMesh; + +// the point representing where a particle is rendered +typedef struct __attribute__((packed, aligned(4))) Point { + float2 delta; + float2 position; + uchar4 color; +} Point_t; +Point_t *point; + +// main worker function that renders particles onto the screen +int root() { + float dt = min(rsGetDt(), 0.1f); + rsgClearColor(0.f, 0.f, 0.f, 1.f); + const float height = rsgGetHeight(); + const int size = rsAllocationGetDimX(rsGetAllocation(point)); + float dy2 = dt * (10.f); + Point_t * p = point; + for (int ct=0; ct < size; ct++) { + p->delta.y += dy2; + p->position += p->delta; + if ((p->position.y > height) && (p->delta.y > 0)) { + p->delta.y *= -0.3f; + } + p++; + } + + rsgDrawMesh(partMesh); + return 1; +} -// This is invoked automatically when the script is created and initializes the variables -// in the Android framework layer as well. -void init() { - gTouchX = 50.0f; - gTouchY = 50.0f; +// adds particles to the screen to render +static float4 partColor[10]; +void addParticles(int rate, float x, float y, int index, bool newColor) +{ + if (newColor) { + partColor[index].x = rsRand(0.5f, 1.0f); + partColor[index].y = rsRand(1.0f); + partColor[index].z = rsRand(1.0f); + } + float rMax = ((float)rate) * 0.02f; + int size = rsAllocationGetDimX(rsGetAllocation(point)); + uchar4 c = rsPackColorTo8888(partColor[index]); + + Point_t * np = &point[newPart]; + float2 p = {x, y}; + while (rate--) { + float angle = rsRand(3.14f * 2.f); + float len = rsRand(rMax); + np->delta.x = len * sin(angle); + np->delta.y = len * cos(angle); + np->position = p; + np->color = c; + newPart++; + np++; + if (newPart >= size) { + newPart = 0; + np = &point[newPart]; + } + } } +</pre> -int root(int launchID) { + <h3 id="creating-entry">Creating the Renderscript entry point class</h3> - // Clear the background color - rsgClearColor(0.0f, 0.0f, 0.0f, 0.0f); - // Tell the runtime what the font color should be - rsgFontColor(1.0f, 1.0f, 1.0f, 1.0f); - // Introuduce ourselves to the world by drawing a greeting - // at the position user touched on the screen - rsgDrawText("Hello World!", gTouchX, gTouchY); + <p>When you create a Renderscript (<code>.rs</code>) file, it is helpful to create a + corresponding Android framework class that is an entry point into the <code>.rs</code> file. + The most important thing this class does is receive a {@link android.renderscript.RenderScriptGL} rendering context + object from the <a href="#creating-view">view class</a> and binds the actual Renderscript + code to the rendering context. This notifies your view class of the code that it needs + to render graphics. + </p> - // Return value tells RS roughly how often to redraw - // in this case 20 ms - return 20; -} -</pre> + <p>In addition, this class should contain all of the things needed to set up Renderscript. + Some important things that you need to do in this class are:</p> - <h3 id="creating-entry">Creating the RenderScript entry point class</h3> - - <p>When you create a RenderScript (<code>.rs</code>) file, it is helpful to create a - corresponding Android framework class that is an entry point into the <code>.rs</code> file. In - this entry point class, you create a RenderScript object by instantiating a - <code>ScriptC_<em>rs_filename</em></code> and binding it to the RenderScript context. The - RenderScript object is attached to the RenderScript bytecode, which is platform-independent and - gets compiled on the device when the RenderScript application runs. Both the - <code>ScriptC_<em>rs_filename</em></code> class and bytecode is generated by the Android build - tools and is packaged with the <code>.apk</code> file. The bytecode file is located in the - <code><project_root>/res/raw/</code> directory and is named <code>rs_filename.bc</code>. - You refer to the bytecode as a resource (<code>R.raw.<em>rs_filename</em></code>). when creating - the RenderScript object..</p> - - <p>You then bind the RenderScript object to the RenderScript context, so that the surface view - knows what code to use to render graphics. The following code shows how the - <code>HelloWorldRS</code> class is implemented:</p> + <ul> + <li>Create a Renderscript object + <code>ScriptC_<em>rs_filename</em></code>. The Renderscript object is attached to the Renderscript bytecode, which is platform-independent and + gets compiled on the device when the Renderscript application runs. The bytecode is referenced + as a raw resource and is passed into the constructor for the Renderscript object. + For example, this is how the <a href="{@docRoot}resources/samples/RenderScript/Fountain/index.html">Fountain</a> + sample creates the Renderscript object: + <pre> + RenderScriptGL rs; //obtained from the view class + Resources res; //obtained from the view class + ... + ScriptC_fountain mScript = new ScriptC_fountain(mRS, mRes, R.raw.fountain); + </pre> + </li> + <li>Allocate any necessary memory and bind it to your Renderscript code via the Renderscript object.</li> + <li>Build any necessary meshes and bind them to the Renderscript code via the Renderscript object.</li> + <li>Create any necessary programs and bind them to the Renderscript code via the Renderscript object.</li> + </ul> + + <p>The following code shows how the <a href= + "{@docRoot}resources/samples/RenderScript/Fountain/src/com/example/android/rs/fountain/FountainRS.html"> + FountainRS</a> class is implemented:</p> <pre> -package com.android.rs.helloworld; +package com.example.android.rs.fountain; import android.content.res.Resources; import android.renderscript.*; +import android.util.Log; -public class HelloWorldRS { - //context and resources are obtained from RSSurfaceView, which calls init() - private Resources mRes; - private RenderScriptGL mRS; - - //Declare the RenderScript object - private ScriptC_helloworld mScript; +public class FountainRS { + public static final int PART_COUNT = 50000; - public HelloWorldRS() { + public FountainRS() { } /** - * This provides us with the RenderScript context and resources - * that allow us to create the RenderScript object + * This provides us with the Renderscript context and resources + * that allow us to create the Renderscript object */ + private Resources mRes; + private RenderScriptGL mRS; + + // Renderscript object + private ScriptC_fountain mScript; + + // Called by the view class to initialize the Renderscript context and renderer public void init(RenderScriptGL rs, Resources res) { mRS = rs; mRes = res; - initRS(); - } - /** - * Calls native RenderScript functions (set_gTouchX and set_gTouchY) - * through the reflected layer class ScriptC_helloworld to pass in - * touch point data. - */ - public void onActionDown(int x, int y) { - mScript.set_gTouchX(x); - mScript.set_gTouchY(y); + + /** + * Create a shader and bind to the Renderscript context + */ + ProgramFragmentFixedFunction.Builder pfb = new ProgramFragmentFixedFunction.Builder(rs); + pfb.setVaryingColor(true); + rs.bindProgramFragment(pfb.create()); + + /** + * Allocate memory for the particles to render and create the mesh to draw + */ + ScriptField_Point points = new ScriptField_Point(mRS, PART_COUNT); + Mesh.AllocationBuilder smb = new Mesh.AllocationBuilder(mRS); + smb.addVertexAllocation(points.getAllocation()); + smb.addIndexSetType(Mesh.Primitive.POINT); + Mesh sm = smb.create(); + + /** + * Create and bind the Renderscript object to the Renderscript context + */ + mScript = new ScriptC_fountain(mRS, mRes, R.raw.fountain); + mScript.set_partMesh(sm); + mScript.bind_point(points); + mRS.bindRootScript(mScript); } + + boolean holdingColor[] = new boolean[10]; + /** - * Binds the RenderScript object to the RenderScript context + * Calls Renderscript functions (invoke_addParticles) + * via the Renderscript object to add particles to render + * based on where a user touches the screen. */ - private void initRS() { - //create the RenderScript object - mScript = new ScriptC_helloworld(mRS, mRes, R.raw.helloworld); - //bind the RenderScript object to the RenderScript context - mRS.bindRootScript(mScript); + public void newTouchPosition(float x, float y, float pressure, int id) { + if (id >= holdingColor.length) { + return; + } + int rate = (int)(pressure * pressure * 500.f); + if (rate > 500) { + rate = 500; + } + if (rate > 0) { + mScript.invoke_addParticles(rate, x, y, id, !holdingColor[id]); + holdingColor[id] = true; + } else { + holdingColor[id] = false; + } + } } - </pre> - <h3 id="creating-view">Creating the surface view</h3> - <p>To create a surface view to render graphics on, create a class that extends {@link - android.renderscript.RSSurfaceView}. This class also creates a RenderScript context object - ({@link android.renderscript.RenderScriptGL} and passes it to the Rendscript entry point class to - bind the two. The following code shows how the <code>HelloWorldView</code> class is - implemented:</p> + <h3 id="creating-view">Creating the view class</h3> + + + <p>To display graphics, you need a view to render on. Create a class that extends {@link + android.renderscript.RSSurfaceView} or {@link android.renderscript.RSTextureView}. This class + allows you to create a {@link android.renderscript.RenderScriptGL} context object by calling and + pass it to the Rendscript entry point class to bind the two. Once bound, the content is aware + of the code that it needs to use to render graphics with. If your Renderscript code + depends on any type of information that the view is aware of, such as touches from the user, + you can also use this class to relay that information to the Renderscript entry point class. + The following code shows how the <code>FountainView</code> class is implemented:</p> <pre> -package com.android.rs.helloworld; +package com.example.android.rs.fountain; -import android.renderscript.RSSurfaceView; +import android.renderscript.RSTextureView; import android.renderscript.RenderScriptGL; import android.content.Context; import android.view.MotionEvent; -public class HelloWorldView extends RSSurfaceView { - // RenderScript context - private RenderScriptGL mRS; - // RenderScript entry point object that does the rendering - private HelloWorldRS mRender; +public class FountainView extends RSTextureView { - public HelloWorldView(Context context) { + public FountainView(Context context) { super(context); - initRS(); } + // Renderscript context + private RenderScriptGL mRS; + // Renderscript entry point object that calls Renderscript code + private FountainRS mRender; - private void initRS() { + /** + * Create Renderscript context and initialize Renderscript entry point + */ + @Override + protected void onAttachedToWindow() { + super.onAttachedToWindow(); + android.util.Log.e("rs", "onAttachedToWindow"); if (mRS == null) { - // Initialize RenderScript with default surface characteristics. RenderScriptGL.SurfaceConfig sc = new RenderScriptGL.SurfaceConfig(); - //Create the RenderScript context mRS = createRenderScriptGL(sc); - // Create an instance of the RenderScript entry point class - mRender = new HelloWorldRS(); - // Call the entry point class to bind it to this context + mRender = new FountainRS(); mRender.init(mRS, getResources()); } } - /** - * Rebind everything when the window becomes attached - */ - protected void onAttachedToWindow() { - super.onAttachedToWindow(); - initRS(); - } - - /** - * Stop rendering when window becomes detached - */ + @Override protected void onDetachedFromWindow() { - // Handle the system event and clean up - mRender = null; + super.onDetachedFromWindow(); + android.util.Log.e("rs", "onDetachedFromWindow"); if (mRS != null) { mRS = null; destroyRenderScriptGL(); } } + /** - * Use callbacks to relay data to RenderScript entry point class + * Use callbacks to relay data to Renderscript entry point class */ - public boolean onTouchEvent(MotionEvent ev) { - // Pass touch events from the system to the rendering script - if (ev.getAction() == MotionEvent.ACTION_DOWN) { - mRender.onActionDown((int)ev.getX(), (int)ev.getY()); - return true; + @Override + public boolean onTouchEvent(MotionEvent ev) + { + int act = ev.getActionMasked(); + if (act == ev.ACTION_UP) { + mRender.newTouchPosition(0, 0, 0, ev.getPointerId(0)); + return false; + } else if (act == MotionEvent.ACTION_POINTER_UP) { + // only one pointer going up, we can get the index like this + int pointerIndex = ev.getActionIndex(); + int pointerId = ev.getPointerId(pointerIndex); + mRender.newTouchPosition(0, 0, 0, pointerId); } - - return false; + int count = ev.getHistorySize(); + int pcount = ev.getPointerCount(); + + for (int p=0; p < pcount; p++) { + int id = ev.getPointerId(p); + mRender.newTouchPosition(ev.getX(p), + ev.getY(p), + ev.getPressure(p), + id); + + for (int i=0; i < count; i++) { + mRender.newTouchPosition(ev.getHistoricalX(p, i), + ev.getHistoricalY(p, i), + ev.getHistoricalPressure(p, i), + id); + } + } + return true; } } - </pre> - <h3 id="creating-activity">Creating the Activity</h3> + <h3 id="creating-activity">Creating the activity class</h3> - <p>Applications that use RenderScript still adhere to activity lifecyle, and are part of the same - view hierarchy as traditional Android applications, which is handled by the Android VM. This - Activity class sets its view to be the {@link android.renderscript.RSSurfaceView} and handles - lifecycle callback events appropriately. The following code shows how the <code>HelloWorld</code> - class is implemented:</p> + <p>Applications that use Renderscript still behave like normal Android applications, so you + need an activity class that handles activity lifecycle callback events appropriately. The activity class + also sets your {@link android.renderscript.RSSurfaceView} view class to be the main content view of the + activity or uses your {@link android.renderscript.RSTextureView} + in a {@link android.view.ViewGroup} alongside other views.</p> + + <p>The following code shows how the <a href="{@docRoot}resources/samples/RenderScript/Fountain/index.html">Fountain</a> + sample declares its activity class:</p> <pre> -public class HelloWorldActivity extends Activity { +package com.example.android.rs.fountain; + +import android.app.Activity; +import android.os.Bundle; +import android.util.Log; + +public class Fountain extends Activity { + + private static final String LOG_TAG = "libRS_jni"; + private static final boolean DEBUG = false; + private static final boolean LOG_ENABLED = false; - //Custom view to use with RenderScript - private HelloWorldView view; + private FountainView mView; + @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); - // Create surface view and set it as the content of our Activity - mView = new HelloWorldView(this); - setContentView(view); + + // Create our Preview view and set it as + // the content of our activity + mView = new FountainView(this); + setContentView(mView); } + @Override protected void onResume() { - // Ideally an app should implement onResume() and onPause() - // to take appropriate action when the activity loses focus + Log.e("rs", "onResume"); + + // Ideally a game should implement onResume() and onPause() + // to take appropriate action when the activity looses focus super.onResume(); - view.resume(); + mView.resume(); } + @Override protected void onPause() { - // Ideally an app should implement onResume() and onPause() - // to take appropriate action when the activity loses focus + Log.e("rs", "onPause"); + + // Ideally a game should implement onResume() and onPause() + // to take appropriate action when the activity looses focus super.onPause(); - view.pause(); + mView.pause(); + + } + + static void log(String message) { + if (LOG_ENABLED) { + Log.v(LOG_TAG, message); + } } } </pre> +<p>Now that you have an idea of what is involved in a Renderscript graphics application, you can +start building your own. It might be easiest to begin with one of the +<a href="{@docRoot}resources/samples/RenderScript/index.html">Renderscript samples</a> as a starting +point if this is your first time using Renderscript.</p> + <h2 id="drawing">Drawing</h2> <p>The following sections describe how to use the graphics functions to draw with Renderscript.</p> - <h3 id="drawing-rsg">Drawing using the rsgDraw functions</h3> - <p>The native RenderScript APIs provide a few convenient functions to easily draw a polygon to - the screen. You call these in your <code>root()</code> function to have them render to the - surface view. These functions are available for simple drawing and should not be used for complex - graphics rendering:</p> + <h3 id="drawing-rsg">Simple drawing</h3> + + <p>The native Renderscript APIs provide a few convenient functions to easily draw a polygon or text to + the screen. You call these in your <code>root()</code> function to have them render to the {@link + android.renderscript.RSSurfaceView} or {@link android.renderscript.RSTextureView}. These functions are + available for simple drawing and should not be used for complex graphics rendering:</p> <ul> <li><code>rsgDrawRect()</code>: Sets up a mesh and draws a rectangle to the screen. It uses the @@ -360,31 +531,32 @@ public class HelloWorldActivity extends Activity { <li><code>rsgDrawQuad()</code>: Sets up a mesh and draws a quadrilateral to the screen.</li> - <li><code>rsgDrawQuadTexCoords()</code>: Sets up a mesh and draws a textured quadrilateral to - the screen.</li> + <li><code>rsgDrawQuadTexCoords()</code>: Sets up a mesh and draws a quadrilateral to the screen + using the provided coordinates of a texture.</li> + + <li><code>rsgDrawText()</code>: Draws specified text to the screen. Use <code>rsgFontColor()</code> + to set the color of the text.</li> </ul> <h3 id="drawing-mesh">Drawing with a mesh</h3> - <p>When you want to draw complex shapes and textures to the screen, instantiate a {@link - android.renderscript.Mesh} and draw it to the screen with <code>rsgDrawMesh()</code>. A {@link + <p>When you want to render complex scenes to the screen, instantiate a {@link + android.renderscript.Mesh} and draw it with <code>rsgDrawMesh()</code>. A {@link android.renderscript.Mesh} is a collection of allocations that represent vertex data (positions, - normals, texture coordinates) and index data such as triangles and lines. You can build a Mesh in - three different ways:</p> + normals, texture coordinates) and index data that provides information on how to draw triangles + and lines with the provided vertex data. You can build a Mesh in three different ways:</p> <ul> <li>Build the mesh with the {@link android.renderscript.Mesh.TriangleMeshBuilder} class, which - allows you to specify a set of vertices and indices for each triangle that you want to draw. - The downside of doing it this way is there is no way to specify the vertices in your native - RenderScript code.</li> + allows you to specify a set of vertices and indices for each triangle that you want to draw.</li> <li>Build the mesh using an {@link android.renderscript.Allocation} or a set of {@link android.renderscript.Allocation}s with the {@link android.renderscript.Mesh.AllocationBuilder} - class. This allows you to build a mesh with vertices already stored in memory, which allows you - to set the vertices in native or Android code.</li> + class. This approach allows you to build a mesh with vertices already stored in memory, which allows you + to specify the vertices in Renderscript or Android framework code.</li> - <li>Build the mesh with the {@link android.renderscript.Mesh.Builder} class. This is a - convenience method for when you know what data types you want to use to build your mesh, but + <li>Build the mesh with the {@link android.renderscript.Mesh.Builder} class. You should use + this convenience method when you know the data types you want to use to build your mesh, but don't want to make separate memory allocations like with {@link android.renderscript.Mesh.AllocationBuilder}. You can specify the types that you want and this mesh builder automatically creates the memory allocations for you.</li> @@ -398,7 +570,7 @@ public class HelloWorldActivity extends Activity { vertex 0, 1, and 2 (the vertices are drawn counter-clockwise).</p> <pre> int float2VtxSize = 2; -Mesh.TriangleMeshBuilder triangle = new Mesh.TriangleMeshBuilder(renderscriptGL, +Mesh.TriangleMeshBuilder triangles = new Mesh.TriangleMeshBuilder(renderscriptGL, float2VtxSize, Mesh.TriangleMeshBuilder.COLOR); triangles.addVertex(300.f, 300.f); triangles.addVertex(150.f, 450.f); @@ -421,7 +593,7 @@ Mesh smP = smb.create(); script.set_mesh(smP); </pre> - <p>In your native RenderScript code, draw the built mesh to the screen:</p> + <p>In your Renderscript code, draw the built mesh to the screen:</p> <pre> rs_mesh mesh; ... @@ -435,18 +607,18 @@ return 0; //specify a non zero, positive integer to specify the frame refresh. } </pre> - <h2 id="shaders">Shaders</h2> + <h2 id="shader">Programs</h2> <p>You can attach four program objects to the {@link android.renderscript.RenderScriptGL} context to customize the rendering pipeline. For example, you can create vertex and fragment shaders in - GLSL or build a raster program object with provided methods without writing GLSL code. The four - program objects mirror a traditional graphical rendering pipeline:</p> + GLSL or build a raster program object that controls culling. The four programs mirror a + traditional graphical rendering pipeline:</p> <table> <tr> <th>Android Object Type</th> - <th>RenderScript Native Type</th> + <th>Renderscript Native Type</th> <th>Description</th> </tr> @@ -457,17 +629,17 @@ return 0; //specify a non zero, positive integer to specify the frame refresh. <td>rs_program_vertex</td> <td> - <p>The RenderScript vertex program, also known as a vertex shader, describes the stage in + <p>The Renderscript vertex program, also known as a vertex shader, describes the stage in the graphics pipeline responsible for manipulating geometric data in a user-defined way. - The object is constructed by providing RenderScript with the following data:</p> + The object is constructed by providing Renderscript with the following data:</p> <ul> - <li>An Element describing its varying inputs or attributes</li> + <li>An {@link android.renderscript.Element} describing its varying inputs or attributes</li> <li>GLSL shader string that defines the body of the program</li> - <li>a Type that describes the layout of an Allocation containing constant or uniform - inputs</li> + <li>a {@link android.renderscript.Type} that describes the layout of an + Allocation containing constant or uniform inputs</li> </ul> <p>Once the program is created, bind it to the {@link android.renderscript.RenderScriptGL} @@ -475,22 +647,29 @@ return 0; //specify a non zero, positive integer to specify the frame refresh. bindProgramVertex()}. It is then used for all subsequent draw calls until you bind a new program. If the program has constant inputs, the user needs to bind an allocation containing those inputs. The allocation's type must match the one provided during creation. - The RenderScript library then does all the necessary plumbing to send those constants to + </p> + + <p>The Renderscript runtime then does all the necessary plumbing to send those constants to the graphics hardware. Varying inputs to the shader, such as position, normal, and texture - coordinates are matched by name between the input Element and the Mesh object being drawn. - The signatures don't have to be exact or in any strict order. As long as the input name in - the shader matches a channel name and size available on the mesh, the run-time would take - care of connecting the two. Unlike OpenGL, there is no need to link the vertex and fragment - programs.</p> - - <p>To bind shader constructs to the Program, declare a struct containing the necessary - shader constants in your native RenderScript code. This struct is generated into a - reflected class that you can use as a constant input element during the Program's creation. - It is an easy way to create an instance of this struct as an allocation. You would then - bind this Allocation to the Program and the RenderScript system sends the data that is - contained in the struct to the hardware when necessary. To update shader constants, you - change the values in the Allocation and notify the native RenderScript code of the - change.</p> + coordinates are matched by name between the input {@link android.renderscript.Element} + and the mesh object that is being drawn. The signatures don't have to be exact or in any + strict order. As long as the input name in the shader matches a channel name and size + available on the mesh, the Renderscript runtime handles connecting the two. Unlike OpenGL + there is no need to link the vertex and fragment programs.</p> + + <p>To bind shader constants to the program, declare a <code>struct</code> that contains the necessary + shader constants in your Renderscript code. This <code>struct</code> is generated into a + reflected class that you can use as a constant input element during the program's creation. + It is an easy way to create an instance of this <code>struct</code> as an allocation. You would then + bind this {@link android.renderscript.Allocation} to the program and the + Renderscript runtime sends the data that is contained in the <code>struct</code> to the hardware + when necessary. To update shader constants, you change the values in the + {@link android.renderscript.Allocation} and notify the Renderscript + code of the change.</p> + + <p>The {@link android.renderscript.ProgramVertexFixedFunction.Builder} class also + lets you build a simple vertex shader without writing GLSL code. + </p> </td> </tr> @@ -500,26 +679,33 @@ return 0; //specify a non zero, positive integer to specify the frame refresh. <td>rs_program_fragment</td> <td> - <p>The RenderScript fragment program, also known as the fragment shader, is responsible for + <p>The Renderscript fragment program, also known as a fragment shader, is responsible for manipulating pixel data in a user-defined way. It's constructed from a GLSL shader string - containing the program body, textures inputs, and a Type object describing the constants - used by the program. Like the vertex programs, when an allocation with constant input + containing the program body, texture inputs, and a {@link android.renderscript.Type} + object that describes the constants + used by the program. Like the vertex programs, when an {@link android.renderscript.Allocation} + with constant input values is bound to the shader, its values are sent to the graphics program automatically. - Note that the values inside the allocation are not explicitly tracked. If they change - between two draw calls using the same program object, notify the runtime of that change by - calling rsgAllocationSyncAll so it could send the new values to hardware. Communication + Note that the values inside the {@link android.renderscript.Allocation} are not explicitly tracked. + If they change between two draw calls using the same program object, notify the runtime of that change by + calling <code>rsgAllocationSyncAll()</code>, so it can send the new values to hardware. Communication between the vertex and fragment programs is handled internally in the GLSL code. For - example, if the fragment program is expecting a varying input called varTex0, the GLSL code + example, if the fragment program is expecting a varying input called <code>varTex0</code>, the GLSL code inside the program vertex must provide it.</p> - <p>To bind shader constants to this program, declare a struct containing the necessary - shader constants in your native RenderScript code. This struct is generated into a - reflected class that you can use as a constant input element during the Program's creation. - It is an easy way to create an instance of this struct as an allocation. You would then - bind this Allocation to the Program and the RenderScript system sends the data that is - contained in the struct to the hardware when necessary. To update shader constants, you - change the values in the Allocation and notify the native RenderScript code of the - change.</p> + <p>To bind shader constructs to the program, declare a <code>struct</code> that contains the necessary + shader constants in your Renderscript code. This <code>struct</code> is generated into a + reflected class that you can use as a constant input element during the program's creation. + It is an easy way to create an instance of this <code>struct</code> as an allocation. You would then + bind this {@link android.renderscript.Allocation} to the program and the + Renderscript runtime sends the data that is contained in the <code>struct</code> to the hardware + when necessary. To update shader constants, you change the values in the + {@link android.renderscript.Allocation} and notify the Renderscript + code of the change.</p> + + <p>The {@link android.renderscript.ProgramFragmentFixedFunction.Builder} class also + lets you build a simple fragment shader without writing GLSL code. + </p> </td> </tr> @@ -528,7 +714,7 @@ return 0; //specify a non zero, positive integer to specify the frame refresh. <td>rs_program_store</td> - <td>The RenderScript ProgramStore contains a set of parameters that control how the graphics + <td>The Renderscript store program contains a set of parameters that control how the graphics hardware writes to the framebuffer. It could be used to enable and disable depth writes and testing, setup various blending modes for effects like transparency and define write masks for color components.</td> @@ -539,12 +725,12 @@ return 0; //specify a non zero, positive integer to specify the frame refresh. <td>rs_program_raster</td> - <td>Program raster is primarily used to specify whether point sprites are enabled and to + <td>The Renderscript raster program is primarily used to specify whether point sprites are enabled and to control the culling mode. By default back faces are culled.</td> </tr> </table> - <p>The following example defines a vertex shader in GLSL and binds it to the RenderScript:</p> + <p>The following example defines a vertex shader in GLSL and binds it to a Renderscript context object:</p> <pre> private RenderScriptGL glRenderer; //rendering context private ScriptField_Point mPoints; //vertices @@ -567,49 +753,37 @@ return 0; //specify a non zero, positive integer to specify the frame refresh. ProgramVertex pvs = sb.create(); pvs.bindConstants(mVpConsts.getAllocation(), 0); glRenderer.bindProgramVertex(pvs); - - </pre> + <p>The <a href= "{@docRoot}resources/samples/RenderScript/MiscSamples/src/com/example/android/rs/miscsamples/RsRenderStatesRS.html"> RsRenderStatesRS</a> sample has many examples on how to create a shader without writing GLSL.</p> - <h3 id="shader-bindings">Shader bindings</h3> + <h3 id="shader-bindings">Program bindings</h3> - <p>You can also set four pragmas that control the shaders' default bindings to the {@link + <p>You can also declare four pragmas that control default program bindings to the {@link android.renderscript.RenderScriptGL} context when the script is executing:</p> <ul> - <li>stateVertex</li> + <li><code>stateVertex</code></li> - <li>stateFragment</li> + <li><code>stateFragment</code></li> - <li>stateRaster</li> + <li><code>stateRaster</code></li> - <li>stateStore</li> + <li><code>stateStore</code></li> </ul> <p>The possible values for each pragma are <code>parent</code> or <code>default</code>. Using - <code>default</code> binds the shaders to the graphical context with the system defaults. The - default shader is defined below:</p> - <pre> -("varying vec4 varColor;\n"); -("varying vec2 varTex0;\n"); -("void main() {\n"); -(" gl_Position = UNI_MVP * ATTRIB_position;\n"); -(" gl_PointSize = 1.0;\n"); -(" varColor = ATTRIB_color;\n"); -(" varTex0 = ATTRIB_texture0;\n"); -("}\n"); -</pre> + <code>default</code> binds the shaders to the graphical context with the system defaults.</p> <p>Using <code>parent</code> binds the shaders in the same manner as it is bound in the calling script. If this is the root script, the parent state is taken from the bind points that are set by the {@link android.renderscript.RenderScriptGL} bind methods.</p> - <p>For example, you can define this at the top of your native graphics RenderScript code to have - the Vertex and Store shaders inherent the bind properties from their parent scripts:</p> + <p>For example, you can define this at the top of your graphics Renderscript code to have + the vertex and store programs inherent the bind properties from their parent scripts:</p> <pre> #pragma stateVertex(parent) #pragma stateStore(parent) @@ -618,18 +792,202 @@ return 0; //specify a non zero, positive integer to specify the frame refresh. <h3 id="shader-sampler">Defining a sampler</h3> <p>A {@link android.renderscript.Sampler} object defines how data is extracted from textures. - Samplers are bound to Program objects (currently only a Fragment Program) alongside the texture - whose sampling they control. These objects are used to specify such things as edge clamping - behavior, whether mip-maps are used, and the amount of anisotropy required. There might be - situations where hardware does not support the desired behavior of the sampler. In these cases, - the runtime attempts to provide the closest possible approximation. For example, the user - requested 16x anisotropy, but only 8x was set because it's the best available on the - hardware.</p> + Samplers are bound to a {@link android.renderscript.ProgramFragment} alongside the texture + whose sampling they control. These + objects are used to specify such things as edge clamping behavior, whether mip-maps are used, and + the amount of anisotropy required. There might be situations where hardware does not support the + desired behavior of the sampler. In these cases, the Renderscript runtime attempts to provide the + closest possible approximation. For example, the user requested 16x anisotropy, but only 8x was + set because it's the best available on the hardware.</p> <p>The <a href= "{@docRoot}resources/samples/RenderScript/MiscSamples/src/com/example/android/rs/miscsamples/RsRenderStatesRS.html"> RsRenderStatesRS</a> sample has many examples on how to create a sampler and bind it to a Fragment program.</p> - -</body> -</html> + + + +<h2 id="fbo">Rendering to a Framebuffer Object</h2> + +<p>Framebuffer objects allow you to render offscreen instead of in the default onscreen +framebuffer. This approach might be useful for situations where you need to post-process a texture before +rendering it to the screen, or when you want to composite two scenes in one such as rendering a rear-view +mirror of a car. There are two buffers associated with a framebuffer object: a color buffer +and a depth buffer. The color buffer (required) contains the actual pixel data of the scene +that you are rendering, and the depth buffer (optional) contains the values necessary to figure +out what vertices are drawn depending on their z-values.</p> + +<p>In general, you need to do the following to render to a framebuffer object:</p> + +<ul> + <li>Create {@link android.renderscript.Allocation} objects for the color buffer and + depth buffer (if needed). Specify the {@link + android.renderscript.Allocation#USAGE_GRAPHICS_RENDER_TARGET} usage attribute for these + allocations to notify the Renderscript runtime to use these allocations for the framebuffer + object. For the color buffer allocation, you most likely need to declare the {@link + android.renderscript.Allocation#USAGE_GRAPHICS_TEXTURE} usage attribute + to use the color buffer as a texture, which is the most common use of the framebuffer object.</li> + + <li>Tell the Renderscript runtime to render to the framebuffer object instead of the default + framebuffer by calling <code>rsgBindColorTarget()</code> and passing it the color buffer + allocation. If applicable, call <code>rsgBindDepthTarget()</code> passing in the depth buffer + allocation as well.</li> + + <li>Render your scene normally with the <code>rsgDraw</code> functions. The scene will be + rendered into the color buffer instead of the default onscreen framebuffer.</li> + + <li>When done, tell the Renderscript runtime stop rendering to the color buffer and back + to the default framebuffer by calling <code>rsgClearAllRenderTargets()</code>.</li> + + <li>Create a fragment shader and bind a the color buffer to it as a texture.</li> + + <li>Render your scene to the default framebuffer. The texture will be used according + to the way you setup your fragment shader.</li> +</ul> + +<p>The following example shows you how to render to a framebuffer object by modifying the +<a href="{@docRoot}guide/resources/renderscript/Fountain/">Fountain</a> Renderscript sample. The end +result is the <a href="{@docRoot}guide/resources/renderscript/FountainFBO/">FountainFBO</a> sample. +The modifications render the exact same scene into a framebuffer object as it does the default +framebuffer. The framebuffer object is then rendered into the default framebuffer in a small +area at the top left corner of the screen.</p> + +<ol> + <li>Modify <code>fountain.rs</code> and add the following global variables. This creates setter + methods when this file is reflected into a <code>.java</code> file, allowing you to allocate + memory in your Android framework code and binding it to the Renderscript runtime. +<pre> +//allocation for color buffer +rs_allocation gColorBuffer; +//fragment shader for rendering without a texture (used for rendering to framebuffer object) +rs_program_fragment gProgramFragment; +//fragment shader for rendering with a texture (used for rendering to default framebuffer) +rs_program_fragment gTextureProgramFragment; +</pre> + </li> + + <li>Modify the root function of <code>fountain.rs</code> to look like the following code. The + modifications are commented: +<pre> +int root() { + float dt = min(rsGetDt(), 0.1f); + rsgClearColor(0.f, 0.f, 0.f, 1.f); + const float height = rsgGetHeight(); + const int size = rsAllocationGetDimX(rsGetAllocation(point)); + float dy2 = dt * (10.f); + Point_t * p = point; + for (int ct=0; ct < size; ct++) { + p->delta.y += dy2; + p->position += p->delta; + if ((p->position.y > height) && (p->delta.y > 0)) { + p->delta.y *= -0.3f; + } + p++; + } + //Tell Renderscript runtime to render to the frame buffer object + rsgBindColorTarget(gColorBuffer, 0); + //Begin rendering on a white background + rsgClearColor(1.f, 1.f, 1.f, 1.f); + rsgDrawMesh(partMesh); + + //When done, tell Renderscript runtime to stop rendering to framebuffer object + rsgClearAllRenderTargets(); + + //Bind a new fragment shader that declares the framebuffer object to be used as a texture + rsgBindProgramFragment(gTextureProgramFragment); + + //Bind the framebuffer object to the fragment shader at slot 0 as a texture + rsgBindTexture(gTextureProgramFragment, 0, gColorBuffer); + //Draw a quad using the framebuffer object as the texture + float startX = 10, startY = 10; + float s = 256; + rsgDrawQuadTexCoords(startX, startY, 0, 0, 1, + startX, startY + s, 0, 0, 0, + startX + s, startY + s, 0, 1, 0, + startX + s, startY, 0, 1, 1); + + //Rebind the original fragment shader to render as normal + rsgBindProgramFragment(gProgramFragment); + + //Render the main scene + rsgDrawMesh(partMesh); + + return 1; +} +</pre> + </li> + + <li>In the <code>FountainRS.java</code> file, modify the <code>init()</code> method to look + like the following code. The modifications are commented: + +<pre> +/* Add necessary members */ +private ScriptC_fountainfbo mScript; +private Allocation mColorBuffer; +private ProgramFragment mProgramFragment; +private ProgramFragment mTextureProgramFragment; + +public void init(RenderScriptGL rs, Resources res) { + mRS = rs; + mRes = res; + + ScriptField_Point points = new ScriptField_Point(mRS, PART_COUNT); + + Mesh.AllocationBuilder smb = new Mesh.AllocationBuilder(mRS); + smb.addVertexAllocation(points.getAllocation()); + smb.addIndexSetType(Mesh.Primitive.POINT); + Mesh sm = smb.create(); + + mScript = new ScriptC_fountainfbo(mRS, mRes, R.raw.fountainfbo); + mScript.set_partMesh(sm); + mScript.bind_point(points); + + ProgramFragmentFixedFunction.Builder pfb = new ProgramFragmentFixedFunction.Builder(rs); + pfb.setVaryingColor(true); + mProgramFragment = pfb.create(); + mScript.set_gProgramFragment(mProgramFragment); + + /* Second fragment shader to use a texture (framebuffer object) to draw with */ + pfb.setTexture(ProgramFragmentFixedFunction.Builder.EnvMode.REPLACE, + ProgramFragmentFixedFunction.Builder.Format.RGBA, 0); + + /* Set the fragment shader in the Renderscript runtime */ + mTextureProgramFragment = pfb.create(); + mScript.set_gTextureProgramFragment(mTextureProgramFragment); + + /* Create the allocation for the color buffer */ + Type.Builder colorBuilder = new Type.Builder(mRS, Element.RGBA_8888(mRS)); + colorBuilder.setX(256).setY(256); + mColorBuffer = Allocation.createTyped(mRS, colorBuilder.create(), + Allocation.USAGE_GRAPHICS_TEXTURE | + Allocation.USAGE_GRAPHICS_RENDER_TARGET); + + /* Set the allocation in the Renderscript runtime */ + mScript.set_gColorBuffer(mColorBuffer); + + mRS.bindRootScript(mScript); +} +</pre> + +<p class="note"><strong>Note:</strong> This sample doesn't use a depth buffer, but the following code +shows you how to declare an example depth buffer if you need to use +one for your application. The depth buffer must have the same dimensions as the color buffer: + +<pre> +Allocation mDepthBuffer; + +... + +Type.Builder b = new Type.Builder(mRS, Element.createPixel(mRS, DataType.UNSIGNED_16, + DataKind.PIXEL_DEPTH)); +b.setX(256).setY(256); +mDepthBuffer = Allocation.createTyped(mRS, b.create(), +Allocation.USAGE_GRAPHICS_RENDER_TARGET); + +</pre> +</p> +</li> + + <li>Run and use the sample. The smaller, white quad on the top-left corner is using the + framebuffer object as a texture, which renders the same scene as the main rendering.</li> +</ol> diff --git a/docs/html/guide/topics/renderscript/index.jd b/docs/html/guide/topics/renderscript/index.jd index 148705c..b2d9f84 100644 --- a/docs/html/guide/topics/renderscript/index.jd +++ b/docs/html/guide/topics/renderscript/index.jd @@ -1,4 +1,4 @@ -page.title=RenderScript +page.title=Renderscript @jd:body <div id="qv-wrapper"> @@ -6,14 +6,14 @@ page.title=RenderScript <h2>In this document</h2> <ol> - <li><a href="#overview">RenderScript System Overview</a></li> - <li> + <li><a href="#overview">Renderscript Overview</a></li> + <li><a href="#native">Renderscript Runtime Layer</a></li> + <li><a href="#reflected">Reflected Layer</a> <ol> - <li><a href="#native">Native RenderScript layer</a></li> - - <li><a href="#reflected">Reflected layer</a></li> - - <li><a href="#framework">Android framework layer</a></li> + <li><a href="#func">Functions</a></li> + <li><a href="#var">Variables</a></li> + <li><a href="#pointer">Pointers</a></li> + <li><a href="#struct">Structs</a></li> </ol> </li> @@ -21,540 +21,284 @@ page.title=RenderScript <a href="#mem-allocation">Memory Allocation APIs</a> </li> <li> - <a href="#dynamic">Dynamic Memory Allocations</a> + <a href="#memory">Working with Memory</a> <ol> - <li><a href="#pointers">Declaring pointers</a></li> - - <li><a href="#struct-pointer-reflection">How pointers are reflected</a></li> - - <li><a href="#binding">Allocating and binding memory to the RenderScript</a></li> + <li><a href="#allocating-mem">Allocating and binding memory to the Renderscript</a></li> - <li><a href="#read-write-dynamic">Reading and writing to memory</a></li> + <li><a href="#read-write">Reading and writing to memory</a></li> </ol> </li> - <li> - <a href="#static">Static Memory Allocations</a> - </li> </ol> </div> </div> - <p>RenderScript offers a high performance 3D graphics rendering and compute API at the native - level, which you write in the C (C99 standard). The main advantages of RenderScript are:</p> + <p>Renderscript offers a high performance 3D graphics rendering and compute API at the native + level that you write in C (C99 standard). The main advantages of Renderscript are:</p> <ul> - <li>Portability: RenderScript is designed to run on many types of devices with different CPU - and GPU architectures. It supports all of these architectures without having to target each - device, because the code is compiled and cached on the device at runtime.</li> + <li>Portability: Renderscript is designed to run on many types of devices with different + processor (CPU, GPU, and DSP for instance) architectures. It supports all of these architectures without + having to target each device, because the code is compiled and cached on the device + at runtime.</li> - <li>Performance: RenderScript provides similar performance to OpenGL with the NDK while - offering the portability of the OpenGL APIs provided by the Android framework ({@link - android.opengl}). In addition, it also offers a high performance compute API that is not - offered by OpenGL.</li> + <li>Performance: Renderscript provides similar performance to OpenGL with the NDK and also + provides a high performance compute API that is not offered by OpenGL.</li> - <li>Usability: RenderScript simplifies development when possible, such as eliminating JNI glue code + <li>Usability: Renderscript simplifies development when possible, such as eliminating JNI glue code and simplifying mesh setup.</li> </ul> <p>The main disadvantages are:</p> <ul> - <li>Development complexity: RenderScript introduces a new set of APIs that you have to learn. - RenderScript also handles memory differently compared to OpenGL with the Android framework APIs - or NDK.</li> + <li>Development complexity: Renderscript introduces a new set of APIs that you have to learn. + Renderscript also allocates memory differently compared to OpenGL with the Android framework APIs. + However, these issues are not hard to understand and Renderscript offers many features that + make it easier than OpenGL to initialize rendering.</li> - <li>Debugging visibility: RenderScript can potentially execute (planned feature for later releases) - on processors other than the main CPU (such as the GPU), so if this occurs, debugging becomes more difficult. + <li>Debugging visibility: Renderscript can potentially execute (planned feature for later releases) + on processors other than the main CPU (such as the GPU), so if this occurs, debugging becomes more difficult. </li> - - <li>Less features: RenderScript does not provide as many features as OpenGL such as all the compressed - texture formats or GL extensions.</li> </ul> - <p>You need to consider all of the aspects of RenderScript before deciding when to use it. The following list describes - general guidelines on when to use OpenGL (framework APIs or NDK) or RenderScript:</p> - <ul> - <li>If you are doing simple graphics rendering and performance is not critical, you probably want to use the - Android framework OpenGL APIs, which still provide adequate performance, to eliminate the added coding and debugging complexity of - RenderScript.</li> - - <li>If you want the most flexibility and features while maintaining relatively good debugging - support, you probably want to use OpenGL and the NDK. Applications that require this are high end - or complicated games, for example.</li> - - <li>If you want a solution that is portable, has good performance, - and you don't need the full feature set of OpenGL, RenderScript is a good solution. If you also - need a high performance compute language, then RenderScript offers that as well. - Good candidates for RenderScript are graphics intensive UIs that require 3D rendering, live wallpapers, - or applications that require intensive mathematical computation.</li> - </ul> - <p>For an example of RenderScript in action, install the RenderScript sample applications that + <p>For an example of Renderscript in action, install the Renderscript sample applications that are shipped with the SDK in <code><sdk_root>/samples/android-11/RenderScript</code>. - You can also see a typical use of RenderScript with the 3D carousel view in the Android 3.x + You can also see a typical use of Renderscript with the 3D carousel view in the Android 3.x versions of Google Books and YouTube.</p> - <h2 id="overview">RenderScript System Overview</h2> - - <p>The RenderScript system adopts a control and slave architecture where the low-level native + <h2 id="overview">Renderscript Overview</h2> + <p>The Renderscript runtime operates at the native level and still needs to communicate +with the Android VM, so the way a Renderscript application is setup is different from a pure VM +application. An application that uses Renderscript is still a traditional Android application that +runs in the VM, but you write Renderscript code for the parts of your program that require +it. Using Renderscript can be as simple as offloading a few math calculations or as complicated as +rendering an entire 3D game. No matter what you use it for, Renderscript remains platform +independent, so you do not have to target multiple architectures (for example, +ARM v5, ARM v7, x86).</p> + + <p>The Renderscript system adopts a control and slave architecture where the low-level Renderscript runtime code is controlled by the higher level Android system that runs in a virtual machine (VM). The - Android VM still retains all control of memory and lifecycle management and calls the native - RenderScript code when necessary. The native code is compiled to intermediate bytecode (LLVM) and - packaged inside your application's <code>.apk</code> file. On the device, the bytecode is - compiled (just-in-time) to machine code that is further optimized for the device that it is - running on. The compiled code on the device is cached, so subsequent uses of the RenderScript - enabled application do not recompile the intermediate code. RenderScript has three layers of code - to enable communication between the native and Android framework code:</p> + Android VM still retains all control of memory management and binds memory that it allocates to + the Renderscript runtime, so the Renderscript code can access it. The Android framework makes +asynchronous calls to Renderscript, and the calls are placed in a message queue and processed +as soon as possible. Figure 1 shows how the Renderscript system is structured.</p> + + <img id="figure1" src="{@docRoot}images/rs_overview.png" /> + <p class="img-caption"><strong>Figure 1.</strong> Renderscript system overview</p> + + <p>When using Renderscript, there are three layers of APIs that enable communication between the + Renderscript runtime and Android framework code:</p> <ul> - <li>The native RenderScript layer does the intensive computation or graphics rendering. You - define your native code in <code>.rs</code> and <code>.rsh</code> files.</li> - - <li>The reflected layer is a set of classes that are reflected from the native code. It is basically - a wrapper around the native code that allows the Android framework to interact with native RenderScripts. - The Android build tools automatically generate the classes for this layer during - the build process and eliminates the need to write JNI glue code, like with the NDK.</li> - - <li>The Android framework layer is comprised of the Android framework - APIs, which include the {@link android.renderscript} package. This layer gives high level commands - like, "rotate the view" or "filter the bitmap", by calling the reflected layer, which in turn calls - the native layer. </li> + <li>The Renderscript runtime APIs allow you to do the computation or graphics rendering + that is required by your application.</li> + + <li>The reflected layer APIs are a set of classes that are reflected from your Renderscript +runtime code. It is basically a wrapper around the Renderscript code that allows the Android +framework to interact with the Renderscript runtime. The Android build tools automatically generate the +classes for this layer during the build process. These classes eliminate the need to write JNI glue +code, like with the NDK.</li> + + <li>The Android framework APIs, which include the {@link android.renderscript} package, allow you to + build your application using traditional Android components such as activities and views. When + using Renderscript, this layer calls the reflected layer to access the Renderscript + runtime.</li> </ul> - <h3 id="native">Native RenderScript layer</h3> + <p></p> - <p>The native RenderScript layer consists of your RenderScript code, which is compiled and - executed in a compact and well defined runtime. Your RenderScript code has access to a limited - amount of functions because it cannot access the NDK or standard C functions, since they must be guaranteed to - run on a standard CPU. The RenderScript runtime was designed to run on different types of processors, - which may not be the CPU, so it cannot guarantee support for standard C libraries. What - RenderScript does offer is an API that supports intensive computation and graphics rendering with a collection of math - and graphics APIs.</p> + <h2 id="native">Renderscript Runtime Layer</h2> - <p>Some key features of the native RenderScript libraries include:</p> + <p>Your Renderscript code is compiled and + executed in a compact and well-defined runtime layer. The Renderscript runtime APIs offer support for +intensive computation and graphics rendering that is portable and automatically scalable to the +amount of cores available on a processor. +</p> +<p class="note"><strong>Note:</strong> The standard C functions in the NDK must be + guaranteed to run on a CPU, so Renderscript cannot access these libraries, + because Renderscript is designed to run on different types of processors.</p> - <ul> - <li>A large collection of math functions with both scalar and vector typed overloaded versions - of many common routines. Operations such as adding, multiplying, dot product, and cross product - are available.</li> +<p>You define your Renderscript code in <code>.rs</code> + and <code>.rsh</code> files in the <code>src/</code> directory of your Android project. The code + is compiled to intermediate bytecode by the + <code>llvm</code> compiler that runs as part of an Android build. When your application + runs on a device, the bytecode is then compiled (just-in-time) to machine code by another + <code>llvm</code> compiler that resides on the device. The machine code is optimized for the + device and also cached, so subsequent uses of the Renderscript enabled application does not + recompile the bytecode.</p> - <li>Conversion routines for primitive data types and vectors, matrix routines, date and time - routines, and graphics routines.</li> + <p>Some key features of the Renderscript runtime libraries include:</p> - <li>Logging functions</li> + <ul> <li>Graphics rendering functions</li> <li>Memory allocation request features</li> - <li>Data types and structures to support the RenderScript system such as Vector types for + <li>A large collection of math functions with both scalar and vector typed overloaded versions + of many common routines. Operations such as adding, multiplying, dot product, and cross product + are available as well as atomic arithmetic and comparison functions.</li> + + <li>Conversion routines for primitive data types and vectors, matrix routines, date and time + routines, and graphics routines.</li> + + <li>Data types and structures to support the Renderscript system such as Vector types for defining two-, three-, or four-vectors.</li> + + <li>Logging functions</li> </ul> - <p>The RenderScript header files and LLVM front-end libraries are located in the <code>include/</code> and - <code>clang-include/</code> directories in the - <code><sdk_root>/platforms/android-11/renderscript/</code> directory of the Android SDK. The - headers are automatically included for you, except for the RenderScript graphics specific header file, which + <p>See the Renderscript runtime API reference for more information on the available functions. The + Renderscript header files are automatically included for you, except for the Renderscript graphics header file, which you can include as follows:</p> - <pre> -#include "rs_graphics.rsh" -</pre> - <h3 id="reflected">Reflected layer</h3> +<pre>#include "rs_graphics.rsh"</pre> + + <h2 id="reflected">Reflected Layer</h2> <p>The reflected layer is a set of classes that the Android build tools generate to allow access - to the native RenderScript code from the Android VM. This layer defines entry points for - RenderScript functions and variables, so that you can interact with them with the Android - framework. This layer also provides methods and constructors that allow you to allocate memory - for pointers that are defined in your RenderScript code. The following list describes the major + to the Renderscript runtime from the Android framework. This layer also provides methods +and constructors that allow you to allocate and work with memory for pointers that are defined in +your Renderscript code. The following list describes the major components that are reflected:</p> <ul> <li>Every <code>.rs</code> file that you create is generated into a class named - <code>ScriptC_<em>renderscript_filename</em></code> of type {@link - android.renderscript.ScriptC}. This is the <code>.java</code> version of your <code>.rs</code> - file, which you can call from the Android framework. This class contains the following - reflections: + <code>project_root/gen/package/name/ScriptC_<em>renderscript_filename</em></code> of +type {@link android.renderscript.ScriptC}. This file is the <code>.java</code> version of your +<code>.rs</code> file, which you can call from the Android framework. This class contains the +following items reflected from the <code>.rs</code> file: <ul> - <li>Non-static functions in your <code>.rs</code> file.</li> - - <li>Non-static, global RenderScript variables. Accessor methods are generated for each - variable, so you can read and write the natively declared variables from the Android - framework. The <code>get</code> method comes with a one-way communication restriction. The - last value that is set from the Android framework is always returned during a call to a - <code>get</code> method. If the native RenderScript code changes the value, the change does - not propagate back to the Android framework layer. - If the global variables are initialized - in the native RenderScript code, those values are used to initialize the corresponding - values in the Android framework layer. If global variables are marked as - <code>const</code>, then a <code>set</code> method is not generated.</li> - <li>Global pointers generate a special method named <code>bind_<em>pointer_name</em></code> - instead of a <code>set()</code> method. This method allows you to bind the memory that is - allocated in the Android VM for the pointer to the native RenderScript (you cannot allocate - memory in your <code>.rs</code> file). You can read and write to this memory from both the - Android framework and RenderScript code. For more information, see <a href="mem-mgmt">Working - with Memory and Data</a></li> + <li>Non-static functions</li> + + <li>Non-static, global Renderscript variables. Accessor methods are generated for each + variable, so you can read and write the Renderscript variables from the Android + framework. If a global variable is initialized at the Renderscript runtime layer, those +values are used to initialize the corresponding values in the Android framework layer. If global +variables are marked as <code>const</code>, then a <code>set</code> method is not +generated.</p></li> + + <li>Global pointers</li> </ul> </li> <li>A <code>struct</code> is reflected into its own class named - <code>ScriptField_<em>struct_name</em></code>, which extends {@link + + <code>project_root/gen/package/name/ScriptField_struct_name</em></code>, which extends {@link android.renderscript.Script.FieldBase}. This class represents an array of the <code>struct</code>, which allows you to allocate memory for one or more instances of this <code>struct</code>.</li> </ul> - <h3 id="framework">Android framework layer</h3> - - <p>The Android framework layer consists of the usual Android framework APIs, which include the - RenderScript APIs in {@link android.renderscript}. This layer handles things such as the - Activity lifecycle and memory management of your application. It issues high level commands to - the native RenderScript code through the reflected layer and receives events from the user such - as touch and input events and relays them to your RenderScript code, if needed. - </p> - - <h2 id="mem-allocation">Memory Allocation APIs</h2> - - <p>Before you begin writing your first RenderScript application, you must understand how - memory is allocated for your RenderScript code and how data is shared between the native and VM - spaces. RenderScript allows you to access allocated memory in both the native layer - and Android system layer. All dynamic and static memory is allocated by the Android VM. - The Android VM also does reference counting and garbage collection for you. - You can also explicitly free memory that you no longer need.</p> - - <p class="note"><strong>Note:</strong> To declare temporary memory in your native RenderScript - code without allocating it in the Android VM, you can still do things like instantiate a scratch - buffer using an array.</p> - - <p>The following classes support the memory management features of RenderScript in the Android - VM. You normally do not need to work with these classes directly, because the reflected layer - classes provide constructors and methods that set up the memory allocation for you. There are - some situations where you would want to use these classes directly to allocate memory on your - own, such as loading a bitmap from a resource or when you want to allocate memory for pointers to - primitive types.</p> - - <table id="mem-mgmt-table"> - <tr> - <th>Android Object Type</th> - - <th>Description</th> - </tr> - - <tr> - <td>{@link android.renderscript.Element}</td> - - <td> - <p>An element represents one cell of a memory allocation and can have two forms: Basic or - Complex.</p> - - <p>A basic element contains a single component of data of any valid RenderScript data type. - Examples of basic element data types include a single float value, a float4 vector, or a - single RGB-565 color.</p> - - <p>Complex elements contain a list of basic elements and are created from - <code>struct</code>s that you declare in your RenderScript code. The most basic primitive - type determines the data alignment of the memory. For example, a float4 vector subelement - is alligned to <code>sizeof(float)</code> and not <code>sizeof(float4)</code>. The ordering - of the elements in memory are the order in which they were added, with each component - aligned as necessary.</p> - </td> - </tr> - - <tr> - <td>{@link android.renderscript.Type}</td> - <td> - A type is a memory allocation template and consists of an element and one or more - dimensions. It describes the layout of the memory (basically an array of {@link - android.renderscript.Element}s) but does not allocate the memory for the data that it - describes. - - <p>A type consists of five dimensions: X, Y, Z, LOD (level of detail), and Faces (of a cube - map). You can assign the X,Y,Z dimensions to any positive integer value within the - constraints of available memory. A single dimension allocation has an X dimension of - greater than zero while the Y and Z dimensions are zero to indicate not present. For - example, an allocation of x=10, y=1 is considered two dimensional and x=10, y=0 is - considered one dimensional. The LOD and Faces dimensions are booleans to indicate present - or not present.</p> - </td> - </tr> - - <tr> - <td>{@link android.renderscript.Allocation}</td> +<h3 id="func">Functions</h3> +<p>Functions are reflected into the script class itself, located in +<code>project_root/gen/package/name/ScriptC_renderscript_filename</code>. For +example, if you declare the following function in your Renderscript code:</p> - <td> - <p>An allocation provides the memory for applications based on a description of the memory - that is represented by a {@link android.renderscript.Type}. Allocated memory can exist in - many memory spaces concurrently. If memory is modified in one space, you must explicitly - synchronize the memory, so that it is updated in all the other spaces that it exists - in.</p> - - <p>Allocation data is uploaded in one of two primary ways: type checked and type unchecked. - For simple arrays there are <code>copyFrom()</code> functions that take an array from the - Android system and copy it to the native layer memory store. The unchecked variants allow - the Android system to copy over arrays of structures because it does not support - structures. For example, if there is an allocation that is an array of n floats, the data - contained in a float[n] array or a byte[n*4] array can be copied.</p> - </td> - </tr> - </table> - - <h2 id="dynamic">Working with dynamic memory allocations</h2> - - <p>RenderScript has support for pointers, but you must allocate the memory in your Android framework - code. When you declare a global pointer in your <code>.rs</code> file, you allocate memory - through the appropriate reflected layer class and bind that memory to the native - RenderScript layer. You can read and write to this memory from the Android framework layer as well as the - RenderScript layer, which offers you the flexibility to modify variables in the most appropriate - layer. The following sections show you how to work with pointers, allocate memory for them, and - read and write to the memory.</p> - - <h3 id="pointers">Declaring pointers</h3> - - <p>Because RenderScript is written in C99, declaring a pointer is done in a familiar way. You can - declare pointers to a <code>struct</code> or a primitive type, but a <code>struct</code> cannot - contain pointers or nested arrays. The following code declares a <code>struct</code>, a pointer - to that <code>struct</code>, and a pointer of primitive type <code>int32_t</code> in an <code>.rs</code> file:</p> - <pre> -#pragma version(1) -#pragma rs java_package_name(com.example.renderscript) - -... - -typedef struct Point { - float2 point; - } Point_t; - - Point_t *touchPoints; - int32_t *intPointer; - -... -</pre> - -<p>You cannot allocate memory for these pointers in your RenderScript code, but the Android -build tools generate classes for you that allow you to allocate memory in the Android VM for use by -your RenderScript code. These classes also let you read and write to the memory. The next section -describes how these classes are generated through reflection.</p> - - <h3>How pointers are reflected</h3> - - <p>Global variables have a getter and setter method generated. A global pointer generates a - <code>bind_pointerName()</code> method instead of a set() method. This method allows you to bind - the memory that is allocated in the Android VM to the native RenderScript. For example, the two - pointers in the previous section generate the following accessor methods in the <code>ScriptC_<em>rs_filename</em></code> file:</p> - <pre> - - private ScriptField_Point mExportVar_touchPoints; - public void bind_touchPoints(ScriptField_Point v) { - mExportVar_touchPoints = v; - if (v == null) bindAllocation(null, mExportVarIdx_touchPoints); - else bindAllocation(v.getAllocation(), mExportVarIdx_touchPoints); - } - - public ScriptField_Point get_touchPoints() { - return mExportVar_touchPoints; - } - - private Allocation mExportVar_intPointer; - public void bind_intPointer(Allocation v) { - mExportVar_intPointer = v; - if (v == null) bindAllocation(null, mExportVarIdx_intPointer); - else bindAllocation(v, mExportVarIdx_intPointer); - } - - public Allocation get_intPointer() { - return mExportVar_intPointer; +<pre> +void touch(float x, float y, float pressure, int id) { + if (id >= 10) { + return; } -</pre> - - <h3>Allocating and binding memory to the RenderScript</h3> - - <p>When the build tools generate the reflected layer, you can use the appropriate class - (<code>ScriptField_Point</code>, in our example) to allocate memory for a pointer. To do this, - you call the constructor for the {@link android.renderscript.Script.FieldBase} class and specify - the amount of structures that you want to allocate memory for. To allocate memory for a primitive - type pointer, you must build an allocation manually, using the memory management classes - described in <a href="mem-mgmt-table">Table 1</a>. The example below allocates memory for both - the <code>intPointer</code> and <code>touchPoints</code> pointer and binds it to the - RenderScript:</p> - <pre> -private RenderScriptGL glRenderer; -private ScriptC_example script; -private Resources resources; - -public void init(RenderScriptGL rs, Resources res) { - //get the rendering context and resources from the calling method - glRenderer = rs; - resources = res; - - //allocate memory for the struct pointer, calling the constructor - ScriptField_Point touchPoints = new ScriptField_Point(glRenderer, 2); - - //Create an element manually and allocate memory for the int pointer - intPointer = Allocation.createSized(glRenderer, Element.I32(glRenderer), 2); - - //create an instance of the RenderScript, pointing it to the bytecode resource - mScript = new ScriptC_example(glRenderer, resources, R.raw.example); - - // bind the struct and int pointers to the RenderScript - mScript.bind_touchPoints(touchPoints); - script.bind_intPointer(intPointer); - - //bind the RenderScript to the rendering context - glRenderer.bindRootScript(script); + touchPos[id].x = x; + touchPos[id].y = y; + touchPressure[id] = pressure; } </pre> - <h3>Reading and writing to memory</h3> - - <p>Although you have to allocate memory within the Android VM, you can work with the memory both - in your native RenderScript code and in your Android code. Once memory is bound, the native - RenderScript can read and write to the memory directly. You can also just use the accessor - methods in the reflected classes to access the memory. If you modify memory in the Android - framework, it gets automatically synchronized to the native layer. If you modify memory in the <code>.rs</code> - file, these changes do not get propagated back to the Android framework. - For example, you can modify the struct in your Android code like this:</p> - <pre> -int index = 0; -boolean copyNow = true; -Float2 point = new Float2(0.0f, 0.0f); -touchPoints.set_point(index, point, copyNow); -</pre>then read it in your native RenderScript code like this: - <pre> -rsDebug("Printing out a Point", touchPoints[0].point.x, touchPoints[0].point.y); -</pre> +<p>then the following code is generated:</p> - <h2>Working with statically allocated memory</h2> - - <p>Non-static, global primitives and structs that you declare in your RenderScript are easier to work with, - because the memory is statically allocated at compile time. Accessor methods to set and get these - variables are generated when the Android build tools generate the reflected layer classes. You - can get and set these variables using the provided accessor methods. - <p class="note"><strong>Note:</strong> The <code>get</code> method comes with a one-way communication restriction. The last value - that is set from the Android framework is always returned during a call to a <code>get</code> - method. If the native RenderScript code changes the value, the change does not propagate back to - the Android framework layer. If the global variables are initialized in the native RenderScript - code, those values are used to initialize the corresponding values in the Android framework - layer. If global variables are marked as <code>const</code>, then a <code>set</code> method is - not generated.</p> - </p> - - <p>For example, if you declare the following primitive in your RenderScript code:</p> - <pre> - uint32_t unsignedInteger = 1; - +<pre> +public void invoke_touch(float x, float y, float pressure, int id) { + FieldPacker touch_fp = new FieldPacker(16); + touch_fp.addF32(x); + touch_fp.addF32(y); + touch_fp.addF32(pressure); + touch_fp.addI32(id); + invoke(mExportFuncIdx_touch, touch_fp); +} </pre> -<p>then the following code is generated in <code>ScriptC_<em>script_name</em>.java</code>:</p> - <pre> - private final static int mExportVarIdx_unsignedInteger = 9; - private long mExportVar_unsignedInteger; - public void set_unsignedInteger(long v) { - mExportVar_unsignedInteger = v; - setVar(mExportVarIdx_unsignedInteger, v); - } +<p> +Functions cannot have a return value, because the Renderscript system is designed to be +asynchronous. When your Android framework code calls into Renderscript, the call is queued and is +executed when possible. This restriction allows the Renderscript system to function without constant +interruption and increases efficiency. If functions were allowed to have return values, the call +would block until the value was returned.</p> - public long get_unsignedInteger() { - return mExportVar_unsignedInteger; - } -</pre> +<p> +If you want the Renderscript code to send a value back to the Android framework, use the +<a href="{@docRoot}reference/renderscript/rs__core_8rsh.html"><code>rsSendToClient()</code></a> +function. +</p> - <p class="note"><strong>Note:</strong> The mExportVarIdx_unsignedInteger variable represents the - index of the <code>unsignedInteger</code>'s in an array of statically allocated primitives. You do - not need to work with or be aware of this index.</p> - - <p>For a <code>struct</code>, the Android build tools generate a class named - <code><project_root>/gen/com/example/renderscript/ScriptField_struct_name</code>. This - class represents an array of the <code>struct</code> and allows you to allocate memory for a - specified number of <code>struct</code>s. This class defines:</p> +<h3 id="var">Variables</h3> - <ul> - <li>Overloaded constructors that allow you to allocate memory. The - <code>ScriptField_<em>struct_name</em>(RenderScript rs, int count)</code> constructor allows - you to define the number of structures that you want to allocate memory for with the - <code>count</code> parameter. The <code>ScriptField_<em>struct_name</em>(RenderScript rs, int - count, int usages)</code> constructor defines an extra parameter, <code>usages</code>, that - lets you specify the memory space of this memory allocation. There are four memory space - possibilities: + <p>Variables of supported types are reflected into the script class itself, located in +<code>project_root/gen/package/name/ScriptC_renderscript_filename</code>. A set of accessor +methods are generated for each variable. For example, if you declare the following variable in +your Renderscript code:</p> + <pre>uint32_t unsignedInteger = 1;</pre> - <ul> - <li>{@link android.renderscript.Allocation#USAGE_SCRIPT}: Allocates in the script memory - space. This is the default memory space if you do not specify a memory space.</li> + <p>then the following code is generated:</p> - <li>{@link android.renderscript.Allocation#USAGE_GRAPHICS_TEXTURE}: Allocates in the - texture memory space of the GPU.</li> +<pre> +private long mExportVar_unsignedInteger; +public void set_unsignedInteger(long v){ + mExportVar_unsignedInteger = v; + setVar(mExportVarIdx_unsignedInteger, v); +} - <li>{@link android.renderscript.Allocation#USAGE_GRAPHICS_VERTEX}: Allocates in the vertex - memory space of the GPU.</li> +public long get_unsignedInteger(){ + return mExportVar_unsignedInteger; +} + </pre> - <li>{@link android.renderscript.Allocation#USAGE_GRAPHICS_CONSTANTS}: Allocates in the - constants memory space of the GPU that is used by the various program objects.</li> - </ul> - <p>You can specify one or all of these memory spaces by OR'ing them together. Doing so notifies - the RenderScript runtime that you intend on accessing the data in the specified memory spaces. The following - example allocates memory for a custom data type in both the script and vertex memory spaces:</p> + <h3 id="struct">Structs</h3> + <p>Structs are reflected into their own classes, located in + <code><project_root>/gen/com/example/renderscript/ScriptField_struct_name</code>. This + class represents an array of the <code>struct</code> and allows you to allocate memory for a + specified number of <code>struct</code>s. For example, if you declare the following struct:</p> <pre> -ScriptField_Point touchPoints = new ScriptField_Point(glRenderer, 2, -Allocation.USAGE_SCRIPT | Allocation.USAGE_GRAPHICS_VERTEX); +typedef struct Point { + float2 position; + float size; +} Point_t; </pre> - <p>If you modify the memory in one memory space and want to push the updates to the rest of - the memory spaces, call <code>rsgAllocationSyncAll()</code> in your RenderScript code to - synchronize the memory.</p> - </li> - - <li>A static nested class, <code>Item</code>, allows you to create an instance of the - <code>struct</code>, in the form of an object. This is useful if it makes more sense to work - with the <code>struct</code> in your Android code. When you are done manipulating the object, - you can push the object to the allocated memory by calling <code>set(Item i, int index, boolean - copyNow)</code> and setting the <code>Item</code> to the desired position in the array. The - native RenderScript code automatically has access to the newly written memory. - - <li>Accessor methods to get and set the values of each field in a struct. Each of these - accessor methods have an <code>index</code> parameter to specify the <code>struct</code> in the - array that you want to read or write to. Each setter method also has a <code>copyNow</code> - parameter that specifies whether or not to immediately sync this memory to the native - RenderScript layer. To sync any memory that has not been synced, call <code>copyAll()</code>.</li> - - <li>The createElement() method creates an object that describes the memory layout of the struct.</li> - - <li>resize() works much like a <code>realloc</code>, allowing you to expand previously - allocated memory, maintaining the current values that were previously set.</li> - - <li>copyAll() synchronizes memory that was set on the framework level to the native level. When you call - a set accessor method on a member, there is an optional <code>copyNow</code> boolean parameter that you can specify. Specifying - <code>true</code> synchronizes the memory when you call the method. If you specify false, you can call <code>copyAll()</code> - once, and it synchronizes memory for the all the properties that are not synchronized.</li> - </ul> - - <p>The following example shows the reflected class, <code>ScriptField_Point.java</code> that is - generated from the Point <code>struct</code>.</p> - <pre> -package com.example.renderscript; +<p>then the following code is generated in <code>ScriptField_Point.java</code>: +<pre> +package com.example.android.rs.hellocompute; import android.renderscript.*; import android.content.res.Resources; - + /** + * @hide + */ public class ScriptField_Point extends android.renderscript.Script.FieldBase { + static public class Item { - public static final int sizeof = 8; + public static final int sizeof = 12; - Float2 point; + Float2 position; + float size; Item() { - point = new Float2(); + position = new Float2(); } - } private Item mItemArray[]; private FieldPacker mIOBuffer; public static Element createElement(RenderScript rs) { Element.Builder eb = new Element.Builder(rs); - eb.add(Element.F32_2(rs), "point"); + eb.add(Element.F32_2(rs), "position"); + eb.add(Element.F32(rs), "size"); return eb.create(); } @@ -573,9 +317,11 @@ public class ScriptField_Point extends android.renderscript.Script.FieldBase { } private void copyToArray(Item i, int index) { - if (mIOBuffer == null) mIOBuffer = new FieldPacker(Item.sizeof * getType().getX()/* count */); + if (mIOBuffer == null) mIOBuffer = new FieldPacker(Item.sizeof * getType().getX()/* count + */); mIOBuffer.reset(index * Item.sizeof); - mIOBuffer.addF32(i.point); + mIOBuffer.addF32(i.position); + mIOBuffer.addF32(i.size); } public void set(Item i, int index, boolean copyNow) { @@ -585,7 +331,6 @@ public class ScriptField_Point extends android.renderscript.Script.FieldBase { copyToArray(i, index); mAllocation.setFromFieldPacker(index, mIOBuffer); } - } public Item get(int index) { @@ -593,24 +338,42 @@ public class ScriptField_Point extends android.renderscript.Script.FieldBase { return mItemArray[index]; } - public void set_point(int index, Float2 v, boolean copyNow) { - if (mIOBuffer == null) mIOBuffer = new FieldPacker(Item.sizeof * getType().getX()/* count */)fnati; + public void set_position(int index, Float2 v, boolean copyNow) { + if (mIOBuffer == null) mIOBuffer = new FieldPacker(Item.sizeof * getType().getX()/* count */); if (mItemArray == null) mItemArray = new Item[getType().getX() /* count */]; if (mItemArray[index] == null) mItemArray[index] = new Item(); - mItemArray[index].point = v; - if (copyNow) { + mItemArray[index].position = v; + if (copyNow) { mIOBuffer.reset(index * Item.sizeof); mIOBuffer.addF32(v); FieldPacker fp = new FieldPacker(8); fp.addF32(v); mAllocation.setFromFieldPacker(index, 0, fp); } + } + public void set_size(int index, float v, boolean copyNow) { + if (mIOBuffer == null) mIOBuffer = new FieldPacker(Item.sizeof * getType().getX()/* count */); + if (mItemArray == null) mItemArray = new Item[getType().getX() /* count */]; + if (mItemArray[index] == null) mItemArray[index] = new Item(); + mItemArray[index].size = v; + if (copyNow) { + mIOBuffer.reset(index * Item.sizeof + 8); + mIOBuffer.addF32(v); + FieldPacker fp = new FieldPacker(4); + fp.addF32(v); + mAllocation.setFromFieldPacker(index, 1, fp); + } } - public Float2 get_point(int index) { + public Float2 get_position(int index) { if (mItemArray == null) return null; - return mItemArray[index].point; + return mItemArray[index].position; + } + + public float get_size(int index) { + if (mItemArray == null) return 0; + return mItemArray[index].size; } public void copyAll() { @@ -627,13 +390,415 @@ public class ScriptField_Point extends android.renderscript.Script.FieldBase { System.arraycopy(mItemArray, 0, ni, 0, copySize); mItemArray = ni; } - mAllocation.resize(newSize); if (mIOBuffer != null) mIOBuffer = new FieldPacker(Item.sizeof * getType().getX()/* count */); } +} +</pre> + +<p>The generated code is provided to you as a convenience to allocate memory for structs requested +by the Renderscript runtime and to interact with <code>struct</code>s +in memory. Each <code>struct</code>'s class defines the following methods and constructors:</p> + + <ul> + <li>Overloaded constructors that allow you to allocate memory. The + <code>ScriptField_<em>struct_name</em>(RenderScript rs, int count)</code> constructor allows + you to define the number of structures that you want to allocate memory for with the + <code>count</code> parameter. The <code>ScriptField_<em>struct_name</em>(RenderScript rs, int + count, int usages)</code> constructor defines an extra parameter, <code>usages</code>, that + lets you specify the memory space of this memory allocation. There are four memory space + possibilities: + + <ul> + <li>{@link android.renderscript.Allocation#USAGE_SCRIPT}: Allocates in the script memory + space. This is the default memory space if you do not specify a memory space.</li> + + <li>{@link android.renderscript.Allocation#USAGE_GRAPHICS_TEXTURE}: Allocates in the + texture memory space of the GPU.</li> + + <li>{@link android.renderscript.Allocation#USAGE_GRAPHICS_VERTEX}: Allocates in the vertex + memory space of the GPU.</li> + + <li>{@link android.renderscript.Allocation#USAGE_GRAPHICS_CONSTANTS}: Allocates in the + constants memory space of the GPU that is used by the various program objects.</li> + </ul> + + <p>You can specify multiple memory spaces by using the bitwise <code>OR</code> operator. Doing so + notifies the Renderscript runtime that you intend on accessing the data in the + specified memory spaces. The following example allocates memory for a custom data type + in both the script and vertex memory spaces:</p> + <pre> + ScriptField_Point touchPoints = new ScriptField_Point(glRenderer, 2, + Allocation.USAGE_SCRIPT | Allocation.USAGE_GRAPHICS_VERTEX); + </pre> + + <p>If you modify the memory in one memory space and want to push the updates to the rest of + the memory spaces, call <a href="{@docRoot}reference/renderscript/rs__graphics_8rsh.html"> + <code>rsgAllocationSyncAll()</code></a> in your Renderscript code to + synchronize the memory.</p> + </li> + + <li>A static nested class, <code>Item</code>, allows you to create an instance of the + <code>struct</code>, in the form of an object. This nested class is useful if it makes more sense to work + with the <code>struct</code> in your Android code. When you are done manipulating the object, + you can push the object to the allocated memory by calling <code>set(Item i, int index, + boolean copyNow)</code> and setting the <code>Item</code> to the desired position in +the array. The Renderscript runtime automatically has access to the newly written memory. + + <li>Accessor methods to get and set the values of each field in a struct. Each of these + accessor methods have an <code>index</code> parameter to specify the <code>struct</code> in + the array that you want to read or write to. Each setter method also has a +<code>copyNow</code> parameter that specifies whether or not to immediately sync this memory +to the Renderscript runtime. To sync any memory that has not been synced, call + <code>copyAll()</code>.</li> + + <li>The <code>createElement()</code> method creates a description of the struct in memory. This + description is used to allocate memory consisting of one or many elements.</li> + + <li><code>resize()</code> works much like a <code>realloc()</code> in C, allowing you to +expand previously allocated memory, maintaining the current values that were previously +created.</li> + + <li><code>copyAll()</code> synchronizes memory that was set on the framework level to the +Renderscript runtime. When you call a set accessor method on a member, there is an optional +<code>copyNow</code> boolean parameter that you can specify. Specifying + <code>true</code> synchronizes the memory when you call the method. If you specify false, + you can call <code>copyAll()</code> once, and it synchronizes memory for all the +properties that are not yet synchronized.</li> + </ul> + + <h3 id="pointer">Pointers</h3> + <p>Pointers are reflected into the script class itself, located in +<code>project_root/gen/package/name/ScriptC_renderscript_filename</code>. You +can declare pointers to a <code>struct</code> or any of the supported Renderscript types, but a +<code>struct</code> cannot contain pointers or nested arrays. For example, if you declare the +following pointers to a <code>struct</code> and <code>int32_t</code></p> + +<pre> +typedef struct Point { + float2 position; + float size; +} Point_t; + +Point_t *touchPoints; +int32_t *intPointer; +</pre> + <p>then the following code is generated in:</p> + +<pre> +private ScriptField_Point mExportVar_touchPoints; +public void bind_touchPoints(ScriptField_Point v) { + mExportVar_touchPoints = v; + if (v == null) bindAllocation(null, mExportVarIdx_touchPoints); + else bindAllocation(v.getAllocation(), mExportVarIdx_touchPoints); +} + +public ScriptField_Point get_touchPoints() { + return mExportVar_touchPoints; +} + +private Allocation mExportVar_intPointer; +public void bind_intPointer(Allocation v) { + mExportVar_intPointer = v; + if (v == null) bindAllocation(null, mExportVarIdx_intPointer); + else bindAllocation(v, mExportVarIdx_intPointer); +} + +public Allocation get_intPointer() { + return mExportVar_intPointer; +} + </pre> + +<p>A <code>get</code> method and a special method named <code>bind_<em>pointer_name</em></code> +(instead of a <code>set()</code> method) is generated. This method allows you to bind the memory +that is allocated in the Android VM to the Renderscript runtime (you cannot allocate +memory in your <code>.rs</code> file). For more information, see <a href="#memory">Working +with Allocated Memory</a>. +</p> + + + <h2 id="mem-allocation">Memory Allocation APIs</h2> + + <p>Applications that use Renderscript still run in the Android VM. The actual Renderscript code, however, runs natively and + needs access to the memory allocated in the Android VM. To accomplish this, you must + attach the memory that is allocated in the VM to the Renderscript runtime. This +process, called binding, allows the Renderscript runtime to seamlessly work with memory that it +requests but cannot explicitly allocate. The end result is essentially the same as if you had +called <code>malloc</code> in C. The added benefit is that the Android VM can carry out garbage collection as well as +share memory with the Renderscript runtime layer. Binding is only necessary for dynamically allocated memory. Statically +allocated memory is automatically created for your Renderscript code at compile time. See <a href="#figure1">Figure 1</a> +for more information on how memory allocation occurs. +</p> + + <p>To support this memory allocation system, there are a set of APIs that allow the Android VM to +allocate memory and offer similar functionality to a <code>malloc</code> call. These classes +essentially describe how memory should be allocated and also carry out the allocation. To better +understand how these classes work, it is useful to think of them in relation to a simple +<code>malloc</code> call that can look like this: </p> + + <pre>array = (int *)malloc(sizeof(int)*10);</pre> + + <p>The <code>malloc</code> call can be broken up into two parts: the size of the memory being allocated (<code>sizeof(int)</code>), + along with how many units of that memory should be allocated (10). The Android framework provides classes for these two parts as + well as a class to represent <code>malloc</code> itself.</p> + + <p>The {@link android.renderscript.Element} class represents the (<code>sizeof(int)</code>) portion + of the <code>malloc</code> call and encapsulates one cell of a memory allocation, such as a single + float value or a struct. The {@link android.renderscript.Type} class encapsulates the {@link android.renderscript.Element} + and the amount of elements to allocate (10 in our example). You can think of a {@link android.renderscript.Type} as + an array of {@link android.renderscript.Element}s. The {@link android.renderscript.Allocation} class does the actual + memory allocation based on a given {@link android.renderscript.Type} and represents the actual allocated memory.</p> + + <p>In most situations, you do not need to call these memory allocation APIs directly. The reflected layer + classes generate code to use these APIs automatically and all you need to do to allocate memory is call a + constructor that is declared in one of the reflected layer classes and then bind + the resulting memory {@link android.renderscript.Allocation} to the Renderscript. + There are some situations where you would want to use these classes directly to allocate memory on your + own, such as loading a bitmap from a resource or when you want to allocate memory for pointers to + primitive types. You can see how to do this in the + <a href="#allocating-mem">Allocating and binding memory to the Renderscript</a> section. + The following table describes the three memory management classes in more detail:</p> + + <table id="mem-mgmt-table"> + <tr> + <th>Android Object Type</th> + + <th>Description</th> + </tr> + + <tr> + <td>{@link android.renderscript.Element}</td> + + <td> + <p>An element describes one cell of a memory allocation and can have two forms: basic or + complex.</p> + + <p>A basic element contains a single component of data of any valid Renderscript data type. + Examples of basic element data types include a single <code>float</code> value, a <code>float4</code> vector, or a + single RGB-565 color.</p> + + <p>Complex elements contain a list of basic elements and are created from + <code>struct</code>s that you declare in your Renderscript code. For instance an allocation + can contain multiple <code>struct</code>s arranged in order in memory. Each struct is considered as its + own element, rather than each data type within that struct.</p> + </td> + </tr> + + <tr> + <td>{@link android.renderscript.Type}</td> + + <td> + <p>A type is a memory allocation template and consists of an element and one or more + dimensions. It describes the layout of the memory (basically an array of {@link + android.renderscript.Element}s) but does not allocate the memory for the data that it + describes.</p> + + <p>A type consists of five dimensions: X, Y, Z, LOD (level of detail), and Faces (of a cube + map). You can assign the X,Y,Z dimensions to any positive integer value within the + constraints of available memory. A single dimension allocation has an X dimension of + greater than zero while the Y and Z dimensions are zero to indicate not present. For + example, an allocation of x=10, y=1 is considered two dimensional and x=10, y=0 is + considered one dimensional. The LOD and Faces dimensions are booleans to indicate present + or not present.</p> + </td> + </tr> + + <tr> + <td>{@link android.renderscript.Allocation}</td> + + <td> + <p>An allocation provides the memory for applications based on a description of the memory + that is represented by a {@link android.renderscript.Type}. Allocated memory can exist in + many memory spaces concurrently. If memory is modified in one space, you must explicitly + synchronize the memory, so that it is updated in all the other spaces in which it exists. + </p> + + <p>Allocation data is uploaded in one of two primary ways: type checked and type unchecked. + For simple arrays there are <code>copyFrom()</code> functions that take an array from the + Android system and copy it to the native layer memory store. The unchecked variants allow + the Android system to copy over arrays of structures because it does not support + structures. For example, if there is an allocation that is an array of n floats, the data + contained in a float[n] array or a <code>byte[n*4]</code> array can be copied.</p> + </td> + </tr> + </table> + + <h2 id="memory">Working with Memory</h2> + +<p>Non-static, global variables that you declare in your Renderscript are allocated memory at compile time. +You can work with these variables directly in your Renderscript code without having to allocate +memory for them at the Android framework level. The Android framework layer also has access to these variables +with the provided accessor methods that are generated in the reflected layer classes. If these variables are +initialized at the Renderscript runtime layer, those values are used to initialize the corresponding +values in the Android framework layer. If global variables are marked as const, then a <code>set</code> method is +not generated.</p> + + +<p class="note"><strong>Note:</strong> If you are using certain Renderscript structures that contain pointers, such as +<code>rs_program_fragment</code> and <code>rs_allocation</code>, you have to obtain an object of the +corresponding Android framework class first and then call the <code>set</code> method for that +structure to bind the memory to the Renderscript runtime. You cannot directly manipulate these structures +at the Renderscript runtime layer. This restriction is not applicable to user-defined structures +that contain pointers, because they cannot be exported to a reflected layer class +in the first place. A compiler error is generated if you try to declare a non-static, global +struct that contains a pointer. +</p> + +<p>Renderscript also has support for pointers, but you must explicitly allocate the memory in your +Android framework code. When you declare a global pointer in your <code>.rs</code> file, you +allocate memory through the appropriate reflected layer class and bind that memory to the native +Renderscript layer. You can interact with this memory from the Android framework layer as well as +the Renderscript layer, which offers you the flexibility to modify variables in the most +appropriate layer.</p> + + + + <h3 id="allocating-mem">Allocating and binding dynamic memory to the Renderscript</h3> + + <p>To allocate dynamic memory, you need to call the constructor of a + {@link android.renderscript.Script.FieldBase} class, which is the most common way. An alternative is to create an + {@link android.renderscript.Allocation} manually, which is required for things such as primitive type pointers. You should + use a {@link android.renderscript.Script.FieldBase} class constructor whenever available for simplicity. + After obtaining a memory allocation, call the reflected <code>bind</code> method of the pointer to bind the allocated memory to the + Renderscript runtime.</p> + <p>The example below allocates memory for both a primitive type pointer, + <code>intPointer</code>, and a pointer to a struct, <code>touchPoints</code>. It also binds the memory to the + Renderscript:</p> + <pre> +private RenderScriptGL glRenderer; +private ScriptC_example script; +private Resources resources; + +public void init(RenderScriptGL rs, Resources res) { + //get the rendering context and resources from the calling method + glRenderer = rs; + resources = res; + + //allocate memory for the struct pointer, calling the constructor + ScriptField_Point touchPoints = new ScriptField_Point(glRenderer, 2); + + //Create an element manually and allocate memory for the int pointer + intPointer = Allocation.createSized(glRenderer, Element.I32(glRenderer), 2); + + //create an instance of the Renderscript, pointing it to the bytecode resource + mScript = new ScriptC_example(glRenderer, resources, R.raw.example); + //bind the struct and int pointers to the Renderscript + mScript.bind_touchPoints(touchPoints); + script.bind_intPointer(intPointer); + + ... } </pre> -</body> -</html> + <h3>Reading and writing to memory</h3> + <p>You can read and write to statically and dynamically allocated memory both at the Renderscript runtime + and Android framework layer.</p> + +<p>Statically allocated memory comes with a one-way communication restriction +at the Renderscript runtime level. When Renderscript code changes the value of a variable, it is not +communicated back to the Android framework layer for efficiency purposes. The last value +that is set from the Android framework is always returned during a call to a <code>get</code> +method. However, when Android framework code modifies a variable, that change can be communicated to +the Renderscript runtime automatically or synchronized at a later time. If you need to send data +from the Renderscript runtime to the Android framework layer, you can use the +<a href="{@docRoot}reference/renderscript/rs__core_8rsh.html"><code>rsSendToClient()</code></a> function +to overcome this limitation. +</p> +<p>When working with dynamically allocated memory, any changes at the Renderscript runtime layer are propagated +back to the Android framework layer if you modified the memory allocation using its associated pointer. +Modifying an object at the Android framework layer immediately propagates that change back to the Renderscript +runtime layer.</p> + + <h4>Reading and writing to global variables</h4> + + <p>Reading and writing to global variables is a straightforward process. You can use the accessor methods + at the Android framework level or set them directly in the Renderscript code. Keep in mind that any + changes that you make in your Renderscript code are not propagated back to the Android framework layer.</p> + + <p>For example, given the following struct declared in a file named <code>rsfile.rs</code>:</p> +<pre> +typedef struct Point { + int x; + int y; +} Point_t; + +Point_t point; + +</pre> +<p>You can assign values to the struct like this directly in <code>rsfile.rs</code>. These values are not +propagated back to the Android framework level:</p> +<pre> +point.x = 1; +point.y = 1; +</pre> + +<p>You can assign values to the struct at the Android framework layer like this. These values are +propagated back to the Renderscript runtime level:</p> +<pre> +ScriptC_rsfile mScript; + +... + +Item i = new ScriptField_Point.Item(); +i.x = 1; +i.y = 1; +mScript.set_point(i); +</pre> + +<p>You can read the values in your Renderscript code like this:</p> + +<pre> +rsDebug("Printing out a Point", point.x, point.y); +</pre> + +<p>You can read the values in the Android framework layer with the following code. Keep in mind that this +code only returns a value if one was set at the Android framework level. You will get a null pointer +exception if you only set the value at the Renderscript runtime level:</p> + +<pre> +Log.i("TAGNAME", "Printing out a Point: " + mScript.get_point().x + " " + mScript.get_point().y); +System.out.println(point.get_x() + " " + point.get_y()); +</pre> + +<h4>Reading and writing global pointers</h4> + +<p>Assuming that memory has been allocated in the Android framework level and bound to the Renderscript runtime, +you can read and write memory from the Android framework level by using the <code>get</code> and <code>set</code> methods for that pointer. +In the Renderscript runtime layer, you can read and write to memory with pointers as normal and the changes are propagated +back to the Android framework layer, unlike with statically allocated memory.</p> + +<p>For example, given the following pointer to a <code>struct</code> in a file named <code>rsfile.rs</code>:</p> +<pre> +typedef struct Point { + int x; + int y; +} Point_t; + +Point_t *point; +</pre> + +<p>Assuming you already allocated memory at the Android framework layer, you can access values in +the <code>struct</code> as normal. Any changes you make to the struct via its pointer variable +are automatically available to the Android framework layer:</p> + +<pre> +point[index].x = 1; +point[index].y = 1; +</pre> + +<p>You can read and write values to the pointer at the Android framework layer as well: +<pre> +ScriptField_Point p = new ScriptField_Point(mRS, 1); + Item i = new ScriptField_Point.Item(); + i.x=100; + i.y = 100; + p.set(i, 0, true); + mScript.bind_point(p); + + points.get_x(0); //read x and y from index 0 + points.get_x(0); +</pre> + +<p>Once memory is already bound, you do not have to rebind the memory to the Renderscript +runtime every time you make a change to a value.</p> diff --git a/docs/html/guide/topics/renderscript/reference.jd b/docs/html/guide/topics/renderscript/reference.jd new file mode 100644 index 0000000..a0a9df2 --- /dev/null +++ b/docs/html/guide/topics/renderscript/reference.jd @@ -0,0 +1,18 @@ +page.title=Runtime API Reference +@jd:body + +<script language="JavaScript"> + +function autoResize(element){ + var newheight; + var newwidth; + + newheight = element.contentWindow.document.body.scrollHeight + 20; + newwidth = element.contentWindow.document.body.scrollWidth; + element.height = (newheight) + "px"; + element.width = (newwidth) + "px"; +} +</script> + + +<iframe SRC="{@docRoot}reference/renderscript/index.html" width="100%" id="iframe" marginheight="0" frameborder="0" onLoad="autoResize(this);"></iframe> diff --git a/docs/html/guide/topics/resources/animation-resource.jd b/docs/html/guide/topics/resources/animation-resource.jd index eaa698f..6473155 100644 --- a/docs/html/guide/topics/resources/animation-resource.jd +++ b/docs/html/guide/topics/resources/animation-resource.jd @@ -335,7 +335,7 @@ set.start(); <dd> <ul> <li><a href="{@docRoot}guide/topics/graphics/animation.html">Property Animation</a></li> - <li><a href="http://zoso:8080/resources/samples/ApiDemos/src/com/example/android/apis/animation/index.html">API Demos</a> for examples + <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/animation/index.html">API Demos</a> for examples on how to use the property animation system.</li> </ul> </dd> diff --git a/docs/html/guide/topics/resources/drawable-resource.jd b/docs/html/guide/topics/resources/drawable-resource.jd index 80de9f9..a34ed6c 100644 --- a/docs/html/guide/topics/resources/drawable-resource.jd +++ b/docs/html/guide/topics/resources/drawable-resource.jd @@ -1248,7 +1248,6 @@ the right edge, a right gravity clips the left edge, and neither clips both edge android:drawable="@drawable/android" android:clipOrientation="horizontal" android:gravity="left" /> -</clip> </pre> <p>The following layout XML applies the clip drawable to a View:</p> <pre> diff --git a/docs/html/guide/topics/resources/index.jd b/docs/html/guide/topics/resources/index.jd index 84eac73..3f0f1ee 100644 --- a/docs/html/guide/topics/resources/index.jd +++ b/docs/html/guide/topics/resources/index.jd @@ -28,18 +28,18 @@ to provide compatibility with different configurations, you must organize resour project's {@code res/} directory, using various sub-directories that group resources by type and configuration.</p> -<div class="figure" style="width:421px"> -<img src="{@docRoot}images/resources/resource_devices_diagram1.png" height="137" alt="" /> +<div class="figure" style="width:429px"> +<img src="{@docRoot}images/resources/resource_devices_diagram1.png" height="167" alt="" /> <p class="img-caption"> -<strong>Figure 1.</strong> Two different devices, both using default -resources.</p> +<strong>Figure 1.</strong> Two different devices, each using the default layout +(the app provides no alternative layouts).</p> </div> -<div class="figure" style="width:421px"> -<img src="{@docRoot}images/resources/resource_devices_diagram2.png" height="137" alt="" /> +<div class="figure" style="width:429px"> +<img src="{@docRoot}images/resources/resource_devices_diagram2.png" height="167" alt="" /> <p class="img-caption"> -<strong>Figure 2.</strong> Two different devices, one using alternative -resources.</p> +<strong>Figure 2.</strong> Two different devices, each using a different layout provided +for different screen sizes.</p> </div> <p>For any type of resource, you can specify <em>default</em> and multiple @@ -54,18 +54,16 @@ append an appropriate configuration qualifier to the directory name.</li> </ul> <p>For example, while your default UI -layout is saved in the {@code res/layout/} directory, you might specify a different UI layout to +layout is saved in the {@code res/layout/} directory, you might specify a different layout to be used when the screen is in landscape orientation, by saving it in the {@code res/layout-land/} directory. Android automatically applies the appropriate resources by matching the device's current configuration to your resource directory names.</p> -<p>Figure 1 demonstrates how a collection of default resources from an application are applied -to two different devices when there are no alternative resources available. Figure 2 shows -the same application with a set of alternative resources that qualify for one of the device -configurations, thus, the two devices uses different resources.</p> +<p>Figure 1 illustrates how the system applies the same layout for +two different devices when there are no alternative resources available. Figure 2 shows +the same application when it adds an alternative layout resource for larger screens.</p> -<p>The information above is just an introduction to how application resources work on Android. -The following documents provide a complete guide to how you can organize your application resources, +<p>The following documents provide a complete guide to how you can organize your application resources, specify alternative resources, access them in your application, and more:</p> <dl> diff --git a/docs/html/guide/topics/resources/localization.jd b/docs/html/guide/topics/resources/localization.jd index 9affb15..c2b668d 100755 --- a/docs/html/guide/topics/resources/localization.jd +++ b/docs/html/guide/topics/resources/localization.jd @@ -186,7 +186,7 @@ speak. </p> and can include other types of resources such as animations.
<br>
<code> res/drawable/</code>(required directory holding at least
- one graphic file, for the application's icon in the Market)<br>
+ one graphic file, for the application's icon on Google Play)<br>
<code> res/layout/</code> (required directory holding an XML
file that defines the default layout)<br>
<code> res/anim/</code> (required if you have any
@@ -507,7 +507,7 @@ the new locale. </p> <h2 id="publishing">Publishing Localized Applications</h2>
-<p>The Android Market is
+<p>The Google Play is
the main application distribution system for Android devices. To publish a
localized application, you need to sign your application, version it, and go
through all the other steps described in <a
@@ -521,7 +521,7 @@ different locale, follow these guidelines:</p> href="{@docRoot}guide/publishing/app-signing.html#strategies">Signing
Strategies</a>. </li>
<li>Give each .apk file a different application name. Currently it is
-impossible to put two applications into the Android Market that have exactly the
+impossible to publish two applications on Google Play that have exactly the
same name.</li>
<li>Include a complete set of default resources in each .apk file.</li>
</ul>
@@ -638,7 +638,7 @@ border="0"></td> <tr>
<td valign="top" align="center"><img src="../../../images/resources/arrow.png" alt="arrow" width="26"
border="0"></td>
- <td>Upload your .apk file or files to Market, selecting the appropriate
+ <td>Upload your .apk file or files to Google Play, selecting the appropriate
languages as
you upload. (For more details, see <a
href="{@docRoot}guide/publishing/publishing.html">Publishing Your
diff --git a/docs/html/guide/topics/resources/more-resources.jd b/docs/html/guide/topics/resources/more-resources.jd index 972eab9..d37b9f8 100644 --- a/docs/html/guide/topics/resources/more-resources.jd +++ b/docs/html/guide/topics/resources/more-resources.jd @@ -216,27 +216,29 @@ is specified with a number followed by a unit of measure. For example: 10px, 2in, 5sp. The following units of measure are supported by Android:</p> <dl> <dt>{@code dp}</dt> - <dd>Density-independent Pixels - an abstract unit that is based on the physical density of the -screen. These units are relative to a 160 dpi (dots per inch) screen, so <em>{@code 160dp} is -always one inch</em> regardless of the screen density. The ratio of dp-to-pixel will change with the -screen density, but not necessarily in direct proportion. You should use these units when specifying -view dimensions in your layout, so the UI properly scales to render at the same actual size on -different screens. (The compiler accepts both "dip" and "dp", though "dp" is more consistent with -"sp".)</dd> + <dd>Density-independent Pixels - An abstract unit that is based on the physical density of the +screen. These units are relative to a 160 dpi (dots per inch) screen, on which 1dp is roughly equal +to 1px. When running on a higher density screen, the number of pixels used to draw 1dp is scaled up +by a factor appropriate for the screen's dpi. Likewise, when on a lower density screen, the number +of pixels used for 1dp is scaled down. The ratio of dp-to-pixel will change with the screen density, +but not necessarily in direct proportion. Using dp units (instead of px units) is a simple solution +to making the view dimensions in your layout resize properly for different screen densities. In +other words, it provides consistency for the real-world sizes of your UI elements across different +devices.</dd> <dt>{@code sp}</dt> - <dd>Scale-independent Pixels - this is like the dp unit, but it is also scaled by the user's font + <dd>Scale-independent Pixels - This is like the dp unit, but it is also scaled by the user's font size preference. It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen density and the user's preference.</dd> <dt>{@code pt}</dt> <dd>Points - 1/72 of an inch based on the physical size of the screen.</dd> <dt>{@code px}</dt> - <dd>Pixels - corresponds to actual pixels on the screen. This unit of measure is not recommended because + <dd>Pixels - Corresponds to actual pixels on the screen. This unit of measure is not recommended because the actual representation can vary across devices; each devices may have a different number of pixels per inch and may have more or fewer total pixels available on the screen.</dd> <dt>{@code mm}</dt> - <dd>Millimeters - based on the physical size of the screen.</dd> + <dd>Millimeters - Based on the physical size of the screen.</dd> <dt>{@code in}</dt> - <dd>Inches - based on the physical size of the screen.</dd> + <dd>Inches - Based on the physical size of the screen.</dd> </dl> <p class="note"><strong>Note:</strong> A dimension is a simple resource that is referenced diff --git a/docs/html/guide/topics/resources/providing-resources.jd b/docs/html/guide/topics/resources/providing-resources.jd index 252c153..b33a097 100644 --- a/docs/html/guide/topics/resources/providing-resources.jd +++ b/docs/html/guide/topics/resources/providing-resources.jd @@ -207,10 +207,10 @@ resources.</p> <h2 id="AlternativeResources">Providing Alternative Resources</h2> -<div class="figure" style="width:421px"> -<img src="{@docRoot}images/resources/resource_devices_diagram2.png" height="137" alt="" /> +<div class="figure" style="width:429px"> +<img src="{@docRoot}images/resources/resource_devices_diagram2.png" height="167" alt="" /> <p class="img-caption"> -<strong>Figure 1.</strong> Two different devices, one using alternative resources.</p> +<strong>Figure 1.</strong> Two different devices, each using different layout resources.</p> </div> <p>Almost every application should provide alternative resources to support specific device @@ -231,6 +231,9 @@ for which these resources are to be used (defined in table 2).</li> </ul> <p>You can append more than one <em>{@code <qualifier>}</em>. Separate each one with a dash.</p> + <p class="caution"><strong>Caution:</strong> When appending multiple qualifiers, you must +place them in the same order in which they are listed in table 2. If the qualifiers are ordered +wrong, the resources are ignored.</p> </li> <li>Save the respective alternative resources in this new directory. The resource files must be named exactly the same as the default resource files.</li> @@ -254,20 +257,14 @@ screen density, but the filenames are exactly the same. This way, the resource ID that you use to reference the {@code icon.png} or {@code background.png} image is always the same, but Android selects the version of each resource that best matches the current device, by comparing the device -configuration information with the qualifiers in the alternative resource directory name.</p> +configuration information with the qualifiers in the resource directory name.</p> <p>Android supports several configuration qualifiers and you can add multiple qualifiers to one directory name, by separating each qualifier with a dash. Table 2 lists the valid configuration qualifiers, in order of precedence—if you use multiple -qualifiers for one resource directory, they must be added to the directory name in the order they +qualifiers for a resource directory, you must add them to the directory name in the order they are listed in the table.</p> -<p class="note"><strong>Note:</strong> Some configuration qualifiers were added after Android 1.0, -so not -all versions of Android support all the qualifiers listed in table 2. New qualifiers -indicate the version in which they were added. To avoid any issues, always include a set of default -resources for resources that your application uses. For more information, see the section about <a -href="#Compatibility">Providing the Best Device Compatibility with Resources</a>.</p> <p class="table-caption" id="table2"><strong>Table 2.</strong> Configuration qualifier names.</p> @@ -290,9 +287,8 @@ names.</p> from the SIM card in the device. For example, <code>mcc310</code> is U.S. on any carrier, <code>mcc310-mnc004</code> is U.S. on Verizon, and <code>mcc208-mnc00</code> is France on Orange.</p> - <p>If the device uses a radio connection (GSM phone), the MCC comes - from the SIM, and the MNC comes from the network to which the - device is connected.</p> + <p>If the device uses a radio connection (GSM phone), the MCC and MNC values come + from the SIM card.</p> <p>You can also use the MCC alone (for example, to include country-specific legal resources in your application). If you need to specify based on the language only, then use the <em>language and region</em> qualifier instead (discussed next). If you decide to use the MCC and @@ -752,6 +748,17 @@ href="#KnownIssues">Known Issues</a> for more information.</p> </table> +<p class="note"><strong>Note:</strong> Some configuration qualifiers have been added since Android +1.0, so not all versions of Android support all the qualifiers. Using a new qualifier implicitly +adds the platform version qualifier so that older devices are sure to ignore it. For example, using +a <code>w600dp</code> qualifier will automatically include the <code>v13</code> qualifier, because +the available-width qualifier was new in API level 13. To avoid any issues, always include a set of +default resources (a set of resources with <em>no qualifiers</em>). For more information, see the +section about <a href="#Compatibility">Providing the Best Device Compatibility with +Resources</a>.</p> + + + <h3 id="QualifierRules">Qualifier name rules</h3> <p>Here are some rules about using configuration qualifier names:</p> @@ -1021,8 +1028,8 @@ drawables from {@code drawable-en-port}.</p> logic:</p> -<div class="figure" style="width:280px"> -<img src="{@docRoot}images/resources/res-selection-flowchart.png" alt="" height="590" /> +<div class="figure" style="width:371px"> +<img src="{@docRoot}images/resources/res-selection-flowchart.png" alt="" height="471" /> <p class="img-caption"><strong>Figure 2.</strong> Flowchart of how Android finds the best-matching resource.</p> </div> diff --git a/docs/html/guide/topics/resources/string-resource.jd b/docs/html/guide/topics/resources/string-resource.jd index ecd2d48..5f5484e 100644 --- a/docs/html/guide/topics/resources/string-resource.jd +++ b/docs/html/guide/topics/resources/string-resource.jd @@ -358,11 +358,14 @@ values, with non-exhaustive examples in parentheses: <pre> int count = getNumberOfsongsAvailable(); Resources res = {@link android.content.Context#getResources()}; -String songsFound = res.{@link android.content.res.Resources#getQuantityString(int,int) -getQuantityString}(R.plurals.numberOfSongsAvailable, count, count); +String songsFound = res.<a +href="{@docRoot}reference/android/content/res/Resources.html#getQuantityString(int, int, java.lang.Object...)" +>getQuantityString</a>(R.plurals.numberOfSongsAvailable, count, count); </pre> -<p>When using the {@link android.content.res.Resources#getQuantityString(int,int) -getQuantityString()} method, you need to pass the {@code count} twice if your string includes + +<p>When using the <a +href="{@docRoot}reference/android/content/res/Resources.html#getQuantityString(int, int, java.lang.Object...)">{@code +getQuantityString()}</a> method, you need to pass the {@code count} twice if your string includes <a href="#FormattingAndStyling">string formatting</a> with a number. For example, for the string {@code %d songs found}, the first {@code count} parameter selects the appropriate plural string and the second {@code count} parameter is inserted into the {@code %d} placeholder. If your plural diff --git a/docs/html/guide/topics/search/search-dialog.jd b/docs/html/guide/topics/search/search-dialog.jd index e06563d..8b8e75b 100644 --- a/docs/html/guide/topics/search/search-dialog.jd +++ b/docs/html/guide/topics/search/search-dialog.jd @@ -544,7 +544,8 @@ public boolean onSearchRequested() { } </pre> -<p>If the user cancels search by pressing the BACK button, the search dialog closes and the activity +<p>If the user cancels search by pressing the <em>Back</em> button, the search dialog closes and the +activity regains input focus. You can register to be notified when the search dialog is closed with {@link android.app.SearchManager#setOnDismissListener(SearchManager.OnDismissListener) setOnDismissListener()} @@ -569,7 +570,8 @@ things happens:</p> android.content.Intent#ACTION_SEARCH} intent with a call to {@link android.app.Activity#onCreate(Bundle) onCreate()} and a new instance of the activity is brought to the top of the activity stack. There are now two instances of your -searchable activity in the activity stack (so pressing the BACK button goes back to the previous +searchable activity in the activity stack (so pressing the <em>Back</em> button goes back to the +previous instance of the searchable activity, rather than exiting the searchable activity).</li> <li>If you set {@code android:launchMode} to <code>"singleTop"</code>, then the searchable activity receives the {@link android.content.Intent#ACTION_SEARCH} intent with a call diff --git a/docs/html/guide/topics/sensors/index.jd b/docs/html/guide/topics/sensors/index.jd index e00a5b1..43903dc 100644 --- a/docs/html/guide/topics/sensors/index.jd +++ b/docs/html/guide/topics/sensors/index.jd @@ -43,7 +43,7 @@ device's temperature sensor and humidity sensor to calculate and report the dewp application might use the geomagnetic field sensor and accelerometer to report a compass bearing.</p> -<p>The Android platform supports four broad categories of sensors:</p> +<p>The Android platform supports three broad categories of sensors:</p> <ul> <li>Motion sensors @@ -81,7 +81,7 @@ following documents:</p> Sensors</a></strong></dt> <dd>Learn how to use the sensors that provide orientation and compass data, such as the orientation sensor and the geomagnetic field sensor.</dd> - <dt><strong><a href="{@docRoot}guide/topics/sensors/environment.html">Environment + <dt><strong><a href="{@docRoot}guide/topics/sensors/sensors_environment.html">Environment Sensors</a></strong></dt> <dd>Learn how to use the sensors that provide environmental data, such as the light, humidity, pressure, temperature, and proximity sensors.</dd> diff --git a/docs/html/guide/topics/sensors/sensors_motion.jd b/docs/html/guide/topics/sensors/sensors_motion.jd index 3f712b2..b6c3cb4 100644 --- a/docs/html/guide/topics/sensors/sensors_motion.jd +++ b/docs/html/guide/topics/sensors/sensors_motion.jd @@ -28,7 +28,7 @@ parent.link=index.html href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/os/RotationVectorDemo.html"> API Demos (OS - RotationVectorDemo)</a></li> <li><a -href="{@docRoot}/resources/samples/ApiDemos/src/com/example/android/apis/os/RotationVectorDemo.html" +href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/os/RotationVectorDemo.html" >API Demos (OS - Sensors)</a></li> </ol> <h2>See also</h2> diff --git a/docs/html/guide/topics/sensors/sensors_overview.jd b/docs/html/guide/topics/sensors/sensors_overview.jd index 3c5e94c..543872c 100644 --- a/docs/html/guide/topics/sensors/sensors_overview.jd +++ b/docs/html/guide/topics/sensors/sensors_overview.jd @@ -606,7 +606,7 @@ sensor is present on a device so your app can run successfully. You have two opt that a given sensor is present on a device:</p> <ul> <li>Detect sensors at runtime and enable or disable application features as appropriate.</li> - <li>Use Android Market filters to target devices with specific sensor configurations.</li> + <li>Use Google Play filters to target devices with specific sensor configurations.</li> </ul> <p>Each option is discussed in the following sections.</p> @@ -633,9 +633,9 @@ whether there's a pressure sensor on a device:</p> } </pre> -<h4>Using Android Market filters to target specific sensor configurations</h4> +<h4>Using Google Play filters to target specific sensor configurations</h4> -<p>If you are publishing your application on Android Market you can use the +<p>If you are publishing your application on Google Play you can use the <a href="{@docRoot}guide//topics/manifest/uses-feature-element.html"><code><uses-feature> </code></a> element in your manifest file to filter your application from devices that do not have the appropriate sensor configuration for your application. The @@ -650,7 +650,7 @@ following is an example manifest entry that filters apps that do not have an acc </pre> <p>If you add this element and descriptor to your application's manifest, users will see your -application on Android Market only if their device has an accelerometer.</p> +application on Google Play only if their device has an accelerometer.</p> <p>You should set the descriptor to <code>android:required="true"</code> only if your application relies entirely on a specific sensor. If your application uses a sensor for some functionality, but diff --git a/docs/html/guide/topics/testing/testing_android.jd b/docs/html/guide/topics/testing/testing_android.jd index c8a3f6e..adbc59d 100755 --- a/docs/html/guide/topics/testing/testing_android.jd +++ b/docs/html/guide/topics/testing/testing_android.jd @@ -318,7 +318,7 @@ parent.link=index.html A useful general test case class, especially if you are just starting out with Android testing, is {@link android.test.AndroidTestCase}. It extends both {@link junit.framework.TestCase} and {@link junit.framework.Assert}. It provides the - JUnit-standard <code>setUp()</code> and <code>tearDown()</code> methods, as well as well as + JUnit-standard <code>setUp()</code> and <code>tearDown()</code> methods, as well as all of JUnit's Assert methods. In addition, it provides methods for testing permissions, and a method that guards against memory leaks by clearing out certain class references. </p> @@ -401,7 +401,7 @@ parent.link=index.html Mock objects isolate tests from a running system by stubbing out or overriding normal operations. For example, a {@link android.test.mock.MockContentResolver} replaces the normal resolver framework with its own local framework, which is isolated - from the rest of the system. MockContentResolver also also stubs out the + from the rest of the system. MockContentResolver also stubs out the {@link android.content.ContentResolver#notifyChange(Uri, ContentObserver, boolean)} method so that observer objects outside the test environment are not accidentally triggered. </p> diff --git a/docs/html/guide/topics/ui/accessibility/apps.jd b/docs/html/guide/topics/ui/accessibility/apps.jd new file mode 100644 index 0000000..dc91638 --- /dev/null +++ b/docs/html/guide/topics/ui/accessibility/apps.jd @@ -0,0 +1,574 @@ +page.title=Making Applications Accessible +parent.title=Accessibility +parent.link=index.html +@jd:body + +<div id="qv-wrapper"> +<div id="qv"> + + <h2>In this document</h2> + <ol> + <li><a href="#label-ui">Labeling User Interface Elements</a></li> + <li><a href="#focus-nav">Enabling Focus Navigation</a> + <ol> + <li><a href="#focus-enable">Enabling view focus</a></li> + <li><a href="#focus-order">Controlling focus order</a></li> + </ol> + </li> + <li><a href="#custom-views">Building Accessible Custom Views</a> + <ol> + <li><a href="#directional-control">Handling directional controller clicks</a></li> + <li><a href="#accessibility-methods">Implementing accessibility API methods</a></li> + <li><a href="#send-events">Sending accessibility events</a></li> + <li><a href="#populate-events">Populating accessibility events</a></li> + </ol> + </li> + <li><a href="#test">Testing Accessibility</a> + <ol> + <li><a href="#test-audibles">Testing audible feedback</a></li> + <li><a href="#test-navigation">Testing focus navigation</a></li> + </ol> + </li> + </ol> + + <h2>Key classes</h2> + <ol> + <li>{@link android.view.accessibility.AccessibilityEvent}</li> + <li>{@link android.view.accessibility.AccessibilityNodeInfo}</li> + <li>{@link android.support.v4.view.accessibility.AccessibilityNodeInfoCompat}</li> + <li>{@link android.view.View.AccessibilityDelegate}</li> + <li>{@link android.support.v4.view.AccessibilityDelegateCompat}</li> + </ol> + + <h2>See also</h2> + <ol> + <li><a href="{@docRoot}training/accessibility/index.html">Implementing Accessibility</a></li> + <li><a href="{@docRoot}training/design-navigation/index.html">Designing Effective Navigation</a> + </li> + <li><a href="{@docRoot}design/index.html">Android Design</a></li> + </ol> + +</div> +</div> + +<p>Applications built for Android are accessible to users with visual, physical or age-related +disabilities when they activate accessibility features and services on a device. By default, +these services make your application more accessible. However, there are further steps you should +take to optimize the accessibility of your application and ensure a pleasant experience for all your +users.</p> + +<p>Making sure your application is accessible to all users is relatively easy, particularly when you +use framework-provided user interface components. If you only use these standard components for your +application, there are just a few steps required to ensure your application is accessible:</p> + +<ol> + <li>Label your {@link android.widget.ImageButton}, {@link android.widget.ImageView}, {@link +android.widget.EditText}, {@link android.widget.CheckBox} and other user interface controls using +the <a href="{@docRoot}reference/android/view/View.html#attr_android:contentDescription"> + {@code android:contentDescription}</a> attribute.</li> + <li>Make all of your user interface elements accessible with a directional controller, + such as a trackball or D-pad.</li> + <li>Test your application by turning on accessibility services like TalkBack and Explore by + Touch, and try using your application using only directional controls.</li> +</ol> + +<p>Developers who create custom controls that extend from the {@link android.view.View} class have +some additional responsibilities for making sure their components are accessible for users. This +document also discusses how to make custom view controls compatible with accessibility services.</p> + + +<h2 id="label-ui">Labeling User Interface Elements</h2> + +<p>Many user interface controls rely on visual cues to inform users of their meaning. For +example, a note-taking application might use an {@link android.widget.ImageButton} with a +picture of a plus sign to indicate that the user can add a new note. Or, an {@link +android.widget.EditText} component may have a label near it that indicates its purpose. When a user +with impaired vision accesses your application, these visual cues are often useless.</p> + +<p>To provide textual information about interface controls (as an alternative to the visual cues), +use the <a href="{@docRoot}reference/android/view/View.html#attr_android:contentDescription"> +{@code android:contentDescription}</a> attribute. The text you provide in this attribute is not +visible on the screen, but if a user has enabled accessibility services that provide audible +prompts, then the description in this attribute is read aloud to the user.</p> + +<p>Set the <a href="{@docRoot}reference/android/view/View.html#attr_android:contentDescription"> +{@code android:contentDescription}</a> attribute for every {@link android.widget.ImageButton}, +{@link android.widget.ImageView}, {@link android.widget.EditText}, {@link android.widget.CheckBox} +in your application's user interface, and on any other input controls that might require additional +information for users who are not able to see it.</p> + +<p>For example, the following {@link android.widget.ImageButton} sets the content description for +the plus button to the {@code add_note} string resource, which could be defined as “Add note" for an +English language interface:</p> + +<pre> +<ImageButton + android:id=”@+id/add_note_button” + android:src=”@drawable/add_note” + android:contentDescription=”@string/add_note”/> +</pre> + +<p>By including the description, speech-based accessibility services can announce "Add note" when a +user moves focus to this button or hovers over it.</p> + +<p class="note"><strong>Note:</strong> For {@link android.widget.EditText} fields, provide an +<a href="{@docRoot}reference/android/widget/TextView.html#attr_android:hint">android:hint</a> +attribute to help users understand what content is expected.</p> + +<h2 id="focus-nav">Enabling Focus Navigation</h2> + +<p>Focus navigation allows users with disabilities to step through user interface controls using a +directional controller. Directional controllers can be physical, such as a clickable trackball, +directional pad (D-pad) or arrow keys, tab key navigation with an attached keyboard or a software +application, such as the +<a href="https://play.google.com/store/apps/details?id=com.googlecode.eyesfree.inputmethod.latin"> +Eyes-Free Keyboard</a>, that provides an on-screen directional control.</p> + +<p>A directional controller is a primary means of navigation for many users. +Verify that all user interface (UI) controls in your application are accessible +without using the touchscreen and that clicking with the center button (or OK button) of a +directional controller has the same effect as touching the controls on the touchscreen. For +information on testing directional controls, see <a href="#test-navigation">Testing focus +navigation</a>.</p> + +<h3 id="focus-enable">Enabling view focus</h3> + +<p>A user interface element is accessible using directional controls when its +<a href="{@docRoot}reference/android/view/View.html#attr_android:focusable"> +{@code android:focusable}</a> attribute is set to {@code true}. This setting allows users to focus +on the element using the directional controls and then interact with it. The user interface controls +provided by the Android framework are focusable by default and visually indicate focus by changing +the control’s appearance.</p> + +<p>Android provides several APIs that let you control whether a user interface control is focusable +and even request that a control be given focus:</p> + +<ul> + <li>{@link android.view.View#setFocusable setFocusable()}</li> + <li>{@link android.view.View#isFocusable isFocusable()}</li> + <li>{@link android.view.View#requestFocus requestFocus()}</li> +</ul> + +<p>When working with a view that is not focusable by default, you can make it focusable from the XML +layout file by setting the +<a href="{@docRoot}reference/android/view/View.html#attr_android:focusable"> +{@code android:focusable}</a> attribute to {@code true} or by using the {@link +android.view.View#setFocusable setFocusable()} method.</p> + +<h3 id="focus-order">Controlling focus order</h3> + +<p>When users navigate in any direction using directional controls, focus is passed from one +user interface element (View) to another, as determined by the focus ordering. The ordering of the +focus movement is based on an algorithm that finds the nearest neighbor in a given direction. In +rare cases, the default algorithm may not match the order that you intended for your UI. In these +situations, you can provide explicit overrides to the ordering using the following XML attributes in +the layout file:</p> + +<dl> + <dt><a href="{@docRoot}reference/android/view/View.html#attr_android:nextFocusDown" +>{@code android:nextFocusDown}</a></dt> + <dd>Defines the next view to receive focus when the user navigates down.</dd> + <a><a href="{@docRoot}reference/android/view/View.html#attr_android:nextFocusLeft" +>{@code android:nextFocusLeft}</a></dt> + <dd>Defines the next view to receive focus when the user navigates left.</dd> + <dt><a href="{@docRoot}reference/android/view/View.html#attr_android:nextFocusRight" +>{@code android:nextFocusRight}</a></dt> + <dd>Defines the next view to receive focus when the user navigates right.</dd> + <dt><a href="{@docRoot}reference/android/view/View.html#attr_android:nextFocusUp" +>{@code android:nextFocusUp}</a></dt> + <dd>Defines the next view to receive focus when the user navigates up.</dd> +</dl> + +<p>The following example XML layout shows two focusable user interface elements where the <a +href="{@docRoot}reference/android/view/View.html#attr_android:nextFocusDown" +>{@code android:nextFocusDown}</a> and <a +href="{@docRoot}reference/android/view/View.html#attr_android:nextFocusUp" +>{@code android:nextFocusUp}</a> attributes have been explicitly set. The {@link android.widget.TextView} is +located to the right of the {@link android.widget.EditText}. However, since these properties have +been set, the {@link android.widget.TextView} element can now be reached by pressing the down arrow +when focus is on the {@link android.widget.EditText} element: </p> + +<pre> +<LinearLayout android:orientation="horizontal" + ... > + <EditText android:id="@+id/edit" + android:nextFocusDown=”@+id/text” + ... /> + <TextView android:id="@+id/text" + android:focusable=”true” + android:text="Hello, I am a focusable TextView" + android:nextFocusUp=”@id/edit” + ... /> +</LinearLayout> +</pre> + +<p>When modifying focus order, be sure that the navigation works as expected in all directions from +each user interface control and when navigating in reverse (to get back to where you came from).</p> + +<p class="note"><strong>Note:</strong> You can modify the focus order of user interface components +at runtime, using methods such as {@link android.view.View#setNextFocusDownId setNextFocusDownId()} +and {@link android.view.View#setNextFocusRightId setNextFocusRightId()}.</p> + + +<h2 id="custom-views">Building Accessible Custom Views</h2> + +<p>If your application requires a <a href="{@docRoot}guide/topics/ui/custom-components.html">custom +view component</a>, you must do some additional work to ensure that your custom view is accessible. +These are the main tasks for ensuring the accessibility of your view:</p> + +<ul> + <li>Handle directional controller clicks</li> + <li>Implement Accessibility API methods</li> + <li>Send {@link android.view.accessibility.AccessibilityEvent} objects specific to your custom view</li> + <li>Populate {@link android.view.accessibility.AccessibilityEvent} and {@link + android.view.accessibility.AccessibilityNodeInfo} for your view</li> +</ul> + + +<h3 id="directional-control">Handling directional controller clicks</h3> + +<p>On most devices, clicking a view using a directional controller sends a {@link +android.view.KeyEvent} with {@link android.view.KeyEvent#KEYCODE_DPAD_CENTER} to the view currently +in focus. All standard Android views already handle {@link +android.view.KeyEvent#KEYCODE_DPAD_CENTER} appropriately. When building a custom {@link +android.view.View} control, make sure this event has the same effect as touching the view on the +touchscreen. </p> + +<p>Your custom control should also treat the {@link android.view.KeyEvent#KEYCODE_ENTER} event the +same as {@link android.view.KeyEvent#KEYCODE_DPAD_CENTER}. This approach makes interaction from a +full keyboard much easier for users.</p> + + +<h3 id="accessibility-methods">Implementing accessibility API methods</h3> + +<p>Accessibility events are messages about users interaction with visual interface components in +your application. These messages are handled by <a href="services.html">Accessibility Services</a>, +which use the information in these events to produce supplemental feedback and prompts when users +have enabled accessibility services. As of Android 4.0 (API Level 14) and higher, the methods for +generating accessibility events have been expanded to provide more detailed information beyond the +{@link android.view.accessibility.AccessibilityEventSource} interface introduced in Android 1.6 (API +Level 4). The expanded accessibility methods are part of the {@link android.view.View} class as well +as the {@link android.view.View.AccessibilityDelegate} class. The methods are as follows:</p> + +<dl> + <dt>{@link android.view.View#sendAccessibilityEvent sendAccessibilityEvent()}</dt> + <dd>(API Level 4) This method is called when a user takes action on a view. The event is +classified with a user action type such as {@link +android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED TYPE_VIEW_CLICKED}. You typically do +not need to implement this method unless you are creating a custom view.</dd> + + <dt>{@link android.view.View#sendAccessibilityEventUnchecked +sendAccessibilityEventUnchecked()}</dt> + <dd>(API Level 4) This method is used when the calling code needs to directly control the check +for accessibility being enabled on the device ({@link +android.view.accessibility.AccessibilityManager#isEnabled AccessibilityManager.isEnabled()}). If +you do implement this method, you must assume that the calling method has already checked that +accessibility is enabled and the result is {@code true}. You typically do not need to implement this +method for a custom view.</dd> + + <dt>{@link android.view.View#dispatchPopulateAccessibilityEvent +dispatchPopulateAccessibilityEvent()} </dt> + <dd>(API Level 4) The system calls this method when your custom view generates an +accessibility event. As of API Level 14, the default implementation of this method calls {@link +android.view.View#onPopulateAccessibilityEvent onPopulateAccessibilityEvent()} for this view and +then the {@link android.view.View#dispatchPopulateAccessibilityEvent +dispatchPopulateAccessibilityEvent()} method for each child of this view. In order to support +accessibility services on revisions of Android <em>prior</em> to 4.0 (API Level 14) you +<em>must</em> override this method and populate {@link +android.view.accessibility.AccessibilityEvent#getText} with descriptive text for your custom +view.</dd> + + <dt>{@link android.view.View#onPopulateAccessibilityEvent onPopulateAccessibilityEvent()}</dt> + <dd>(API Level 14) This method sets the text output of an {@link +android.view.accessibility.AccessibilityEvent} for your view. This method is also called if the +view is a child of a view which generates an accessibility event. + + <p class="note"><strong>Note:</strong> Modifying additional attributes beyond the text within +this method potentially overwrites properties set by other methods. So, while you are able modify +attributes of the accessibility event with this method, you should limit these changes +to text content only and use the {@link android.view.View#onInitializeAccessibilityEvent +onInitializeAccessibilityEvent()} method to modify other properties of the event.</p> + + <p class="note"><strong>Note:</strong> If your implementation of this event calls for completely +overiding the output text without allowing other parts of your layout to modify its content, then +do not call the super implementation of this method in your code.</p> + </dd> + + <dt>{@link android.view.View#onInitializeAccessibilityEvent onInitializeAccessibilityEvent()}</dt> + <dd>(API Level 14) The system calls this method to obtain additional information about the +state of the view, beyond text content. If your custom view provides interactive control beyond a +simple {@link android.widget.TextView} or {@link android.widget.Button}, you should override this +method and set the additional information about your view into the event using this method, such as +password field type, checkbox type or states that provide user interaction or feedback. If you +do override this method, you must call its super implementation and then only modify properties +that have not been set by the super class.</dd> + + <dt>{@link android.view.View#onInitializeAccessibilityNodeInfo +onInitializeAccessibilityNodeInfo()}</dt> + <dd>(API Level 14) This method provides accessibility services with information about the state of +the view. The default {@link android.view.View} implementation sets a standard set of view +properties, but if your custom view provides interactive control beyond a simple {@link +android.widget.TextView} or {@link android.widget.Button}, you should override this method and set +the additional information about your view into the {@link +android.view.accessibility.AccessibilityNodeInfo} object handled by this method.</dd> + + <dt>{@link android.view.ViewGroup#onRequestSendAccessibilityEvent +onRequestSendAccessibilityEvent()}</dt> + <dd>(API Level 14) The system calls this method when a child of your view has generated an +{@link android.view.accessibility.AccessibilityEvent}. This step allows the the parent view to amend +the accessibility event with additional information. You should implement this method only if your +custom view can have child views and if the parent view can provide context information to the +accessibility event that would be useful to accessibility services.</dd> +</dl> + +<p>In order to support these accessibility methods for a custom view, you should take one of the +following approaches:</p> + +<ul> + <li>If your application targets Android 4.0 (API level 14) and higher, override and implement the +accessibility methods listed above directly in your custom view class.</li> + <li>If your custom view is intended to be compatible with Android 1.6 (API Level 4) and above, add +the Android <a href="{@docRoot}sdk/compatibility-library.html">Support Library</a>, revision 5 or +higher, to your project. Then, within your custom view class, call the +{@link android.support.v4.view.ViewCompat#setAccessibilityDelegate +ViewCompat.setAccessibilityDelegate()} method to implement the accessibility methods +above. For an example of this approach, see the Android Support Library (revision 5 or higher) +sample {@code AccessibilityDelegateSupportActivity} in +({@code <sdk>/extras/android/support/v4/samples/Support4Demos/}) + </li> +</ul> + +<p>In either case, you should implement the following accessibility methods for your custom view +class:</p> + +<ul> + <li>{@link android.view.View#dispatchPopulateAccessibilityEvent + dispatchPopulateAccessibilityEvent()}</li> + <li>{@link android.view.View#onPopulateAccessibilityEvent + onPopulateAccessibilityEvent()}</li> + <li>{@link android.view.View#onInitializeAccessibilityEvent + onInitializeAccessibilityEvent()}</li> + <li>{@link android.view.View#onInitializeAccessibilityNodeInfo + onInitializeAccessibilityNodeInfo()}</li> +</ul> + +<p>For more information about implementing these methods, see <a href="#populate-events">Populating +Accessibility Events</a>.</p> + + +<h3 id="send-events">Sending accessibility events</h3> + +<p>Depending on the specifics of your custom view, it may need to send {@link +android.view.accessibility.AccessibilityEvent} objects at a different times or for events not +handled by the default implementation. The {@link android.view.View} class provides a default +implementation for these event types:</p> + +<ul> + <li>Starting with API Level 4: + <ul> + <li>{@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED}</li> + + <li>{@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_LONG_CLICKED}</li> + + <li>{@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_FOCUSED}</li> + </ul> + </li> + <li>Starting with API Level 14: + <ul> + <li>{@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_SCROLLED}</li> + + <li>{@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}</li> + + <li>{@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_EXIT}</li> + </ul> + </li> +</ul> + +<p class="note"><strong>Note:</strong> Hover events are associated with the Explore by +Touch feature, which uses these events as triggers for providing audible prompts for user interface +elements.</p> + +<p>In general, you should send an {@link android.view.accessibility.AccessibilityEvent} whenever the +content of your custom view changes. For example, if you are implementing a custom slider bar that +allows a user to select a numeric value by pressing the left or right arrows, your custom view +should emit an event of type {@link +android.view.accessibility.AccessibilityEvent#TYPE_VIEW_TEXT_CHANGED} whenever the slider +value changes. The following sample code demonstrates the use of the {@link +android.view.accessibility.AccessibilityEventSource#sendAccessibilityEvent +sendAccessibilityEvent()} method to report this event.</p> + +<pre> +@Override +public boolean onKeyUp (int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) { + mCurrentValue--; + sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED); + return true; + } + ... +} +</pre> + + +<h3 id="populate-events">Populating accessibility events</h3> + +<p>Each {@link android.view.accessibility.AccessibilityEvent} has a set of required properties that +describe the current state of the view. These properties include things such as the view’s class +name, content description and checked state. The specific properties required for each event type +are described in the {@link android.view.accessibility.AccessibilityEvent} reference documentation. +The {@link android.view.View} implementation provides default values for these properties. Many of +these values, including the class name and event timestamp, are provided automatically. If you are +creating a custom view component, you must provide some information about the content and +characteristics of the view. This information may be as simple as a button label, but may also +include additional state information that you want to add to the event.</p> + +<p>The minimum requirement for providing information to accessibility services with a custom +view is to implement {@link android.view.View#dispatchPopulateAccessibilityEvent +dispatchPopulateAccessibilityEvent()}. This method is called by the system to request +information for an {@link android.view.accessibility.AccessibilityEvent} and makes your custom +view compatible with accessibility services on Android 1.6 (API Level 4) and higher. The +following example code demonstrates a basic implementation of this method.</p> + +<pre> +@Override +public void dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { + super.dispatchPopulateAccessibilityEvent(event); + // Call the super implementation to populate its text to the event, which + // calls onPopulateAccessibilityEvent() on API Level 14 and up. + + // In case this is running on a API revision earlier that 14, check + // the text content of the event and add an appropriate text + // description for this custom view: + CharSequence text = getText(); + if (!TextUtils.isEmpty(text)) { + event.getText().add(text); + } +} +</pre> + +<p>On Android 4.0 (API Level 14) and higher, the {@link +android.view.View#onPopulateAccessibilityEvent onPopulateAccessibilityEvent()} and +{@link android.view.View#onInitializeAccessibilityEvent onInitializeAccessibilityEvent()} +methods are the recommended way to populate or modify the information in an {@link +android.view.accessibility.AccessibilityEvent}. Use the +{@link android.view.View#onPopulateAccessibilityEvent onPopulateAccessibilityEvent()} method +specifically for adding or modifying the text content of the event, which is turned into audible +prompts by accessibility services such as TalkBack. Use the +{@link android.view.View#onInitializeAccessibilityEvent onInitializeAccessibilityEvent()} method for +populating additional information about the event, such as the selection state of the view.</p> + +<p>In addition, you should also implement the +{@link android.view.View#onInitializeAccessibilityNodeInfo onInitializeAccessibilityNodeInfo()} +method. {@link android.view.accessibility.AccessibilityNodeInfo} objects populated by this method +are used by accessibility services to investigate the view hierarchy that generated an accessibility +event after receiving that event, to obtain a more detailed context information and provide +appropriate feedback to users.</p> + +<p>The example code below shows how override these three methods by using +{@link android.support.v4.view.ViewCompat#setAccessibilityDelegate +ViewCompat.setAccessibilityDelegate()}. Note that this sample code requires that the Android +<a href="{@docRoot}sdk/compatibility-library.html">Support Library</a> for API Level 4 (revision 5 +or higher) is added to your project.</p> + +<pre> +ViewCompat.setAccessibilityDelegate(new AccessibilityDelegateCompat() { + @Override + public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { + super.onPopulateAccessibilityEvent(host, event); + // We call the super implementation to populate its text for the + // event. Then we add our text not present in a super class. + // Very often you only need to add the text for the custom view. + CharSequence text = getText(); + if (!TextUtils.isEmpty(text)) { + event.getText().add(text); + } + } + @Override + public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { + super.onInitializeAccessibilityEvent(host, event); + // We call the super implementation to let super classes + // set appropriate event properties. Then we add the new property + // (checked) which is not supported by a super class. + event.setChecked(isChecked()); + } + @Override + public void onInitializeAccessibilityNodeInfo(View host, + AccessibilityNodeInfoCompat info) { + super.onInitializeAccessibilityNodeInfo(host, info); + // We call the super implementation to let super classes set + // appropriate info properties. Then we add our properties + // (checkable and checked) which are not supported by a super class. + info.setCheckable(true); + info.setChecked(isChecked()); + // Quite often you only need to add the text for the custom view. + CharSequence text = getText(); + if (!TextUtils.isEmpty(text)) { + info.setText(text); + } + } +} +</pre> + +<p>On applications targeting Android 4.0 (API Level 14) and higher, these methods can be implemented +directly in your custom view class. For another example of this approach, see the Android +<a href="{@docRoot}sdk/compatibility-library.html">Support Library</a> (revision 5 or higher) sample +{@code AccessibilityDelegateSupportActivity} in +({@code <sdk>/extras/android/support/v4/samples/Support4Demos/}).</p> + +<p class="note"><strong>Note:</strong> You may find information on implementing accessibility for +custom views written prior to Android 4.0 that describes the use of the +{@link android.view.View#dispatchPopulateAccessibilityEvent dispatchPopulateAccessibilityEvent()} +method for populating AccessibilityEvents. As of the Android 4.0 release, however, the recommended +approach is to use the +{@link android.view.View#onPopulateAccessibilityEvent onPopulateAccessibilityEvent()} and +{@link android.view.View#onInitializeAccessibilityEvent onInitializeAccessibilityEvent()} +methods.</p> + + +<h2 id="test">Testing Accessibility</h2> + +<p>Testing the accessibility of your application is an important part of ensuring your users have a +great experience. You can test the most important parts of accessibility by testing your application +with audible feedback enabled and testing navigation within your application using directional +controls.</p> + +<h3 id="test-audibles">Testing audible feedback</h3> +<p>You can simulate the experience for many users by enabling an accessibility service that speaks +as you move around the screen. The Explore by Touch accessibility service, which is available on +devices with Android 4.0 and later. The <a +href="https://play.google.com/store/apps/details?id=com.google.android.marvin.talkback">TalkBack</a> +accessibility service, by the <a href="http://code.google.com/p/eyes-free/">Eyes-Free +Project</a> comes preinstalled on many Android devices.</p> + +<p>To enable TalkBack on revisions of Android prior to Android 4.0:</p> +<ol> + <li>Launch the Settings application.</li> + <li>Navigate to the <strong>Accessibility</strong> category and select it.</li> + <li>Select <strong>Accessibility</strong> to enable it.</li> + <li>Select <strong>TalkBack</strong> to enable it.</li> +</ol> + +<p class="note"><strong>Note:</strong> If the TalkBack accessibility service is not available, you +can install it for free from <a href="http://play.google.com">Google Play</a>.</p> + +<p>To enable Explore by Touch on Android 4.0 and later:</p> +<ol> + <li>Launch the Settings application.</li> + <li>Navigate to the <strong>Accessibility</strong> category and select it.</li> + <li>Select the <strong>TalkBack</strong> to enable it.</li> + <li>Return to the <strong>Accessibility</strong> category and select <strong>Explore by +Touch</strong> to enable it. + <p class="note"><strong>Note:</strong> You must turn on TalkBack <em>first</em>, otherwise this +option is not available.</p> + </li> +</ol> + +<h3 id="test-navigation">Testing focus navigation</h3> + +<p>As part of your accessibility testing, you can test navigation of your application using focus, +even if your test devices does not have a directional controller. The <a +href="{@docRoot}guide/developing/tools/emulator.html">Android Emulator</a> provides a +simulated directional controller that you can easily use to test navigation. You can also use a +software-based directional controller, such as the one provided by the +<a href="https://play.google.com/store/apps/details?id=com.googlecode.eyesfree.inputmethod.latin"> +Eyes-Free Keyboard</a> to simulate use of a D-pad.</p> diff --git a/docs/html/guide/topics/ui/accessibility/index.jd b/docs/html/guide/topics/ui/accessibility/index.jd new file mode 100644 index 0000000..414d5f3 --- /dev/null +++ b/docs/html/guide/topics/ui/accessibility/index.jd @@ -0,0 +1,55 @@ +page.title=Accessibility +parent.title=User Interface +parent.link=../index.html +@jd:body + +<div id="qv-wrapper"> +<div id="qv"> + + <h2>Topics</h2> + <ol> + <li><a href="{@docRoot}guide/topics/ui/accessibility/apps.html">Making Applications Accessible</a> + </li> + <li><a href="{@docRoot}guide/topics/ui/accessibility/services.html">Building Accessibility + Services</a></li> + </ol> + + <h2>Key classes</h2> + <ol> + <li>{@link android.view.accessibility.AccessibilityEvent}</li> + <li>{@link android.accessibilityservice.AccessibilityService}</li> + </ol> + + <h2>See also</h2> + <ol> + <li><a href="{@docRoot}training/accessibility/index.html">Implementing Accessibility</a></li> + </ol> + +</div> +</div> + +<p>Many Android users have disabilities that require them to interact with their Android devices in +different ways. These include users who have visual, physical or age-related disabilities that +prevent them from fully seeing or using a touchscreen.</p> + +<p>Android provides accessibility features and services for helping these users navigate their +devices more easily, including text-to-speech, haptic feedback, trackball and D-pad navigation that +augment their experience. Android application developers can take advantage of these services to +make their applications more accessible and also build their own accessibility services.</p> + +<p>The following topics show you how to use the Android framework to make applications more +accessible.</p> + +<dl> + <dt><strong><a href="{@docRoot}guide/topics/ui/accessibility/apps.html">Making Applications +Accessible</a></strong> + </dt> + <dd>Development practices and API features to ensure your application is accessible to users with +disabilities.</dd> + + <dt><strong><a href="{@docRoot}guide/topics/ui/accessibility/service.html">Building Accessibility +Services</a></strong> + </dt> + <dd>How to use API features to build services that make other applications more accessible for +users.</dd> +</dl>
\ No newline at end of file diff --git a/docs/html/guide/topics/ui/accessibility/services.jd b/docs/html/guide/topics/ui/accessibility/services.jd new file mode 100644 index 0000000..0dad4ec --- /dev/null +++ b/docs/html/guide/topics/ui/accessibility/services.jd @@ -0,0 +1,290 @@ +page.title=Building Accessibility Services +parent.title=Accessibility +parent.link=index.html +@jd:body + +<div id="qv-wrapper"> +<div id="qv"> + + <h2>Topics</h2> + <ol> + <li><a href="#manifest">Manifest Declarations and Permissions</a> + <ol> + <li><a href="service-declaration">Accessibility service declaration</a></li> + <li><a href="#service-config">Accessibility service configuration</a></li> + </ol> + </li> + <li><a href="#methods">AccessibilityService Methods</a></li> + <li><a href="#event-details">Getting Event Details</a></li> + <li><a href="#examples">Example Code</a></li> + </ol> + + <h2>Key classes</h2> + <ol> + <li>{@link android.accessibilityservice.AccessibilityService}</li> + <li>{@link android.accessibilityservice.AccessibilityServiceInfo}</li> + <li>{@link android.view.accessibility.AccessibilityEvent}</li> + <li>{@link android.view.accessibility.AccessibilityRecord}</li> + <li>{@link android.view.accessibility.AccessibilityNodeInfo}</li> + </ol> + + <h2>See also</h2> + <ol> + <li><a href="{@docRoot}training/accessibility/index.html">Implementing Accessibility</a></li> + </ol> + +</div> +</div> + +<p>An accessibility service is an application that provides user interface enhancements to +assist users with disabilities, or who may temporarily be unable to fully interact with a device. +For example, users who are driving, taking care of a young child or attending a very loud party +might need additional or alternative interface feedback.</p> + +<p>Android provides standard accessibility services, including TalkBack, and developers can +create and distribute their own services. This document explains the basics of building an +accessibility service.</p> + +<p>The ability for you to build and deploy accessibility services was introduced with Android +1.6 (API Level 4) and received significant improvements with Android 4.0 (API Level 14). The Android +Support Library was also updated with the release of Android 4.0 to provide support for these +enhanced accessibility features back to Android 1.6. Developers aiming for widely compatible +accessibility services are encouraged to use the +<a href="{@docRoot}sdk/compatibility-library.html">Support Library</a> and develop for the more +advanced accessibility features introduced in Android 4.0.</p> + + +<h2 id="manifest">Manifest Declarations and Permissions</h2> + +<p>Applications that provide accessibility services must include specific declarations in their + application manifests in order to be treated as an accessibility service by an Android system. + This section explains the required and optional settings for accessibility services.</p> + + +<h3 id="service-declaration">Accessibility service declaration</h3> + +<p>In order to be treated as an accessibility service, your application must include the +{@code service} element (rather than the {@code activity} element) within the {@code application} +element in its manifest. In addition, within the {@code service} element, you must also include an +accessibility service intent filter, as shown in the following sample:</p> + +<pre> +<application> + <service android:name=".MyAccessibilityService" + android:label="@string/accessibility_service_label"> + <intent-filter> + <action android:name="android.accessibilityservice.AccessibilityService" /> + </intent-filter> + </service> +</application> +</pre> + +<p>These declarations are required for all accessibility services deployed on Android 1.6 (API Level + 4) or higher.</p> + + +<h3 id="service-config">Accessibility service configuration</h3> + +<p>Accessibility services must also provide a configuration which specifies the types of +accessibility events that the service handles and additional information about the service. The +configuration of an accessibility service is contained in the {@link +android.accessibilityservice.AccessibilityServiceInfo} class. Your service can build and set a +configuration using an instance of this class and {@link +android.accessibilityservice.AccessibilityService#setServiceInfo setServiceInfo()} at runtime. +However, not all configuration options are available using this method.</p> + +<p>Beginning with Android 4.0, you can include a {@code <meta-data>} element in your manifest +with a reference to a configuration file, which allows you to set the full range of options for +your accessibility service, as shown in the following example:</p> + +<pre> +<service android:name=".MyAccessibilityService"> + ... + <meta-data + android:name="android.accessibilityservice" + android:resource="@xml/accessibility_service_config" /> +</service> +</pre> + +<p>This meta-data element refers to an XML file that you create in your application’s resource +directory ({@code <project_dir>/res/xml/accessibility_service_config.xml}). The following code +shows example contents for the service configuration file:</p> + +<pre> +<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android" + android:description="@string/accessibility_service_description" + android:packageNames="com.example.android.apis" + android:accessibilityEventTypes="typeAllMask" + android:accessibilityFlags="flagDefault" + android:accessibilityFeedbackType="feedbackSpoken" + android:notificationTimeout="100" + android:canRetrieveWindowContent="true" + android:settingsActivity="com.example.android.accessibility.ServiceSettingsActivity" +/> +</pre> + +<p>One of the most important functions of the accessibility service configuration parameters is to +allow you to specify what types of accessibility events your service can handle. Being able to +specify this information enables accessibility services to cooperate with each other, and allows you +as a developer the flexibility to handle only specific events types from specific applications. The +event filtering can include the following criteria:</p> + +<ul> + <li><strong>Package Names</strong> - Specify the package names of applications whose accessibility +events you want your service to handle. If this parameter is omitted, your accessibility service is +considered available to service accessibility events for any application. This parameter can be set +in the accessibility service configuration files with the {@code android:packageNames} attribute as +a comma-separated list, or set using the {@link +android.accessibilityservice.AccessibilityServiceInfo#packageNames +AccessibilityServiceInfo.packageNames} member.</li> + <li><strong>Event Types</strong> - Specify the types of accessibility events you want your service +to handle. This parameter can be set in the accessibility service configuration files with the +{@code android:accessibilityEventTypes} attribute as a comma-separated list, or set using the +{@link android.accessibilityservice.AccessibilityServiceInfo#eventTypes +AccessibilityServiceInfo.eventTypes} member. </li> +</ul> + +<p>For more information about the XML attributes which can be used in the accessibility service + configuration file, follow these links to the reference documentation:</p> + +<ul> + <li><a href="{@docRoot}reference/android/R.styleable.html#AccessibilityService_description">{@code android:description}</a></li> + <li><a href="{@docRoot}reference/android/R.styleable.html#AccessibilityService_packageNames">{@code android:packageNames}</a></li> + <li><a href="{@docRoot}reference/android/R.styleable.html#AccessibilityService_accessibilityEventTypes">{@code android:accessibilityEventTypes}</a></li> + <li><a href="{@docRoot}reference/android/R.styleable.html#AccessibilityService_accessibilityFlags">{@code android:accessibilityFlags}</a></li> + <li><a href="{@docRoot}reference/android/R.styleable.html#AccessibilityService_accessibilityFeedbackType">{@code android:accessibilityFeedbackType}</a></li> + <li><a href="{@docRoot}reference/android/R.styleable.html#AccessibilityService_notificationTimeout">{@code android:notificationTimeout}</a></li> + <li><a href="{@docRoot}reference/android/R.styleable.html#AccessibilityService_canRetrieveWindowContent">{@code android:canRetrieveWindowContent}</a></li> + <li><a href="{@docRoot}reference/android/R.styleable.html#AccessibilityService_settingsActivity">{@code android:settingsActivity}</a></li> +</ul> + +<p>For more information about which configuration settings can be dynamically set at runtime, see +the {@link android.accessibilityservice.AccessibilityServiceInfo} reference documentation.</p> + + +<h2 id="methods">AccessibilityService Methods</h2> + +<p>An application that provides accessibility service must extend the {@link +android.accessibilityservice.AccessibilityService} class and override the following methods from +that class. These methods are presented in the order in which they are called by the Android system, +from when the service is started +({@link android.accessibilityservice.AccessibilityService#onServiceConnected onServiceConnected()}), +while it is running ({@link android.accessibilityservice.AccessibilityService#onAccessibilityEvent +onAccessibilityEvent()}, +{@link android.accessibilityservice.AccessibilityService#onInterrupt onInterrupt()}) to when it is +shut down ({@link android.accessibilityservice.AccessibilityService#onUnbind onUnbind()}).</p> + +<ul> + <li>{@link android.accessibilityservice.AccessibilityService#onServiceConnected +onServiceConnected()} - (optional) This system calls this method when it successfully connects to +your accessibility service. Use this method to do any one-time setup steps for your service, +including connecting to user feedback system services, such as the audio manager or device vibrator. +If you want to set the configuration of your service at runtime or make one-time adjustments, this +is a convenient location from which to call {@link +android.accessibilityservice.AccessibilityService#setServiceInfo setServiceInfo()}.</li> + + <li>{@link android.accessibilityservice.AccessibilityService#onAccessibilityEvent +onAccessibilityEvent()} - (required) This method is called back by the system when it detects an +{@link android.view.accessibility.AccessibilityEvent} that matches the event filtering parameters +specified by your accessibility service. For example, when the user clicks a button or focuses on a +user interface control in an application for which your accessibility service is providing feedback. +When this happens, the system calls this method of your service with the associated {@link +android.view.accessibility.AccessibilityEvent}, which you can then interpret and provide feedback to +the user. This method may be called many times over the lifecycle of your service.</li> + + <li>{@link android.accessibilityservice.AccessibilityService#onInterrupt onInterrupt()} - +(required) This method is called when the system wants to interrupt the feedback your service is +providing, usually in response to a user taking action, such as moving focus to a different user +interface control than the one for which you are currently providing feedback. This method may be +called many times over the lifecycle of your service.</li> + + <li>{@link android.accessibilityservice.AccessibilityService#onUnbind onUnbind()} - (optional) +This method is called when the system is about to shutdown the accessibility service. Use this +method to do any one-time shutdown procedures, including de-allocating user feedback system +services, such as the audio manager or device vibrator.</li> +</ul> + +<p>These callback methods provide the basic structure for your accessibility service. It is up to +you to decide on how to process data provided by the Android system in the form of {@link +android.view.accessibility.AccessibilityEvent} objects and provide feedback to the user.</p> + + +<h2 id="event-details">Getting Event Details</h2> + +<p>The Android system provides information to accessibility services about the user interface +interaction through {@link android.view.accessibility.AccessibilityEvent} objects. Prior to Android +4.0, the information available in an accessibility event, while providing a significant amount of +detail about a user interface control selected by the user, typically provided limited contextual +information. In many cases, this missing context information might be critical to understanding the +meaning of the selected control.</p> + +<p>A typical example of an interface where context is of critical importance is a calendar or day +planner. If a user selects a 4:00 PM time slot in a Monday to Friday day list and the accessibility +service announces “4 PM”, but fails to indicate this is a Friday a Monday, the month or day, this is +hardly ideal feedback for the user. In this case, the context of a user interface control is of +critical importance to a user who wants to schedule a meeting.</p> + +<p>Android 4.0 significantly extends the amount of information that an accessibility service can +obtain about an user interface interaction by composing accessibility events based on the view +hierarchy. A view hierarchy is the set of user interface components that contain the component (its +parents) and the user interface elements that may be contained by that component (its children). In +this way, the Android system can provide much richer detail about accessibility events, allowing +accessibility services to provide more useful feedback to users.</p> + +<p>An accessibility service gets information about an user interface event through an {@link +android.view.accessibility.AccessibilityEvent} passed by the system to the service’s +{@link android.accessibilityservice.AccessibilityService#onAccessibilityEvent +onAccessibilityEvent()} callback method. This object provides details about the event, including the +type of object being acted upon, its descriptive text and other details. Starting in Android 4.0 +(and supported in previous releases through the {@link +android.support.v4.view.accessibility.AccessibilityEventCompat} object in the Support Library), you +can obtain additional information about the event using these calls:</p> + +<ul> + <li>{@link android.view.accessibility.AccessibilityEvent#getRecordCount +AccessibilityEvent.getRecordCount()} and {@link +android.view.accessibility.AccessibilityEvent#getRecord getRecord(int)} - These methods allow you to +retrieve the set of {@link android.view.accessibility.AccessibilityRecord} objects which contributed +to the {@link android.view.accessibility.AccessibilityEvent} passed to you by the system, which can +provide more context for your accessibility service.</li> + + <li>{@link android.view.accessibility.AccessibilityEvent#getSource +AccessibilityEvent.getSource()} - This method returns an {@link +android.view.accessibility.AccessibilityNodeInfo} object. This object allows you to request the +parents and children of the component that originated the accessibility event and investigate their +contents and state in order to provide + + <p class="caution"><strong>Important:</strong> The ability to investigate the full view +hierarchy from an {@link android.view.accessibility.AccessibilityEvent} potentially exposes private +user information to your accessibility service. For this reason, your service must request this +level of access through the accessibility <a href="#service-config">service configuration XML</a> +file, by including the {@code canRetrieveWindowContent} attribute and setting it to {@code true}. If +you do not include this setting in your service configuration xml file, calls to {@link +android.view.accessibility.AccessibilityEvent#getSource getSource()} fail.</p> + </li> +</ul> + + +<h2 id="examples">Example Code</h2> + +<p>The API Demo project contains two samples which can be used as a starting point for generating +accessibility services +({@code <sdk>/samples/<platform>/ApiDemos/src/com/example/android/apis/accessibility}): +</p> + +<ul> + <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/accessibility/ClockBackService.html">ClockBackService</a> + - This service is based on the original implementation of {@link +android.accessibilityservice.AccessibilityService} and can be used as a base for developing basic +accessibility services that are compatible with Android 1.6 (API Level 4) and higher.</li> + <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/accessibility/TaskBackService.html">TaskBackService</a> + - This service is based on the enhanced accessibility APIs introduced in Android 4.0 (API Level +14). However, you can use the Android <a href="{@docRoot}sdk/compatibility-library.html">Support +Libary</a> to substitute classes introduced in later API levels (e.g., +{@link android.view.accessibility.AccessibilityRecord}, +{@link android.view.accessibility.AccessibilityNodeInfo} +) with equivalent support package classes (e.g., +{@link android.support.v4.view.accessibility.AccessibilityRecordCompat}, +{@link android.support.v4.view.accessibility.AccessibilityNodeInfoCompat} +) to make this example work with API versions back to Android 1.6 (API Level 4).</li> +</ul> diff --git a/docs/html/guide/topics/ui/actionbar.jd b/docs/html/guide/topics/ui/actionbar.jd index 3c0ef26..bf7369a 100644 --- a/docs/html/guide/topics/ui/actionbar.jd +++ b/docs/html/guide/topics/ui/actionbar.jd @@ -73,8 +73,10 @@ href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/inde API Demos</a></li> </ol> - <h2>See also</h2>item + <h2>See also</h2> <ol> + <li><a +href="{@docRoot}design/patterns/actionbar.html">Android Design: Action Bar</a></li> <li><a href="{@docRoot}guide/topics/ui/menus.html">Menus</a></li> <li><a href="{@docRoot}guide/practices/tablets-and-handsets.html">Supporting Tablets and Handsets</a></li> @@ -111,9 +113,10 @@ accessible to the user in a predictable way. href="{@docRoot}guide/topics/ui/menus.html#OptionsMenu">options menu</a> directly in the action bar, as "action items." Action items can also provide an "action view," which provides an embedded widget for even more immediate action behaviors. Menu items that are not promoted -to an action item are available in the overflow menu, revealed by either the device MENU button +to an action item are available in the overflow menu, revealed by either the device <em>Menu</em> +button (when available) or by an "overflow menu" button in the action bar (when the device does not -include a MENU button).</p> +include a <em>Menu</em> button).</p> </li> </ul> @@ -123,6 +126,18 @@ href="{@docRoot}resources/samples/HoneycombGallery/index.html">Honeycomb Gallery landscape handset), showing the logo on the left, navigation tabs, and an action item on the right (plus the overflow menu button).</p> +<p class="note"><strong>Note:</strong> If you're looking for information about the contextual +action bar for displaying contextual action items, see the <a +href="{@docRoot}guide/topics/ui/menus.html#context-menu">Menu</a> guide.</p> + + +<div class="design-announce"> +<p><strong>Action Bar Design</strong></p> + <p>For design guidelines, read Android Design's <a +href="{@docRoot}design/patterns/actionbar.html">Action Bar</a> guide.</p> +</div> + + <div class="sidebox-wrapper"> <div class="sidebox"> @@ -215,9 +230,10 @@ later—calling {@link android.app.Activity#getActionBar()} will return null href="{@docRoot}guide/topics/ui/menus.html#OptionsMenu">options menu</a>. To do this, you can declare that the menu item should appear in the action bar as an "action item." An action item can include an icon and/or a text title. If a menu item does not appear as an action item, then the -system places it in the overflow menu. The overflow menu is revealed either by the device MENU +system places it in the overflow menu. The overflow menu is revealed either by the device +<em>Menu</em> button (if provided by the device) or an additional button in the action bar (if the device does not -provide the MENU button).</p> +provide the <em>Menu</em> button).</p> <div class="figure" style="width:359px"> <img src="{@docRoot}images/ui/actionbar-item-withtext.png" height="57" alt="" /> @@ -333,7 +349,7 @@ of the following:</p> <li><strong>Frequently used</strong>: It's an action that your users need seven out of ten visits or they use it several times in a row. <p>Example frequent actions: "New message" in the Messaging app and -"Search" in Android Market.</p> +"Search" on Google Play.</p> </li> <li><strong>Important</strong>: It's an action that you need users to easily discover or, if it's @@ -536,6 +552,12 @@ the email application, but presses the action bar icon to navigate up, rather th <p class="img-caption"><strong>Figure 6.</strong> Example behavior for UP navigation after entering the Email app from the People app.</p> +<div class="design-announce"> +<p><strong>Navigation Design</strong></p> + <p>For more about how <em>Up</em> and <em>Back</em> navigation differ, read Android Design's <a +href="{@docRoot}design/patterns/navigation.html">Navigation</a> guide.</p> +</div> + <p>To enable the icon for up navigation (which displays the "up" indicator next to the icon), call {@link android.app.ActionBar#setDisplayHomeAsUpEnabled setDisplayHomeAsUpEnabled(true)} on your {@link android.app.ActionBar}:</p> @@ -642,7 +664,7 @@ work as designed otherwise.</p> <p>Adding this value requires that you set your build target to Android 4.0 or higher in order to compile. Older versions of Android ignore the {@code "collapseActionView"} value because they don't understand it. Just be sure not to use other APIs in your source code that are not supported in the -version declared by your <a href="{@docRoot}guide/topics/manifest/uses-sdk-elementl.html#min">{@code +version declared by your <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min">{@code minSdkVersion}</a>, unless you add the appropriate version check at runtime.</p> </div> </div> @@ -843,8 +865,8 @@ you <em>do not</em> need to handle click events from the {@link android.app.Activity#onOptionsItemSelected onOptionsItemSelected()} callback method.</p> <p>For a sample using the share action provider, see -<a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/ActionBarActionProviderActivity.html" ->ActionBarActionProviderActivity</a>. +<a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/ActionBarShareActionProviderActivity.html" +>ActionBarShareActionProviderActivity</a>. @@ -1405,7 +1427,7 @@ href="#ActionView">action views</a>. (Added in API level 14.)</dd> </style> <!-- style for the action bar tab text --> - <style name="CustomTabTextStyle"> + <style name="CustomTabTextStyle" parent="@android:style/TextAppearance.Holo"> <item name="android:textColor">#2456c2</item> </style> </resources> @@ -1421,8 +1443,7 @@ action bar styles you want to change without re-implementing the styles you want manifest file like this:</p> <pre> -<application android:theme="@style/CustomActivityTheme" - ... /> +<application android:theme="@style/CustomActivityTheme" ... /> </pre> <p>For more information about using style and theme resources in your application, read <a @@ -1441,7 +1462,7 @@ android:backgroundStacked}. If you override these action bar styles, be sure tha parent action bar style such as {@link android.R.style#Widget_Holo_ActionBar Widget.Holo.ActionBar}.</p> -<p>For example, if you want to change the action bar's background, you could use the following +<p>For example, if you want to change the action bar's background, you can use the following styles:</p> <pre> @@ -1449,14 +1470,15 @@ styles:</p> <resources> <!-- the theme applied to the application or activity --> <style name="CustomActivityTheme" parent="@android:style/Theme.Holo"> -  <item name="android:actionBarTabTextStyle">@style/customTabTextStyle</item> + <item name="android:actionBarStyle">@style/MyActionBar</item> <!-- other activity and action bar styles here --> </style> - <!-- style for the action bar, simply to change the background --> - <style parent="@android:style/Widget.Holo.ActionBar"> + <!-- style for the action bar backgrounds --> + <style name="MyActionBar" parent="@android:style/Widget.Holo.ActionBar"> <item name="android:background">@drawable/ab_background</item> - <item name="android:backgroundSplit">@drawable/ab_background</item> + <item name="android:backgroundStacked">@drawable/ab_background</item> + <item name="android:backgroundSplit">@drawable/ab_split_background</item> </style> </resources> </pre> diff --git a/docs/html/guide/topics/ui/declaring-layout.jd b/docs/html/guide/topics/ui/declaring-layout.jd index 4dc915f..8af4a1c 100644 --- a/docs/html/guide/topics/ui/declaring-layout.jd +++ b/docs/html/guide/topics/ui/declaring-layout.jd @@ -194,7 +194,7 @@ contains property types that define the size and position for each child view, a appropriate for the view group. As you can see in figure 1, the parent view group defines layout parameters for each child view (including the child view group).</p> -<img src="{@docRoot}images/layoutparams.png" alt="" height="300" align="center"/> +<img src="{@docRoot}images/layoutparams.png" alt="" /> <p class="img-caption"><strong>Figure 1.</strong> Visualization of a view hierarchy with layout parameters associated with each view.</p> diff --git a/docs/html/guide/topics/ui/dialogs.jd b/docs/html/guide/topics/ui/dialogs.jd index 16f14cb..82cbfd1 100644 --- a/docs/html/guide/topics/ui/dialogs.jd +++ b/docs/html/guide/topics/ui/dialogs.jd @@ -37,6 +37,11 @@ DatePicker</a></li> <li><a href="{@docRoot}resources/tutorials/views/hello-timepicker.html">Hello TimePicker</a></li> </ol> + + <h2>See also</h2> + <ol> + <li><a href="{@docRoot}design/building-blocks/dialogs.html">Android Design: Dialogs</a></li> + </ol> </div> </div> @@ -70,6 +75,13 @@ of the following subclasses:</p> 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> +<div class="design-announce"> +<p><strong>Dialog Design</strong></p> + <p>For design guidelines, read Android Design's <a +href="{@docRoot}design/building-blocks/dialogs.html">Dialogs</a> guide.</p> +</div> + + <h2 id="ShowingADialog">Showing a Dialog</h2> diff --git a/docs/html/guide/topics/ui/index.jd b/docs/html/guide/topics/ui/index.jd index d3060c5..45c9ac9 100644 --- a/docs/html/guide/topics/ui/index.jd +++ b/docs/html/guide/topics/ui/index.jd @@ -51,7 +51,7 @@ as shown in the diagram below. This hierarchy tree can be as simple or complex a can build it up using Android's set of predefined widgets and layouts, or with custom Views that you create yourself.</p> -<img src="{@docRoot}images/viewgroup.png" alt="" width="312" height="211" align="center"/> +<img src="{@docRoot}images/viewgroup.png" alt="" /> <p> In order to attach the view hierarchy tree to the screen for rendering, your Activity must call the @@ -174,7 +174,8 @@ href="ui-events.html">Input Events</a> document.</p> <p>Application menus are another important part of an application's UI. Menus offers a reliable interface that reveals application functions and settings. The most common application menu is revealed by pressing -the MENU key on the device. However, you can also add Context Menus, which may be revealed when the user presses +the <em>Menu</em> button on the device. However, you can also add Context Menus, which may be +revealed when the user presses and holds down on an item.</p> <p>Menus are also structured using a View hierarchy, but you don't define this structure yourself. Instead, diff --git a/docs/html/guide/topics/ui/layout-objects.jd b/docs/html/guide/topics/ui/layout-objects.jd index 8b2792d..e251fe9 100644 --- a/docs/html/guide/topics/ui/layout-objects.jd +++ b/docs/html/guide/topics/ui/layout-objects.jd @@ -163,7 +163,7 @@ refer to the ID using the syntax of a relative resource <td> <pre> <?xml version="1.0" encoding="utf-8"?> -<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android +<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/blue" diff --git a/docs/html/guide/topics/ui/menus.jd b/docs/html/guide/topics/ui/menus.jd index 7b5b3dc..d51a378 100644 --- a/docs/html/guide/topics/ui/menus.jd +++ b/docs/html/guide/topics/ui/menus.jd @@ -6,77 +6,129 @@ parent.link=index.html <div id="qv-wrapper"> <div id="qv"> <h2>In this document</h2> - <ol> - <li><a href="#xml">Creating a Menu Resource</a></li> - <li><a href="#Inflating">Inflating a Menu Resource</a> - <li><a href="#options-menu">Creating an Options Menu</a> - <ol> - <li><a href="#ChangingTheMenu">Changing menu items at runtime</a></li> - </ol> - </li> - <li><a href="#context-menu">Creating a Context Menu</a></li> - <li><a href="#submenu">Creating a Submenu</a></li> - <li><a href="#features">Other Menu Features</a> - <ol> - <li><a href="#groups">Menu groups</a></li> - <li><a href="#checkable">Checkable menu items</a></li> - <li><a href="#shortcuts">Shortcut keys</a></li> - <li><a href="#intents">Dynamically adding menu intents</a></li> - </ol> - </li> - </ol> +<ol> + <li><a href="#xml">Defining a Menu in XML</a></li> + <li><a href="#options-menu">Creating an Options Menu</a> + <ol> + <li><a href="#RespondingOptionsMenu">Handling click events</a></li> + <li><a href="#ChangingTheMenu">Changing menu items at runtime</a></li> + </ol> + </li> + <li><a href="#context-menu">Creating Contextual Menus</a> + <ol> + <li><a href="#FloatingContextMenu">Creating a floating context menu</a></li> + <li><a href="#CAB">Using the contextual action mode</a></li> + </ol> + </li> + <li><a href="#PopupMenu">Creating a Popup Menu</a> + <ol> + <li><a href="#PopupEvents">Handling click events</a></li> + </ol> + </li> + <li><a href="#groups">Creating Menu Groups</a> + <ol> + <li><a href="#checkable">Using checkable menu items</a></li> + </ol> + </li> + <li><a href="#intents">Adding Menu Items Based on an Intent</a> + <ol> + <li><a href="#AllowingToAdd">Allowing your activity to be added to other menus</a></li> + </ol> + </li> +</ol> <h2>Key classes</h2> <ol> <li>{@link android.view.Menu}</li> <li>{@link android.view.MenuItem}</li> <li>{@link android.view.ContextMenu}</li> - <li>{@link android.view.SubMenu}</li> + <li>{@link android.view.ActionMode}</li> </ol> <h2>See also</h2> <ol> <li><a href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a></li> <li><a href="{@docRoot}guide/topics/resources/menu-resource.html">Menu Resource</a></li> + <li><a +href="http://android-developers.blogspot.com/2012/01/say-goodbye-to-menu-button.html">Say +Goodbye to the Menu Button</a></li> </ol> </div> </div> -<p>Menus are an important part of an activity's user interface, which provide users a familiar -way to perform actions. Android offers a simple framework for you to add standard -menus to your application.</p> +<p>Menus are a common user interface component in many types of applications. To provide a familiar +and consistent user experience, you should use the {@link android.view.Menu} APIs to present user +actions and other options in your activities.</p> + +<p>Beginning with Android 3.0 (API level 11), Android-powered devices are no longer required to +provide a dedicated <em>Menu</em> button. With this change, Android apps should migrate away from a +dependence on the traditional 6-item menu panel and instead provide an action bar to present common +user actions.</p> + +<p>Although the design and user experience for some menu items have changed, the semantics to define +a set of actions and options is still based on the {@link android.view.Menu} APIs. This +guide shows how to create the three fundamental types of menus or action presentations on all +versions of Android:</p> -<p>There are three types of application menus:</p> <dl> - <dt><strong>Options Menu</strong></dt> - <dd>The primary collection of menu items for an activity, which appears when the user touches -the MENU button. When your application is running on Android 3.0 or later, you can provide -quick access to select menu items by placing them directly in the <a -href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a>, as "action items."</dd> - <dt><strong>Context Menu</strong></dt> - <dd>A floating list of menu items that appears when the user touches and holds a view -that's registered to provide a context menu. + <dt><strong>Options menu and action bar</strong></dt> + <dd>The <a href="#options-menu">options menu</a> is the primary collection of menu items for an +activity. It's where you should place actions that have a global impact on the app, such as +"Search," "Compose email," and "Settings." + <p>If you're developing for Android 2.3 or lower, users can +reveal the options menu panel by pressing the <em>Menu</em> button.</p> + <p>On Android 3.0 and higher, items from the options menu are presented by the <a +href="{@docRoot}guide/topics/ui/actionbar.html">action bar</a> as a combination of on-screen action +items and overflow options. Beginning with Android 3.0, the <em>Menu</em> button is deprecated (some +devices +don't have one), so you should migrate toward using the action bar to provide access to actions and +other options.</p> + <p>See the section about <a href="#options-menu">Creating an Options Menu</a>.</p> + </dd> + + <dt><strong>Context menu and contextual action mode</strong></dt> + + <dd>A context menu is a <a href="#FloatingContextMenu">floating menu</a> that appears when the +user performs a long-click on an element. It provides actions that affect the selected content or +context frame. + <p>When developing for Android 3.0 and higher, you should instead use the <a +href="#CAB">contextual action mode</a> to enable actions on selected content. This mode displays +action items that affect the selected content in a bar at the top of the screen and allows the user +to select multiple items.</p> + <p>See the section about <a href="#context-menu">Creating Contextual Menus</a>.</p> +</dd> + + <dt><strong>Popup menu</strong></dt> + <dd>A popup menu displays a list of items in a vertical list that's anchored to the view that +invoked the menu. It's good for providing an overflow of actions that relate to specific content or +to provide options for a second part of a command. Actions in a popup menu should +<strong>not</strong> directly affect the corresponding content—that's what contextual actions +are for. Rather, the popup menu is for extended actions that relate to regions of content in your +activity. + <p>See the section about <a href="#PopupMenu">Creating a Popup Menu</a>.</p> </dd> - <dt><strong>Submenu</strong></dt> - <dd>A floating list of menu items that appears when the user touches a menu item that contains -a nested menu.</dd> </dl> -<p>This document shows you how to create each type of menu, using XML to define the content of -the menu and callback methods in your activity to respond when the user selects an item.</p> +<h2 id="xml">Defining a Menu in XML</h2> -<h2 id="xml">Creating a Menu Resource</h2> +<p>For all menu types, Android provides a standard XML format to define menu items. +Instead of building a menu in your activity's code, you should define a menu and all its items in an +XML <a href="{@docRoot}guide/topics/resources/menu-resource.html">menu resource</a>. You can then +inflate the menu resource (load it as a {@link android.view.Menu} object) in your activity or +fragment.</p> -<p>Instead of instantiating a {@link android.view.Menu} in your application code, you should -define a menu and all its items in an XML <a -href="{@docRoot}guide/topics/resources/menu-resource.html">menu resource</a>, then inflate the menu -resource (load it as a programmable object) in your application code. Using a menu resource to -define your menu is a good practice because it separates the content for the menu from your -application code. It's also easier to visualize the structure and content of a menu in XML.</p> +<p>Using a menu resource is a good practice for a few reasons:</p> +<ul> + <li>It's easier to visualize the menu structure in XML.</li> + <li>It separates the content for the menu from your application's behavioral code.</li> + <li>It allows you to create alternative menu configurations for different platform versions, +screen sizes, and other configurations by leveraging the <a +href="{@docRoot}guide/topics/resources/index.html">app resources</a> framework.</li> +</ul> -<p>To create a menu resource, create an XML file inside your project's <code>res/menu/</code> +<p>To define the menu, create an XML file inside your project's <code>res/menu/</code> directory and build the menu with the following elements:</p> <dl> <dt><code><menu></code></dt> @@ -90,8 +142,8 @@ element may contain a nested <code><menu></code> element in order to create a <dt><code><group></code></dt> <dd>An optional, invisible container for {@code <item>} elements. It allows you to -categorize menu items so they share properties such as active state and visibility. See the -section about <a href="#groups">Menu groups</a>.</dd> +categorize menu items so they share properties such as active state and visibility. For more +information, see the section about <a href="#groups">Creating Menu Groups</a>.</dd> </dl> @@ -101,14 +153,17 @@ section about <a href="#groups">Menu groups</a>.</dd> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/new_game" android:icon="@drawable/ic_new_game" - android:title="@string/new_game" /> + android:title="@string/new_game" + android:showAsAction="ifRoom"/> <item android:id="@+id/help" android:icon="@drawable/ic_help" android:title="@string/help" /> </menu> </pre> -<p>This example defines a menu with two items. Each item includes the attributes:</p> +<p>The <code><item></code> element supports several attributes you can use to define an item's +appearance and behavior. The items in the above menu include the following attributes:</p> + <dl> <dt>{@code android:id}</dt> <dd>A resource ID that's unique to the item, which allows the application can recognize the item @@ -117,158 +172,175 @@ when the user selects it.</dd> <dd>A reference to a drawable to use as the item's icon.</dd> <dt>{@code android:title}</dt> <dd>A reference to a string to use as the item's title.</dd> + <dt>{@code android:showAsAction}</dt> + <dd>Specifies when and how this item should appear as an action item in the <a +href="{@docRoot}guide/topics/ui/actionbar.html">action bar</a>.</dd> </dl> -<p>There are many more attributes you can include in an {@code <item>}, including some that - specify how the item may appear in the <a -href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a>. For more information about the XML -syntax and attributes for a menu resource, see the <a -href="{@docRoot}guide/topics/resources/menu-resource.html">Menu Resource</a> reference.</p> +<p>These are the most important attributes you should use, but there are many more available. +For information about all the supported attributes, see the <a +href="{@docRoot}guide/topics/resources/menu-resource.html">Menu Resource</a> document.</p> - - -<h2 id="Inflating">Inflating a Menu Resource</h2> - -<p>From your application code, you can inflate a menu resource (convert the XML resource into a -programmable object) using -{@link android.view.MenuInflater#inflate(int,Menu) MenuInflater.inflate()}. For -example, the following code inflates the <code>game_menu.xml</code> file defined above, during the -{@link android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} callback method, to -use the menu as the activity's Options Menu:</p> +<p>You can add a submenu to an item in any menu (except a submenu) by adding a {@code <menu>} +element as the child of an {@code <item>}. Submenus are useful when your application has a lot +of functions that can be organized into topics, like items in a PC application's menu bar (File, +Edit, View, etc.). For example:</p> <pre> -@Override -public boolean onCreateOptionsMenu(Menu menu) { - MenuInflater inflater = getMenuInflater(); - inflater.inflate(R.menu.game_menu, menu); - return true; -} +<?xml version="1.0" encoding="utf-8"?> +<menu xmlns:android="http://schemas.android.com/apk/res/android"> + <item android:id="@+id/file" + android:title="@string/file" > + <!-- "file" submenu --> + <menu> + <item android:id="@+id/create_new" + android:title="@string/create_new" /> + <item android:id="@+id/open" + android:title="@string/open" /> + </menu> + </item> +</menu> </pre> -<p>The {@link android.app.Activity#getMenuInflater()} method returns a {@link -android.view.MenuInflater} for the activity. With this object, you can call {@link -android.view.MenuInflater#inflate(int,Menu) inflate()}, which inflates a menu resource into a -{@link android.view.Menu} object. In this example, the menu resource defined by -<code>game_menu.xml</code> -is inflated into the {@link android.view.Menu} that was passed into {@link -android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()}. (This callback method for -the Options Menu is discussed more in the next section.)</p> +<p>To use the menu in your activity, you need to inflate the menu resource (convert the XML +resource into a programmable object) using {@link android.view.MenuInflater#inflate(int,Menu) +MenuInflater.inflate()}. In the following sections, you'll see how to inflate a menu for each +menu type.</p> <h2 id="options-menu">Creating an Options Menu</h2> -<div class="figure" style="width:200px"> +<div class="figure" style="width:200px;margin:0"> <img src="{@docRoot}images/options_menu.png" height="333" alt="" /> - <p class="img-caption"><strong>Figure 1.</strong> Screenshot of the Options Menu in the -Browser.</p> + <p class="img-caption"><strong>Figure 1.</strong> Options menu in the +Browser, on Android 2.3.</p> </div> -<p>The Options Menu is where you should include basic activity actions and necessary navigation -items (for example, a button to open the application settings). Items in the Options Menu are -accessible in two distinct ways: the MENU button or in the <a -href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a> (on devices running Android 3.0 -or higher).</p> - -<p>When running on a device with Android 2.3 and lower, the Options Menu appears at the bottom of -the screen, as shown in figure 1. When opened, the first visible portion of the Options Menu is -the icon menu. It holds the first six menu items. If you add more than six items to the -Options Menu, Android places the sixth item and those after it into the overflow menu, which the -user can open by touching the "More" menu item.</p> - -<p>On Android 3.0 and higher, items from the Options Menu is placed in the Action Bar, which appears -at the top of the activity in place of the traditional title bar. By default all items from the -Options Menu are placed in the overflow menu, which the user can open by touching the menu icon -on the right side of the Action Bar. However, you can place select menu items directly in the -Action Bar as "action items," for instant access, as shown in figure 2.</p> - -<p>When the Android system creates the Options Menu for the first time, it calls your -activity's {@link android.app.Activity#onCreateOptionsMenu(Menu) -onCreateOptionsMenu()} method. Override this method in your activity -and populate the {@link android.view.Menu} that is passed into the method, -{@link android.view.Menu} by inflating a menu resource as described above in <a -href="#Inflating">Inflating a Menu Resource</a>. For example:</p> +<p>The options menu is where you should include actions and other options that are relevant to the +current activity context, such as "Search," "Compose email," and "Settings."</p> + +<p>Where the items in your options menu appear on the screen depends on the version for which you've +developed your application:</p> + +<ul> + <li>If you've developed your application for <strong>Android 2.3.x (API level 10) or +lower</strong>, the contents of your options menu appear at the bottom of the screen when the user +presses the <em>Menu</em> button, as shown in figure 1. When opened, the first visible portion is +the icon +menu, which holds up to six menu items. If your menu includes more than six items, Android places +the sixth item and the rest into the overflow menu, which the user can open by selecting +<em>More</em>.</li> + + <li>If you've developed your application for <strong>Android 3.0 (API level 11) and +higher</strong>, items from the options menu are available in the <a +href="{@docRoot}guide/topics/ui/actionbar.html">action bar</a>. By default, the system +places all items in the action overflow, which the user can reveal with the action overflow icon on +the right side of the action bar (or by pressing the device <em>Menu</em> button, if available). To +enable +quick access to important actions, you can promote a few items to appear in the action bar by adding +{@code android:showAsAction="ifRoom"} to the corresponding {@code <item>} elements (see figure +2). <p>For more information about action items and other action bar behaviors, see the <a +href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a> guide. </p> +<p class="note"><strong>Note:</strong> Even if you're <em>not</em> developing for Android 3.0 or +higher, you can build your own action bar layout for a similar effect. For an example of how you can +support older versions of Android with an action bar, see the <a +href="{@docRoot}resources/samples/ActionBarCompat/index.html">Action Bar Compatibility</a> +sample.</p> +</li> +</ul> + +<img src="{@docRoot}images/ui/actionbar.png" alt="" /> +<p class="img-caption"><strong>Figure 2.</strong> Action bar from the <a +href="{@docRoot}resources/samples/HoneycombGallery/index.html">Honeycomb Gallery</a> app, showing +navigation tabs and a camera action item (plus the action overflow button).</p> + +<p>You can declare items for the options menu from either your {@link android.app.Activity} +subclass or a {@link android.app.Fragment} subclass. If both your activity and fragment(s) +declare items for the options menu, they are combined in the UI. The activity's items appear +first, followed by those of each fragment in the order in which each fragment is added to the +activity. If necessary, you can re-order the menu items with the {@code android:orderInCategory} +attribute in each {@code <item>} you need to move.</p> + +<p>To specify the options menu for an activity, override {@link +android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} (fragments provide their +own {@link android.app.Fragment#onCreateOptionsMenu onCreateOptionsMenu()} callback). In this +method, you can inflate your menu resource (<a href="#xml">defined in XML</a>) into the {@link +android.view.Menu} provided in the callback. For example:</p> <pre> @Override public boolean onCreateOptionsMenu(Menu menu) { - MenuInflater inflater = getMenuInflater(); + MenuInflater inflater = {@link android.app.Activity#getMenuInflater()}; inflater.inflate(R.menu.game_menu, menu); return true; } </pre> -<div class="figure" style="width:450px"> -<img src="{@docRoot}images/ui/actionbar.png" alt="" /> -<p class="img-caption"><strong>Figure 2.</strong> Action bar from the <a -href="{@docRoot}resources/samples/HoneycombGallery/index.html">Honeycomb Gallery</a> app, including -navigation tabs and a camera action item (plus the overflow menu button).</p> -</div> +<p>You can also add menu items using {@link android.view.Menu#add(int,int,int,int) +add()} and retrieve items with {@link android.view.Menu#findItem findItem()} to revise their +properties with {@link android.view.MenuItem} APIs.</p> -<p>You can also populate the menu in code, using {@link android.view.Menu#add(int,int,int,int) -add()} to add items to the {@link android.view.Menu}.</p> +<p>If you've developed your application for Android 2.3.x and lower, the system calls {@link +android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} to create the options menu +when the user opens the menu for the first time. If you've developed for Android 3.0 and higher, the +system calls {@link android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} when +starting the activity, in order to show items to the action bar.</p> -<p class="note"><strong>Note:</strong> On Android 2.3 and lower, the system calls {@link -android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} to create the Options Menu -when the user opens it for the first time, but on Android 3.0 and greater, the system creates it as -soon as the activity is created, in order to populate the Action Bar.</p> -<h3 id="RespondingOptionsMenu">Responding to user action</h3> +<h3 id="RespondingOptionsMenu">Handling click events</h3> -<p>When the user selects a menu item from the Options Menu (including action items in the -Action Bar), the system calls your activity's -{@link android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} -method. This method passes the -{@link android.view.MenuItem} that the user selected. You can identify the menu item by calling -{@link android.view.MenuItem#getItemId()}, which returns the unique ID for the menu -item (defined by the {@code android:id} attribute in the menu resource or with an integer -given to the {@link android.view.Menu#add(int,int,int,int) add()} method). You can match this ID -against known menu items and perform the appropriate action. For example:</p> +<p>When the user selects an item from the options menu (including action items in the action bar), +the system calls your activity's {@link android.app.Activity#onOptionsItemSelected(MenuItem) +onOptionsItemSelected()} method. This method passes the {@link android.view.MenuItem} selected. You +can identify the item by calling {@link android.view.MenuItem#getItemId()}, which returns the unique +ID for the menu item (defined by the {@code android:id} attribute in the menu resource or with an +integer given to the {@link android.view.Menu#add(int,int,int,int) add()} method). You can match +this ID against known menu items to perform the appropriate action. For example:</p> <pre> @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { - case R.id.new_game: - newGame(); - return true; - case R.id.help: - showHelp(); - return true; - default: - return super.onOptionsItemSelected(item); + case R.id.new_game: + newGame(); + return true; + case R.id.help: + showHelp(); + return true; + default: + return super.onOptionsItemSelected(item); } } </pre> -<p>In this example, {@link android.view.MenuItem#getItemId()} queries the ID for the selected menu -item and the switch statement compares the ID against the resource IDs that were assigned to menu -items in the XML resource. When a switch case successfully handles the menu item, it -returns {@code true} to indicate that the item selection was handled. Otherwise, the default -statement passes the menu item to the super class, in -case it can handle the item selected. (If you've directly extended the {@link android.app.Activity} -class, then the super class returns {@code false}, but it's a good practice to -pass unhandled menu items to the super class instead of directly returning {@code false}.)</p> - -<p>Additionally, Android 3.0 adds the ability for you to define the on-click behavior for a menu -item in the <a href="{@docRoot}guide/topics/resources/menu-resource.html">menu resource</a> XML, -using the {@code android:onClick} attribute. So you don't need to implement {@link -android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()}. Using the {@code -android:onClick} attribute, you can specify a method to call when the user selects the menu item. -Your activity must then implement the method specified in the {@code android:onClick} attribute so -that it accepts a single {@link android.view.MenuItem} parameter—when the system calls this -method, it passes the menu item selected.</p> +<p>When you successfully handle a menu item, return {@code true}. If you don't handle the menu +item, you should call the superclass implementation of {@link +android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} (the default +implementation returns false).</p> + +<p>If your activity includes fragments, the system first calls {@link +android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} for the activity then +for each fragment (in the order each fragment was added) until one returns +{@code true} or all fragments have been called.</p> + +<p class="note"><strong>Tip:</strong> Android 3.0 adds the ability for you to define the on-click +behavior for a menu item in XML, using the {@code android:onClick} attribute. The value for the +attribute must be the name of a method defined by the activity using the menu. The method +must be public and accept a single {@link android.view.MenuItem} parameter—when the system +calls this method, it passes the menu item selected. For more information and an example, see the <a +href="{@docRoot}guide/topics/resources/menu-resource.html">Menu Resource</a> document.</p> <p class="note"><strong>Tip:</strong> If your application contains multiple activities and -some of them provide the same Options Menu, consider creating +some of them provide the same options menu, consider creating an activity that implements nothing except the {@link android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} and {@link android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} methods. Then extend this class for each activity that should share the -same Options Menu. This way, you have to manage only one set of code for handling menu -actions and each descendant class inherits the menu behaviors.<br/><br/> -If you want to add menu items to one of your descendant activities, +same options menu. This way, you can manage one set of code for handling menu +actions and each descendant class inherits the menu behaviors. +If you want to add menu items to one of the descendant activities, override {@link android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} in that activity. Call {@code super.onCreateOptionsMenu(menu)} so the original menu items are created, then add new menu items with {@link @@ -278,180 +350,477 @@ behavior for individual menu items.</p> <h3 id="ChangingTheMenu">Changing menu items at runtime</h3> -<p>Once the activity is created, the {@link android.app.Activity#onCreateOptionsMenu(Menu) -onCreateOptionsMenu()} method is -called only once, as described above. The system keeps and re-uses the {@link -android.view.Menu} you define in this method until your activity is destroyed. If you want to change -the Options Menu any time after it's first created, you must override the -{@link android.app.Activity#onPrepareOptionsMenu(Menu) onPrepareOptionsMenu()} method. This passes -you the {@link android.view.Menu} object as it currently exists. This is useful if you'd like to -remove, add, disable, or enable menu items depending on the current state of your application.</p> - -<p>On Android 2.3 and lower, the system calls {@link android.app.Activity#onPrepareOptionsMenu(Menu) -onPrepareOptionsMenu()} each time the user opens the Options Menu.</p> +<p>After the system calls {@link android.app.Activity#onCreateOptionsMenu(Menu) +onCreateOptionsMenu()}, it retains an instance of the {@link android.view.Menu} you populate and +will not call {@link android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} +again unless the menu is invalidated for some reason. However, you should use {@link +android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} only to create the initial +menu state and not to make changes during the activity lifecycle.</p> + +<p>If you want to modify the options menu based on +events that occur during the activity lifecycle, you can do so in +the {@link android.app.Activity#onPrepareOptionsMenu(Menu) onPrepareOptionsMenu()} method. This +method passes you the {@link android.view.Menu} object as it currently exists so you can modify it, +such as add, remove, or disable items. (Fragments also provide an {@link +android.app.Fragment#onPrepareOptionsMenu onPrepareOptionsMenu()} callback.)</p> + +<p>On Android 2.3.x and lower, the system calls {@link +android.app.Activity#onPrepareOptionsMenu(Menu) +onPrepareOptionsMenu()} each time the user opens the options menu (presses the <em>Menu</em> +button).</p> -<p>On Android 3.0 and higher, you must call {@link android.app.Activity#invalidateOptionsMenu -invalidateOptionsMenu()} when you want to update the menu, because the menu is always open. The -system will then call {@link android.app.Activity#onPrepareOptionsMenu(Menu) onPrepareOptionsMenu()} -so you can update the menu items.</p> +<p>On Android 3.0 and higher, the options menu is considered to always be open when menu items are +presented in the action bar. When an event occurs and you want to perform a menu update, you must +call {@link android.app.Activity#invalidateOptionsMenu invalidateOptionsMenu()} to request that the +system call {@link android.app.Activity#onPrepareOptionsMenu(Menu) onPrepareOptionsMenu()}.</p> <p class="note"><strong>Note:</strong> -You should never change items in the Options Menu based on the {@link android.view.View} currently +You should never change items in the options menu based on the {@link android.view.View} currently in focus. When in touch mode (when the user is not using a trackball or d-pad), views cannot take focus, so you should never use focus as the basis for modifying -items in the Options Menu. If you want to provide menu items that are context-sensitive to a {@link +items in the options menu. If you want to provide menu items that are context-sensitive to a {@link android.view.View}, use a <a href="#context-menu">Context Menu</a>.</p> -<p>If you're developing for Android 3.0 or higher, be sure to also read the <a -href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a> developer guide.</p> +<h2 id="context-menu">Creating Contextual Menus</h2> -<h2 id="context-menu">Creating a Context Menu</h2> +<div class="figure" style="width:420px;margin-top:-1em"> + <img src="{@docRoot}images/ui/menu-context.png" alt="" /> + <p class="img-caption"><strong>Figure 3.</strong> Screenshots of a floating context menu (left) +and the contextual action bar (right).</p> +</div> -<p>A context menu is conceptually similar to the menu displayed when the user performs a -"right-click" on a PC. You should use a context menu to provide the user access to -actions that pertain to a specific item in the user interface. On Android, a context menu is -displayed when the user performs a "long press" (press and hold) on an item.</p> +<p>A contextual menu offers actions that affect a specific item or context frame in the UI. You +can provide a context menu for any view, but they are most often used for items in a {@link +android.widget.ListView}, {@link android.widget.GridView}, or other view collections in which +the user can perform direct actions on each item.</p> -<p>You can create a context menu for any View, though context menus are most often used for items in -a {@link android.widget.ListView}. When the user performs a long-press on an item in a ListView and -the list is registered to provide a context menu, the list item signals to the user that a context -menu is available by animating its background color—it transitions from -orange to white before opening the context menu. (The Contacts application demonstrates this -feature.)</p> +<p>There are two ways to provide contextual actions:</p> +<ul> + <li>In a <a href="#FloatingContextMenu">floating context menu</a>. A menu appears as a +floating list of menu items (similar to a dialog) when the user performs a long-click (press and +hold) on a view that declares support for a context menu. Users can perform a contextual +action on one item at a time.</li> + + <li>In the <a href="#CAB">contextual action mode</a>. This mode is a system implementation of +{@link android.view.ActionMode} that displays a <em>contextual action bar</em> at the top of the +screen with action items that affect the selected item(s). When this mode is active, users +can perform an action on multiple items at once (if your app allows it).</li> +</ul> -<div class="sidebox-wrapper"> -<div class="sidebox"> -<h3>Register a ListView</h3> -<p>If your activity uses a {@link android.widget.ListView} and -you want all list items to provide a context menu, register all items for a context -menu by passing the {@link android.widget.ListView} to {@link -android.app.Activity#registerForContextMenu(View) registerForContextMenu()}. For -example, if you're using a {@link android.app.ListActivity}, register all list items like this:</p> -<p><code>registerForContextMenu({@link android.app.ListActivity#getListView()});</code></p> -</div> -</div> +<p class="note"><strong>Note:</strong> The contextual action mode is available on Android 3.0 (API +level 11) and higher and is the preferred technique for displaying contextual actions when +available. If your app supports versions lower than 3.0 then you should fall back to a floating +context menu on those devices.</p> -<p>In order for a View to provide a context menu, you must "register" the view for a context -menu. Call {@link android.app.Activity#registerForContextMenu(View) registerForContextMenu()} and -pass it the {@link android.view.View} you want to give a context menu. When this View then -receives a long-press, it displays a context menu.</p> -<p>To define the context menu's appearance and behavior, override your activity's context menu -callback methods, {@link android.app.Activity#onCreateContextMenu(ContextMenu,View,ContextMenuInfo) -onCreateContextMenu()} and -{@link android.app.Activity#onContextItemSelected(MenuItem) onContextItemSelected()}.</p> +<h3 id="FloatingContextMenu">Creating a floating context menu</h3> -<p>For example, here's an {@link -android.app.Activity#onCreateContextMenu(ContextMenu,View,ContextMenuInfo) -onCreateContextMenu()} that uses the {@code context_menu.xml} menu resource:</p> +<p>To provide a floating context menu:</p> +<ol> + <li>Register the {@link android.view.View} to which the context menu should be associated by +calling {@link android.app.Activity#registerForContextMenu(View) registerForContextMenu()} and pass +it the {@link android.view.View}. + <p>If your activity uses a {@link android.widget.ListView} or {@link android.widget.GridView} and +you want each item to provide the same context menu, register all items for a context menu by +passing the {@link android.widget.ListView} or {@link android.widget.GridView} to {@link +android.app.Activity#registerForContextMenu(View) registerForContextMenu()}.</p> +</li> + + <li>Implement the {@link +android.view.View.OnCreateContextMenuListener#onCreateContextMenu onCreateContextMenu()} method +in your {@link android.app.Activity} or {@link android.app.Fragment}. + <p>When the registered view receives a long-click event, the system calls your {@link +android.view.View.OnCreateContextMenuListener#onCreateContextMenu onCreateContextMenu()} +method. This is where you define the menu items, usually by inflating a menu resource. For +example:</p> <pre> @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { - super.onCreateContextMenu(menu, v, menuInfo); - MenuInflater inflater = getMenuInflater(); - inflater.inflate(R.menu.context_menu, menu); + super.onCreateContextMenu(menu, v, menuInfo); + MenuInflater inflater = getMenuInflater(); + inflater.inflate(R.menu.context_menu, menu); } </pre> -<p>{@link android.view.MenuInflater} is used to inflate the context menu from a <a -href="{@docRoot}guide/topics/resources/menu-resource.html">menu resource</a>. (You can also use -{@link android.view.Menu#add(int,int,int,int) add()} to add menu items.) The callback method +<p>{@link android.view.MenuInflater} allows you to inflate the context menu from a <a +href="{@docRoot}guide/topics/resources/menu-resource.html">menu resource</a>. The callback method parameters include the {@link android.view.View} that the user selected and a {@link android.view.ContextMenu.ContextMenuInfo} object that provides -additional information about the item selected. You might use these parameters to determine -which context menu should be created, but in this example, all context menus for the activity are -the same.</p> +additional information about the item selected. If your activity has several views that each provide +a different context menu, you might use these parameters to determine which context menu to +inflate.</p> +</li> -<p>Then when the user selects an item from the context menu, the system calls {@link -android.app.Activity#onContextItemSelected(MenuItem) onContextItemSelected()}. Here is an example -of how you can handle selected items:</p> +<li>Implement {@link android.app.Activity#onContextItemSelected(MenuItem) +onContextItemSelected()}. + <p>When the user selects a menu item, the system calls this method so you can perform the +appropriate action. For example:</p> <pre> @Override public boolean onContextItemSelected(MenuItem item) { - AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); - switch (item.getItemId()) { - case R.id.edit: - editNote(info.id); - return true; - case R.id.delete: - deleteNote(info.id); - return true; - default: - return super.onContextItemSelected(item); - } + AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); + switch (item.getItemId()) { + case R.id.edit: + editNote(info.id); + return true; + case R.id.delete: + deleteNote(info.id); + return true; + default: + return super.onContextItemSelected(item); + } } </pre> -<p>The structure of this code is similar to the example for <a href="#options-menu">Creating an -Options Menu</a>, in which {@link android.view.MenuItem#getItemId()} queries the ID for the selected -menu item and a switch statement matches the item to the IDs that are defined in the menu resource. -And like the options menu example, the default statement calls the super class in case it -can handle menu items not handled here, if necessary.</p> +<p>The {@link android.view.MenuItem#getItemId()} method queries the ID for +the selected menu item, which you should assign to each menu item in XML using the {@code +android:id} attribute, as shown in the section about <a href="#xml">Defining a Menu in +XML</a>.</p> + +<p>When you successfully handle a menu item, return {@code true}. If you don't handle the menu item, +you should pass the menu item to the superclass implementation. If your activity includes fragments, +the activity receives this callback first. By calling the superclass when unhandled, the system +passes the event to the respective callback method in each fragment, one at a time (in the order +each fragment was added) until {@code true} or {@code false} is returned. (The default +implementation for {@link android.app.Activity} and {@code android.app.Fragment} return {@code +false}, so you should always call the superclass when unhandled.)</p> +</li> +</ol> + + +<h3 id="CAB">Using the contextual action mode</h3> -<p>In this example, the selected item is an item from a {@link android.widget.ListView}. To -perform an action on the selected item, the application needs to know the list -ID for the selected item (it's position in the ListView). To get the ID, the application calls -{@link android.view.MenuItem#getMenuInfo()}, which returns a {@link -android.widget.AdapterView.AdapterContextMenuInfo} object that includes the list ID for the -selected item in the {@link android.widget.AdapterView.AdapterContextMenuInfo#id id} field. The -local methods <code>editNote()</code> and <code>deleteNote()</code> methods accept this list ID to -perform an action on the data specified by the list ID.</p> +<p>The contextual action mode is a system implementation of {@link android.view.ActionMode} that +focuses user interaction toward performing contextual actions. When a +user enables this mode by selecting an item, a <em>contextual action bar</em> appears at the top of +the screen to present actions the user can perform on the currently selected item(s). While this +mode is enabled, the user can select multiple items (if you allow it), deselect items, and continue +to navigate within the activity (as much as you're willing to allow). The action mode is disabled +and the contextual action bar disappears when the user deselects all items, presses the BACK button, +or selects the <em>Done</em> action on the left side of the bar.</p> -<p class="note"><strong>Note:</strong> Items in a context menu do not support icons or shortcut -keys.</p> +<p class="note"><strong>Note:</strong> The contextual action bar is not necessarily +associated with the <a href="{@docRoot}guide/topics/ui/actionbar.html">action bar</a>. They operate +independently, even though the contextual action bar visually overtakes the action bar +position.</p> +<p>If you're developing for Android 3.0 (API level 11) or higher, you +should usually use the contextual action mode to present contextual actions, instead of the <a +href="#FloatingContextMenu">floating context menu</a>.</p> +<p>For views that provide contextual actions, you should usually invoke the contextual action mode +upon one of two events (or both):</p> +<ul> + <li>The user performs a long-click on the view.</li> + <li>The user selects a checkbox or similar UI component within the view.</li> +</ul> + +<p>How your application invokes the contextual action mode and defines the behavior for each +action depends on your design. There are basically two designs:</p> +<ul> + <li>For contextual actions on individual, arbitrary views.</li> + <li>For batch contextual actions on groups of items in a {@link +android.widget.ListView} or {@link android.widget.GridView} (allowing the user to select multiple +items and perform an action on them all).</li> +</ul> -<h2 id="submenu">Creating Submenus</h2> +<p>The following sections describe the setup required for each scenario.</p> -<p>A submenu is a menu that the user can open by selecting an item in another menu. You can add a -submenu to any menu (except a submenu). Submenus are useful when your application has a lot of -functions that can be organized into topics, like items in a PC application's menu bar (File, Edit, -View, etc.).</p> -<p>When creating your <a href="{@docRoot}guide/topics/resources/menu-resource.html">menu -resource</a>, you can create a submenu by adding a {@code <menu>} element as the child of an -{@code <item>}. For example:</p> +<h4 id="CABforViews">Enabling the contextual action mode for individual views</h4> +<p>If you want to invoke the contextual action mode only when the user selects specific +views, you should:</p> +<ol> + <li>Implement the {@link android.view.ActionMode.Callback} interface. In its callback methods, you +can specify the actions for the contextual action bar, respond to click events on action items, and +handle other lifecycle events for the action mode.</li> + <li>Call {@link android.app.Activity#startActionMode startActionMode()} when you want to show the +bar (such as when the user long-clicks the view).</li> +</ol> + +<p>For example:</p> + +<ol> + <li>Implement the {@link android.view.ActionMode.Callback ActionMode.Callback} interface: <pre> -<?xml version="1.0" encoding="utf-8"?> -<menu xmlns:android="http://schemas.android.com/apk/res/android"> - <item android:id="@+id/file" - android:icon="@drawable/file" - android:title="@string/file" > - <!-- "file" submenu --> - <menu> - <item android:id="@+id/create_new" - android:title="@string/create_new" /> - <item android:id="@+id/open" - android:title="@string/open" /> - </menu> - </item> -</menu> +private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() { + + // Called when the action mode is created; startActionMode() was called + @Override + public boolean onCreateActionMode(ActionMode mode, Menu menu) { + // Inflate a menu resource providing context menu items + MenuInflater inflater = mode.getMenuInflater(); + inflater.inflate(R.menu.context_menu, menu); + return true; + } + + // Called each time the action mode is shown. Always called after onCreateActionMode, but + // may be called multiple times if the mode is invalidated. + @Override + public boolean onPrepareActionMode(ActionMode mode, Menu menu) { + return false; // Return false if nothing is done + } + + // Called when the user selects a contextual menu item + @Override + public boolean onActionItemClicked(ActionMode mode, MenuItem item) { + switch (item.getItemId()) { + case R.id.menu_share: + shareCurrentItem(); + mode.finish(); // Action picked, so close the CAB + return true; + default: + return false; + } + } + + // Called when the user exits the action mode + @Override + public void onDestroyActionMode(ActionMode mode) { + mActionMode = null; + } +}; +</pre> + +<p>Notice that these event callbacks are almost exactly the same as the callbacks for the <a +href="#options-menu">options menu</a>, except each of these also pass the {@link +android.view.ActionMode} object associated with the event. You can use {@link +android.view.ActionMode} APIs to make various changes to the CAB, such as revise the title and +subtitle with {@link android.view.ActionMode#setTitle setTitle()} and {@link +android.view.ActionMode#setSubtitle setSubtitle()} (useful to indicate how many items are +selected).</p> + +<p>Also notice that the above sample sets the {@code mActionMode} variable null when the +action mode is destroyed. In the next step, you'll see how it's initialized and how saving +the member variable in your activity or fragment can be useful.</p> +</li> + + <li>Call {@link android.app.Activity#startActionMode startActionMode()} to enable the contextual +action mode when appropriate, such as in response to a long-click on a {@link +android.view.View}:</p> + +<pre> +someView.setOnLongClickListener(new View.OnLongClickListener() { + // Called when the user long-clicks on someView + public boolean onLongClick(View view) { + if (mActionMode != null) { + return false; + } + + // Start the CAB using the ActionMode.Callback defined above + mActionMode = getActivity().startActionMode(mActionModeCallback); + view.setSelected(true); + return true; + } +}); +</pre> + +<p>When you call {@link android.app.Activity#startActionMode startActionMode()}, the system returns +the {@link android.view.ActionMode} created. By saving this in a member variable, you can +make changes to the contextual action bar in response to other events. In the above sample, the +{@link android.view.ActionMode} is used to ensure that the {@link android.view.ActionMode} instance +is not recreated if it's already active, by checking whether the member is null before starting the +action mode.</p> +</li> +</ol> + + + +<h4 id="CABforListView">Enabling batch contextual actions in a ListView or GridView</h4> + +<p>If you have a collection of items in a {@link android.widget.ListView} or {@link +android.widget.GridView} (or another extension of {@link android.widget.AbsListView}) and want to +allow users to perform batch actions, you should:</p> + +<ul> + <li>Implement the {@link android.widget.AbsListView.MultiChoiceModeListener} interface and set it +for the view group with {@link android.widget.AbsListView#setMultiChoiceModeListener +setMultiChoiceModeListener()}. In the listener's callback methods, you can specify the actions +for the contextual action bar, respond to click events on action items, and handle other callbacks +inherited from the {@link android.view.ActionMode.Callback} interface.</li> + + <li>Call {@link android.widget.AbsListView#setChoiceMode setChoiceMode()} with the {@link +android.widget.AbsListView#CHOICE_MODE_MULTIPLE_MODAL} argument.</li> +</ul> + +<p>For example:</p> + +<pre> +ListView listView = getListView(); +listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); +listView.setMultiChoiceModeListener(new MultiChoiceModeListener() { + + @Override + public void onItemCheckedStateChanged(ActionMode mode, int position, + long id, boolean checked) { + // Here you can do something when items are selected/de-selected, + // such as update the title in the CAB + } + + @Override + public boolean onActionItemClicked(ActionMode mode, MenuItem item) { + // Respond to clicks on the actions in the CAB + switch (item.getItemId()) { + case R.id.menu_delete: + deleteSelectedItems(); + mode.finish(); // Action picked, so close the CAB + return true; + default: + return false; + } + } + + @Override + public boolean onCreateActionMode(ActionMode mode, Menu menu) { + // Inflate the menu for the CAB + MenuInflater inflater = mode.getMenuInflater(); + inflater.inflate(R.menu.context, menu); + return true; + } + + @Override + public void onDestroyActionMode(ActionMode mode) { + // Here you can make any necessary updates to the activity when + // the CAB is removed. By default, selected items are deselected/unchecked. + } + + @Override + public boolean onPrepareActionMode(ActionMode mode, Menu menu) { + // Here you can perform updates to the CAB due to + // an {@link android.view.ActionMode#invalidate} request + return false; + } +}); +</pre> + +<p>That's it. Now when the user selects an item with a long-click, the system calls the {@link +android.widget.AbsListView.MultiChoiceModeListener#onCreateActionMode onCreateActionMode()} +method and displays the contextual action bar with the specified actions. While the contextual +action bar is visible, users can select additional items.</p> + +<p>In some cases in which the contextual actions provide common action items, you might +want to add a checkbox or a similar UI element that allows users to select items, because they +might not discover the long-click behavior. When a user selects the checkbox, you +can invoke the contextual action mode by setting the respective list item to the checked +state with {@link android.widget.AbsListView#setItemChecked setItemChecked()}.</p> + + + + +<h2 id="PopupMenu">Creating a Popup Menu</h2> + +<div class="figure" style="width:220px"> +<img src="{@docRoot}images/ui/popupmenu.png" alt="" /> +<p><strong>Figure 4.</strong> A popup menu in the Gmail app, anchored to the overflow +button at the top-right.</p> +</div> + +<p>A {@link android.widget.PopupMenu} is a modal menu anchored to a {@link android.view.View}. +It appears below the anchor view if there is room, or above the view otherwise. It's useful for:</p> +<ul> + <li>Providing an overflow-style menu for actions that <em>relate to</em> specific content (such as +Gmail's email headers, shown in figure 4). + <p class="note"><strong>Note:</strong> This is not the same as a context menu, which is +generally for actions that <em>affect</em> selected content. For actions that affect selected +content, use the <a href="#CAB">contextual action mode</a> or <a +href="#FloatingContextMenu">floating context menu</a>.</p></li> + <li>Providing a second part of a command sentence (such as a button marked "Add" +that produces a popup menu with different "Add" options).</li> + <li>Providing a drop-down similar to {@link android.widget.Spinner} that does not retain +a persistent selection.</li> +</ul> + + +<p class="note"><strong>Note:</strong> {@link android.widget.PopupMenu} is available with API +level 11 and higher.</p> + +<p>If you <a href="#xml">define your menu in XML</a>, here's how you can show the popup menu:</p> +<ol> + <li>Instantate a {@link android.widget.PopupMenu} with its constructor, which takes the +current application {@link android.content.Context} and the {@link android.view.View} to which the +menu should be anchored.</li> + <li>Use {@link android.view.MenuInflater} to inflate your menu resource into the {@link +android.view.Menu} object returned by {@link +android.widget.PopupMenu#getMenu() PopupMenu.getMenu()}. On API level 14 and above, you can use +{@link android.widget.PopupMenu#inflate PopupMenu.inflate()} instead.</li> + <li>Call {@link android.widget.PopupMenu#show() PopupMenu.show()}.</li> +</ol> + +<p>For example, here's a button with the {@link android.R.attr#onClick android:onClick} attribute +that shows a popup menu:</p> + +<pre> +<ImageButton + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:src="@drawable/ic_overflow_holo_dark" + android:contentDescription="@string/descr_overflow_button" + android:onClick="showPopup" /> +</pre> + +<p>The activity can then show the popup menu like this:</p> + +<pre> +public void showPopup(View v) { + PopupMenu popup = new PopupMenu(this, v); + MenuInflater inflater = popup.getMenuInflater(); + inflater.inflate(R.menu.actions, popup.getMenu()); + popup.show(); +} </pre> -<p>When the user selects an item from a submenu, the parent menu's respective on-item-selected -callback method receives the event. For instance, if the above menu is applied as an Options Menu, -then the {@link android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} method -is called when a submenu item is selected.</p> +<p>In API level 14 and higher, you can combine the two lines that inflate the menu with {@link +android.widget.PopupMenu#inflate PopupMenu.inflate()}.</p> + +<p>The menu is dismissed when the user selects an item or touches outside the menu +area. You can listen for the dismiss event using {@link +android.widget.PopupMenu.OnDismissListener}.</p> + +<h3 id="PopupEvents">Handling click events</h3> -<p>You can also use {@link android.view.Menu#addSubMenu(int,int,int,int) addSubMenu()} to -dynamically add a {@link android.view.SubMenu} to an existing {@link android.view.Menu}. This -returns the new {@link android.view.SubMenu} object, to which you can add -submenu items, using {@link android.view.Menu#add(int,int,int,int) add()}</p> +<p>To perform an +action when the user selects a menu item, you must implement the {@link +android.widget.PopupMenu.OnMenuItemClickListener} interface and register it with your {@link +android.widget.PopupMenu} by calling {@link android.widget.PopupMenu#setOnMenuItemClickListener +setOnMenuItemclickListener()}. When the user selects an item, the system calls the {@link +android.widget.PopupMenu.OnMenuItemClickListener#onMenuItemClick onMenuItemClick()} callback in +your interface.</p> +<p>For example:</p> +<pre> +public void showMenu(View v) { + PopupMenu popup = new PopupMenu(this, v); -<h2 id="features">Other Menu Features</h2> + // This activity implements OnMenuItemClickListener + popup.setOnMenuItemClickListener(this); + popup.inflate(R.menu.actions); + popup.show(); +} + +@Override +public boolean onMenuItemClick(MenuItem item) { + switch (item.getItemId()) { + case R.id.archive: + archive(item); + return true; + case R.id.delete: + delete(item); + return true; + default: + return false; + } +} +</pre> -<p>Here are some other features that you can apply to most menu items.</p> -<h3 id="groups">Menu groups</h3> +<h2 id="groups">Creating Menu Groups</h2> <p>A menu group is a collection of menu items that share certain traits. With a group, you can:</p> @@ -473,38 +842,41 @@ android.view.Menu#add(int,int,int,int) add()} method.</p> <pre> <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> - <item android:id="@+id/item1" - android:icon="@drawable/item1" - android:title="@string/item1" /> + <item android:id="@+id/menu_save" + android:icon="@drawable/menu_save" + android:title="@string/menu_save" /> <!-- menu group --> - <group android:id="@+id/group1"> - <item android:id="@+id/groupItem1" - android:title="@string/groupItem1" /> - <item android:id="@+id/groupItem2" - android:title="@string/groupItem2" /> + <group android:id="@+id/group_delete"> + <item android:id="@+id/menu_archive" + android:title="@string/menu_archive" /> + <item android:id="@+id/menu_delete" + android:title="@string/menu_delete" /> </group> </menu> </pre> -<p>The items that are in the group appear the same as the first item that is not in a -group—all three items in the menu are siblings. However, you can modify the traits of the two -items in the group by referencing the group ID and using the methods listed above.</p> +<p>The items that are in the group appear at the same level as the first item—all three items +in the menu are siblings. However, you can modify the traits of the two +items in the group by referencing the group ID and using the methods listed above. The system +will also never separate grouped items. For example, if you declare {@code +android:showAsAction="ifRoom"} for each item, they will either both appear in the action +bar or both appear in the action overflow.</p> -<h3 id="checkable">Checkable menu items</h3> +<h3 id="checkable">Using checkable menu items</h3> <div class="figure" style="width:200px"> <img src="{@docRoot}images/radio_buttons.png" height="333" alt="" /> - <p class="img-caption"><strong>Figure 3.</strong> Screenshot of a submenu with checkable + <p class="img-caption"><strong>Figure 5.</strong> Screenshot of a submenu with checkable items.</p> </div> <p>A menu can be useful as an interface for turning options on and off, using a checkbox for stand-alone options, or radio buttons for groups of -mutually exclusive options. Figure 2 shows a submenu with items that are checkable with radio +mutually exclusive options. Figure 5 shows a submenu with items that are checkable with radio buttons.</p> -<p class="note"><strong>Note:</strong> Menu items in the Icon Menu (from the Options Menu) cannot +<p class="note"><strong>Note:</strong> Menu items in the Icon Menu (from the options menu) cannot display a checkbox or radio button. If you choose to make items in the Icon Menu checkable, you must manually indicate the checked state by swapping the icon and/or text each time the state changes.</p> @@ -550,15 +922,15 @@ user selected it) with {@link android.view.MenuItem#isChecked()} and then set th <pre> @Override public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case R.id.vibrate: - case R.id.dont_vibrate: - if (item.isChecked()) item.setChecked(false); - else item.setChecked(true); - return true; - default: - return super.onOptionsItemSelected(item); - } + switch (item.getItemId()) { + case R.id.vibrate: + case R.id.dont_vibrate: + if (item.isChecked()) item.setChecked(false); + else item.setChecked(true); + return true; + default: + return super.onOptionsItemSelected(item); + } } </pre> @@ -575,30 +947,8 @@ you should store the data using <a href="{@docRoot}guide/topics/data/data-storage.html#pref">Shared Preferences</a>.</p> -<h3 id="shortcuts">Shortcut keys</h3> - -<p>To facilitate quick access to items in the Options Menu when the user's device has a hardware -keyboard, you can add quick-access shortcut keys using letters and/or numbers, with the -{@code android:alphabeticShortcut} and {@code android:numericShortcut} attributes in the {@code -<item>} element. You can also use the methods {@link -android.view.MenuItem#setAlphabeticShortcut(char)} and {@link -android.view.MenuItem#setNumericShortcut(char)}. Shortcut keys are <em>not</em> -case sensitive.</p> - -<p>For example, if you apply the "s" character as an alphabetic shortcut to a "save" menu item, then -when the menu is open (or while the user holds the MENU button) and the user presses the "s" key, -the "save" menu item is selected.</p> - -<p>This shortcut key is displayed as a tip in the menu item, below the menu item name -(except for items in the Icon Menu, which are displayed only if the user holds the MENU -button).</p> - -<p class="note"><strong>Note:</strong> Shortcut keys for menu items only work on devices with a -hardware keyboard. Shortcuts cannot be added to items in a Context Menu.</p> - - -<h3 id="intents">Dynamically adding menu intents</h3> +<h2 id="intents">Adding Menu Items Based on an Intent</h2> <p>Sometimes you'll want a menu item to launch an activity using an {@link android.content.Intent} (whether it's an activity in your application or another application). When you know the intent you @@ -671,7 +1021,7 @@ addIntentOptions()}, it overrides any and all menu items by the menu group speci argument.</p> -<h4>Allowing your activity to be added to other menus</h4> +<h3 id="AllowingToAdd">Allowing your activity to be added to other menus</h3> <p>You can also offer the services of your activity to other applications, so your application can be included in the menu of others (reverse the roles described above).</p> @@ -681,7 +1031,7 @@ filter as usual, but be sure to include the {@link android.content.Intent#CATEGO and/or {@link android.content.Intent#CATEGORY_SELECTED_ALTERNATIVE} values for the intent filter category. For example:</p> <pre> -<intent-filter label="Resize Image"> +<intent-filter label="@string/resize_image"> ... <category android:name="android.intent.category.ALTERNATIVE" /> <category android:name="android.intent.category.SELECTED_ALTERNATIVE" /> diff --git a/docs/html/guide/topics/ui/notifiers/notifications.jd b/docs/html/guide/topics/ui/notifiers/notifications.jd index 7bc1cde..d104b4b 100644 --- a/docs/html/guide/topics/ui/notifiers/notifications.jd +++ b/docs/html/guide/topics/ui/notifiers/notifications.jd @@ -16,6 +16,7 @@ user clicks it</li> <h2>In this document</h2> <ol> <li><a href="#Basics">The Basics</a></li> + <li><a href="#HandlingNotifications">Responding to Notifications</a></li> <li><a href="#ManageYourNotifications">Managing your Notifications</a></li> <li><a href="#CreateANotification">Creating a Notification</a> <ol> @@ -33,6 +34,12 @@ user clicks it</li> <li>{@link android.app.Notification}</li> <li>{@link android.app.NotificationManager}</li> </ol> + + <h2>See also</h2> + <ol> + <li><a href="{@docRoot}design/patterns/notifications.html">Android +Design: Notifications</a></li> + </ol> </div> </div> @@ -61,6 +68,14 @@ when selected by the user.</p> <p class="img-caption"><strong>Figure 2.</strong> The notifications window.</p> +<div class="design-announce"> +<p><strong>Notification Design</strong></p> + <p>For design guidelines, read Android Design's <a +href="{@docRoot}design/patterns/notifications.html">Notifications</a> guide.</p> +</div> + + + <h2 id="Basics">The Basics</h2> <p>An {@link android.app.Activity} or {@link android.app.Service} can initiate a status bar @@ -123,6 +138,134 @@ mNotificationManager.notify(HELLO_ID, notification); </ol> +<h2 id="HandlingNotifications">Responding to Notifications</h2> + +<p>A central part of the user's experience with a notification revolves around +how it interacts with the application's UI flow. You must implement +this correctly to provide a consistent user experience within your app.</p> + +<p>Two typical examples of notifications are provided by Calendar, which can send out +notifications of upcoming events, and Email, which can send out notifications +when new messages arrive. These represent the two recommended patterns for handling +notifications: either launching into an activity that is separate from the +main application, or launching an entirely new instance of the application +showing the appropriate point for the notification.</p> + +<p>The following scenario shows how the activity stack should work +in these two typical notification flows, first handling a Calendar notification: +</p> + +<ol> + <li>User is creating a new event in Calendar. They realize they + need to copy part of an email message into this event. + </li> + <li> + The user chooses Home > Email. + </li> + <li> + While in Email, they receive a notification from Calendar for an upcoming + meeting. + </li> + <li> + So they choose that notification, which takes them to a + dedicated Calendar activity that displays brief details of the + upcoming meeting. + </li> + <li> + The user has seen enough to know they have a meeting coming up, + so they press the <em>Back</em> button. They are now returned to Email, which + is where they were when they took the notification. + </li> +</ol> + +<p>Handling an Email notification:</p> + +<ol> + <li> + The user is currently in Email composing a message, and needs to + check a date in their calendar. + </li> + <li> + The user chooses Home > Calendar. + </li> + <li> + While in Calendar, they receive a notification from Email about a new + message. + </li> + <li> + They select the notification, which brings them to Email with the message + details displayed. This has replaced what they were previously doing + (writing an e-mail), but that message is still saved in their drafts. + </li> + <li> + The user presses <em>Back</em> once to go to the message list (the typical flow in the + Email app), and press <em>Back</em> again to return to Calendar as they left it. + </li> +</ol> + +<p>In an Email style of notification, the UI launched by the notification +shows the main application in a state representing that notification. +For example, when the Email application comes to the foreground from its +notification, it displays either the conversion list or a specific +conversation depending on whether there are multiple or only one new +email. To achieve this, we want to completely replace whatever current +state the application is in with a new activity stack representing the +new notification state.</p> + +<p>The following code illustrates how to show this kind of notification. Of +most interest is the <code>makeMessageIntentStack()</code> method, which constructs +an array of intents representing the app's new activity stack for this state. +(If you are using fragments, you may need to initialize your fragment and +app state so that pressing <em>Back</em> will switch the UI back to its parent state.) +The core of this is the {@link android.content.Intent#makeRestartActivityTask +Intent.makeRestartActivityTask()} method, which constructs the root activity +of the stack with the appropriate flags, such as +{@link android.content.Intent#FLAG_ACTIVITY_CLEAR_TASK Intent.FLAG_ACTIVITY_CLEAR_TASK}.</p> + +{@sample development/samples/ApiDemos/src/com/example/android/apis/app/IncomingMessage.java + app_notification} + +<p>In a Calendar style of notification, the UI launched by the notification +is a dedicated activity that is not part of the normal application flow. +For example, when the user receives a Calendar notification, choosing that +notification starts a special activity that displays a list +of upcoming calendar events — this view is available only +from the notification, not through the Calendar's normal user +interface.</p> + +<p>The code for posting this type of notification is very straight-forward; it +is like the above, but the {@link android.app.PendingIntent} is for just a single +activity, our dedicated notification activity.</p> + +{@sample development/samples/ApiDemos/src/com/example/android/apis/app/IncomingMessage.java + interstitial_notification} + +<p>This is not enough, however. Normally Android considers all activities within +an application to be part of that application's UI flow, so simply launching the +activity like this can cause it to be mixed with your normal application back stack +in undesired ways. To make it behave correctly, in the manifest declaration +for the activity the attributes +<code>android:launchMode="singleTask"</code>, +<code>android:taskAffinity=""</code> and +<code>android:excludeFromRecents="true"</code> +must be set. The full activity declaration for this sample is:</p> + +{@sample development/samples/ApiDemos/AndroidManifest.xml interstitial_affinity} + +<p>You must be careful when launching other activities from this initial activity, +because this is not a top-level part of the application, does not appear in +recents, and needs to be relaunched at any point from the notification with new data +to show. This best approach is to make sure any activity launched from it is +launched in its own task. When doing this care must be taken to make sure this +new task interacts well with the current state of your exiting application's +task. This is essentially +the same as switching to the main application as described for the Email style +notification shown before. Given the <code>makeMessageIntentStack()</code> +method previously shown, handling a click then would look something like this:</p> + +{@sample development/samples/ApiDemos/src/com/example/android/apis/app/IncomingMessageInterstitial.java + app_launch} + <h2 id="ManageYourNotifications">Managing your Notifications</h2> <p>The {@link android.app.NotificationManager} is a system service that manages all diff --git a/docs/html/guide/topics/usb/accessory.jd b/docs/html/guide/topics/usb/accessory.jd index b0f4881..8b74bc0 100644 --- a/docs/html/guide/topics/usb/accessory.jd +++ b/docs/html/guide/topics/usb/accessory.jd @@ -169,8 +169,9 @@ UsbAccessory accessory = (UsbAccessory) intent.getParcelableExtra(UsbManager.EXT include a <code><uses-feature></code> element that declares that your application uses the <code>android.hardware.usb.accessory</code> feature.</li> - <li>If you are using the <a href="addon">add-on library</a>, add the - <code><uses-library></code> element specifying + <li>If you are using the + <a href="http://code.google.com/android/add-ons/google-apis/index.html">add-on library</a>, + add the <code><uses-library></code> element specifying <code>com.android.future.usb.accessory</code> for the library.</li> <li>Set the minimum SDK of the application to API Level 10 if you are using the add-on library diff --git a/docs/html/guide/topics/usb/adk.jd b/docs/html/guide/topics/usb/adk.jd index 6c7ab0d..c8949a3 100644 --- a/docs/html/guide/topics/usb/adk.jd +++ b/docs/html/guide/topics/usb/adk.jd @@ -97,6 +97,9 @@ page.title=Android Open Accessory Development Kit <li><a href="http://www.sparkfun.com/products/10748"> SparkFun</a></li> + <li><a href="http://troido.de/de/shoplsmallgbuy-android-stufflsmallg"> + Troido</a></li> + </ol> </div> </div> @@ -281,16 +284,17 @@ page.title=Android Open Accessory Development Kit <p>On Mac:</p> <ol type="a"> - <li>Right-click on the Arduino application in Finder and select <strong>Show Package - Contents</strong>.</li> + <li>Create, if it does not already exist, an <code>Arduino</code> + directory inside your user account's <code>Documents</code> directory, and within + that, a <code>libraries</code> directory.</li> <li>Copy the <code>firmware/arduino_libs/AndroidAccessory</code> and - <code>firmware/arduino_libs/USB_Host_Shield</code> directories (the complete directories, - not just the files within) to the <code>Contents/Resources/Java/libraries</code> directory - inside the Arduino application.</li> + <code>firmware/arduino_libs/USB_Host_Shield</code> directories (the + complete directories, not just the files within) to your + <code>Documents/Arduino/libraries/</code> directory.</li> - <li>Create a <code>CapSense</code> directory in the - <code>Contents/Resources/Java/libraries</code> directory.</li> + <li>Create a <code>CapSense</code> directory in your + <code>Documents/Arduino/libraries/</code> directory.</li> <li>Copy <code>CapSense.cpp</code> and <code>CapSense.h</code> from the unzipped CapSense download to the <code>CapSense</code> directory.</li> @@ -699,7 +703,7 @@ bool AndroidAccessory::switchDevice(byte addr) </pre>If this method returns false, the board waits until a new device is connected. If it is successful, the device displays itself on the USB bus as being in accessory mode when the ADK board re-enumerates the bus. When the device is in accessory mode, the accessory then <a href= -"establish-adk">establishes communication with the device</a>. +"#establish-adk">establishes communication with the device</a>. <h3 id="establish-adk">Establish communication with the device</h3> diff --git a/docs/html/guide/topics/wireless/bluetooth.jd b/docs/html/guide/topics/wireless/bluetooth.jd index 0af1d2c..0567799 100644 --- a/docs/html/guide/topics/wireless/bluetooth.jd +++ b/docs/html/guide/topics/wireless/bluetooth.jd @@ -29,6 +29,7 @@ other devices</li> <li><a href="#Profiles">Working with Profiles</a> <ol> <li><a href="#AT-Commands">Vendor-specific AT commands</a> + <li><a href="#HDP">Health Device Profile</a> </ol></li> </ol> @@ -43,6 +44,7 @@ other devices</li> <h2>Related samples</h2> <ol> <li><a href="{@docRoot}resources/samples/BluetoothChat/index.html">Bluetooth Chat</a></li> + <li><a href="{@docRoot}resources/samples/BluetoothHDP/index.html">Bluetooth HDP (Health Device Profile)</a></li> </ol> </div> @@ -132,11 +134,27 @@ Headset and Hands-Free (v1.5) profiles.</dd> audio can be streamed from one device to another over a Bluetooth connection. "A2DP" stands for Advanced Audio Distribution Profile.</dd> -<dt>{@link android.bluetooth.BluetoothProfile.ServiceListener}</dt> +<dt>{@link android.bluetooth.BluetoothHealth}</dt> +<dd> Represents a Health Device Profile proxy that controls the Bluetooth service.</dd> + +<dt>{@link android.bluetooth.BluetoothHealthCallback}</dt> + +<dd>An abstract class that you use to implement {@link +android.bluetooth.BluetoothHealth} callbacks. You must extend this class and +implement the callback methods to receive updates about changes in the +application’s registration state and Bluetooth channel state.</dd> + +<dt>{@link android.bluetooth.BluetoothHealthAppConfiguration}</dt> + +<dd>Represents an application configuration that the Bluetooth Health third-party +application registers to communicate with a remote Bluetooth health +device.</dd> + +<dt>{@link android.bluetooth.BluetoothProfile.ServiceListener}</dt> <dd>An interface that notifies {@link android.bluetooth.BluetoothProfile} IPC clients when they have been connected to or disconnected from the service (that -is, the internal service that runs a particular profile). </dd> +is, the internal service that runs a particular profile). </dd> </dl> @@ -231,12 +249,20 @@ if (!mBluetoothAdapter.isEnabled()) { <p>A dialog will appear requesting user permission to enable Bluetooth, as shown in Figure 1. If the user responds "Yes," the system will begin to enable Bluetooth and focus will return to your application once the process completes (or fails).</p> -<p>If enabling Bluetooth succeeds, your Activity will receive the {@link + +<p>The {@code REQUEST_ENABLE_BT} constant passed to {@link +android.app.Activity#startActivityForResult(Intent,int) startActivityForResult()} is a locally +defined integer (which must be greater than 0), that the system passes back to you in your +{@link +android.app.Activity#onActivityResult(int,int,Intent) onActivityResult()} implementation as the +<code>requestCode</code> parameter.</p> + +<p>If enabling Bluetooth succeeds, your activity receives the {@link android.app.Activity#RESULT_OK} result code in the {@link android.app.Activity#onActivityResult(int,int,Intent) onActivityResult()} callback. If Bluetooth was not enabled -due to an error (or the user responded "No") then the result code will be {@link -android.app.Activity#RESULT_CANCELED}.</p> +due to an error (or the user responded "No") then the result code is {@link +android.app.Activity#RESULT_CANCELED}.</p> </li> </ol> @@ -413,11 +439,11 @@ startActivity(discoverableIntent); <p>A dialog will be displayed, requesting user permission to make the device discoverable, as shown in Figure 2. If the user responds "Yes," then the device -will become discoverable for the specified amount of time. Your Activity will +will become discoverable for the specified amount of time. Your activity will then receive a call to the {@link android.app.Activity#onActivityResult(int,int,Intent) onActivityResult())} callback, with the result code equal to the duration that the device is discoverable. If the user responded "No" or if an error occurred, the result code will -be Activity.RESULT_CANCELLED.</p> +be {@link android.app.Activity#RESULT_CANCELED}.</p> <p class="note"><strong>Note:</strong> If Bluetooth has not been enabled on the device, then enabling device discoverability will automatically enable Bluetooth.</p> @@ -550,7 +576,7 @@ socket.</p> </ol> <p>The {@link android.bluetooth.BluetoothServerSocket#accept()} call should not -be executed in the main Activity UI thread because it is a blocking call and +be executed in the main activity UI thread because it is a blocking call and will prevent any other interaction with the application. It usually makes sense to do all work with a {@link android.bluetooth.BluetoothServerSocket} or {@link android.bluetooth.BluetoothSocket} in a new @@ -678,7 +704,7 @@ android.bluetooth.BluetoothSocket#connect()} method times out (after about 12 seconds), then it will throw an exception.</p> <p>Because {@link android.bluetooth.BluetoothSocket#connect()} is a blocking call, this connection -procedure should always be performed in a thread separate from the main Activity +procedure should always be performed in a thread separate from the main activity thread.</p> <p class="note">Note: You should always ensure that the device is not performing device discovery when you call {@link @@ -820,7 +846,7 @@ private class ConnectedThread extends Thread { try { // Read from the InputStream bytes = mmInStream.read(buffer); - // Send the obtained bytes to the UI Activity + // Send the obtained bytes to the UI activity mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer) .sendToTarget(); } catch (IOException e) { @@ -829,14 +855,14 @@ private class ConnectedThread extends Thread { } } - /* Call this from the main Activity to send data to the remote device */ + /* Call this from the main activity to send data to the remote device */ public void write(byte[] bytes) { try { mmOutStream.write(bytes); } catch (IOException e) { } } - /* Call this from the main Activity to shutdown the connection */ + /* Call this from the main activity to shutdown the connection */ public void cancel() { try { mmSocket.close(); @@ -848,12 +874,12 @@ private class ConnectedThread extends Thread { <p>The constructor acquires the necessary streams and once executed, the thread will wait for data to come through the InputStream. When {@link java.io.InputStream#read(byte[])} returns with -bytes from the stream, the data is sent to the main Activity using a member +bytes from the stream, the data is sent to the main activity using a member Handler from the parent class. Then it goes back and waits for more bytes from the stream.</p> <p>Sending outgoing data is as simple as calling the thread's -<code>write()</code> method from the main Activity and passing in the bytes to +<code>write()</code> method from the main activity and passing in the bytes to be sent. This method then simply calls {@link java.io.OutputStream#write(byte[])} to send the data to the remote device.</p> @@ -889,7 +915,7 @@ Bluetooth Headset Service via interprocess communication (<a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#IPC">IPC</a >). This includes both Bluetooth Headset and Hands-Free (v1.5) profiles. The {@link android.bluetooth.BluetoothHeadset} class includes support for AT commands. -For more discussion of this topic, see <a href="#AT-Commands">Vendor-specific AT commands</a></li> +For more discussion of this topic, see <a href="#AT-Commands">Vendor-specific AT commands</a></li> <li><strong>A2DP</strong>. The Advanced Audio Distribution Profile (A2DP) profile defines how high quality audio can be streamed from one device to @@ -897,13 +923,25 @@ another over a Bluetooth connection. Android provides the {@link android.bluetooth.BluetoothA2dp} class, which is a proxy for controlling the Bluetooth A2DP Service via IPC.</li> + <li><strong>Health Device</strong>. Android 4.0 (API level 14) introduces +support for the Bluetooth Health Device Profile (HDP). This lets you create +applications that use Bluetooth to communicate with health devices that support +Bluetooth, such as heart-rate monitors, blood meters, thermometers, scales, and +so on. For a list of supported devices and their corresponding device data +specialization codes, refer to <strong>Bluetooth Assigned Numbers</strong> at <a +href="http://www.bluetooth.org">www.bluetooth.org</a>. Note that these values +are also referenced in the ISO/IEEE 11073-20601 [7] specification as +MDC_DEV_SPEC_PROFILE_* in the Nomenclature Codes Annex. For more discussion of +HDP, see <a href="#HDP">Health Device Profile</a>.</li> + </ul> <p>Here are the basic steps for working with a profile:</p> <ol> - <li>Get the default adapter, as described in <a href="{@docRoot}guide/topics/wireless/bluetooth. -html#SettingUp">Setting Up Bluetooth</a>.</li> + <li>Get the default adapter, as described in + <a href="{@docRoot}guide/topics/wireless/bluetooth.html#SettingUp">Setting Up + Bluetooth</a>.</li> <li>Use {@link android.bluetooth.BluetoothAdapter#getProfileProxy(android.content.Context, @@ -925,7 +963,9 @@ to the profile proxy object.</li> state of the connection and perform other operations that are relevant to that profile.</li> </ol> -<p> For example, this code snippet shows how to connect to a {@link android.bluetooth.BluetoothHeadset} proxy object so that you can control the + +<p> For example, this code snippet shows how to connect to a {@link +android.bluetooth.BluetoothHeadset} proxy object so that you can control the Headset profile:</p> <pre>BluetoothHeadset mBluetoothHeadset; @@ -955,6 +995,8 @@ private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile mBluetoothAdapter.closeProfileProxy(mBluetoothHeadset); </pre> + + <h3 id="AT-Commands">Vendor-specific AT commands</h3> <p>Starting in Android 3.0, applications can register to receive system @@ -964,3 +1006,81 @@ broadcasts that indicate a connected device's battery level and could notify the user or take other action as needed. Create a broadcast receiver for the {@link android.bluetooth.BluetoothHeadset#ACTION_VENDOR_SPECIFIC_HEADSET_EVENT} intent to handle vendor-specific AT commands for the headset.</p> + +<h3 id="HDP">Health Device Profile</h3> + +<p>Android 4.0 (API level 14) introduces support for the Bluetooth Health Device +Profile (HDP). This lets you create applications that use Bluetooth to +communicate with health devices that support Bluetooth, such as heart-rate +monitors, blood meters, thermometers, and scales. The Bluetooth Health API +includes the classes {@link android.bluetooth.BluetoothHealth}, {@link +android.bluetooth.BluetoothHealthCallback}, and {@link +android.bluetooth.BluetoothHealthAppConfiguration}, which are described in <a +href="#TheBasics">The Basics</a>. </p> + +<p>In using the Bluetooth Health API, it's helpful to understand these key HDP concepts:</p> +<table> + <tr> + <th>Concept</th> + <th>Description</th> + </tr> + <tr> + <td><strong>Source</strong></td> + + <td>A role defined in HDP. A <em>source</em> is a health device that +transmits medical data (weight scale, glucose meter, thermometer, etc.) to a +smart device such as an Android phone or tablet. </td> + </tr> + <tr> + <td><strong>Sink</strong></td> + + <td>A role defined in HDP. In HDP, a <em>sink</em> is the smart device that +receives the medical data. In an Android HDP application, the sink is +represented by a {@link android.bluetooth.BluetoothHealthAppConfiguration} +object.</td> + </tr> + <tr> + <td><strong>Registration</strong></td> + <td>Refers to registering a sink for a particular health device.</td> + </tr> + <tr> + <td><strong>Connection</strong></td> + + <td>Refers to opening a channel between a health device and a smart device +such as an Android phone or tablet.</td> + </tr> +</table> + +<h4>Creating an HDP Application</h4> + +<p>Here are the basic steps involved in creating an Android HDP application:</p> +<ol> + + <li>Get a reference to the {@link android.bluetooth.BluetoothHealth} proxy +object. <p>Similar to regular headset and A2DP profile devices, you must call +{@link android.bluetooth.BluetoothAdapter#getProfileProxy getProfileProxy()} +with a {@link android.bluetooth.BluetoothProfile.ServiceListener} and the {@link +android.bluetooth.BluetoothProfile.ServiceListener#HEALTH} profile type to +establish a connection with the profile proxy object.</p> </li> + + <li>Create a {@link android.bluetooth.BluetoothHealthCallback} and register an +application configuration +({@link android.bluetooth.BluetoothHealthAppConfiguration}) +that acts as a health +sink.</li> + + <li>Establish a connection to a health device. Some devices will initiate the +connection. It is unnecessary to carry out this step for those devices.</li> + + <li>When connected successfully to a health device, read/write to the health +device using the file descriptor. <p>The received data needs to be interpreted +using a health manager which implements the IEEE 11073-xxxxx +specifications.</p></li> + + <li>When done, close the health channel and unregister the application. The +channel also closes when there is extended inactivity.</li> +</ol> + +<p>For a complete code sample that illustrates these steps, see <a +href="{@docRoot}resources/samples/BluetoothHDP/index.html">Bluetooth HDP (Health +Device Profile)</a>. </p> diff --git a/docs/html/guide/topics/wireless/wifip2p.jd b/docs/html/guide/topics/wireless/wifip2p.jd new file mode 100644 index 0000000..82c9abd --- /dev/null +++ b/docs/html/guide/topics/wireless/wifip2p.jd @@ -0,0 +1,611 @@ +page.title=Wi-Fi Direct + +@jd:body + + <div id="qv-wrapper"> + <div id="qv"> + <h2>In this document</h2> + + <ol> + <li><a href="#api">API Overview</a></li> + <li><a href="#creating-br">Creating a Broadcast Receiver for Wi-Fi Direct Intents</a></li> + + <li> + <a href="#creating-app">Creating a Wi-Fi Direct Application</a> + + <ol> + <li><a href="#setup">Initial setup</a></li> + + <li><a href="#discovering">Discovering peers</a></li> + + <li><a href="#connecting">Connecting to peers</a></li> + + <li><a href="#transferring">Transferring data</a></li> + </ol> + </li> + </ol> + <h2>Related Samples</h2> + <ol> + <li><a href="{@docRoot}resources/samples/WiFiDirectDemo/index.html">Wi-Fi Direct Demo</a></li> + </ol> + </div> + </div> + + <p>Wi-Fi Direct allows Android 4.0 (API level 14) or later devices with the appropriate hardware + to connect directly to each other via Wi-Fi without an intermediate access point. + Using these APIs, you can discover and connect to other devices when each device supports Wi-Fi Direct, + then communicate over a speedy connection across distances much longer than a Bluetooth connection. + This is useful for applications that share data among users, such as a multiplayer game or + a photo sharing application.</p> + + <p>The Wi-Fi Direct APIs consist of the following main parts:</p> + + <ul> + <li>Methods that allow you to discover, request, and connect to peers are defined + in the {@link android.net.wifi.p2p.WifiP2pManager} class.</li> + + <li>Listeners that allow you to be notified of the success or failure of {@link + android.net.wifi.p2p.WifiP2pManager} method calls. When calling {@link + android.net.wifi.p2p.WifiP2pManager} methods, each method can receive a specific listener + passed in as a parameter.</li> + + <li>Intents that notify you of specific events detected by the Wi-Fi Direct framework, + such as a dropped connection or a newly discovered peer.</li> + </ul> + + <p>You often use these three main components of the APIs together. For example, you can + provide a {@link android.net.wifi.p2p.WifiP2pManager.ActionListener} to a call to {@link + android.net.wifi.p2p.WifiP2pManager#discoverPeers discoverPeers()}, so that you can be + notified with the {@link android.net.wifi.p2p.WifiP2pManager.ActionListener#onSuccess + ActionListener.onSuccess()} and {@link android.net.wifi.p2p.WifiP2pManager.ActionListener#onFailure + ActionListener.onFailure()} + methods. A {@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_PEERS_CHANGED_ACTION} intent is + also broadcast if the {@link android.net.wifi.p2p.WifiP2pManager#discoverPeers discoverPeers()} + method discovers that the peers list has changed.</p> + + <h2 id="api">API Overview</h2> + +<p>The {@link android.net.wifi.p2p.WifiP2pManager} class provides methods to allow you to interact with + the Wi-Fi hardware on your device to do things like discover and connect to peers. The following actions + are available:</p> + +<p class="table-caption"><strong>Table 1.</strong>Wi-Fi Direct Methods</p> + + <table> + <tr> + <th>Method</th> + <th>Description</th> + </tr> + + <tr> + <td>{@link android.net.wifi.p2p.WifiP2pManager#initialize initialize()}</td> + <td>Registers the application with the Wi-Fi framework. This must be called before calling any other Wi-Fi Direct method.</td> + </tr> + + <tr> + <td>{@link android.net.wifi.p2p.WifiP2pManager#connect connect()}</td> + <td>Starts a peer-to-peer connection with a device with the specified configuration.</td> + </tr> + + <tr> + <td>{@link android.net.wifi.p2p.WifiP2pManager#cancelConnect cancelConnect()}</td> + <td>Cancels any ongoing peer-to-peer group negotiation.</td> + </tr> + + <tr> + <td>{@link android.net.wifi.p2p.WifiP2pManager#requestConnectionInfo requestConnectInfo()}</td> + <td>Requests a device's connection information.</td> + </tr> + + <tr> + <td>{@link android.net.wifi.p2p.WifiP2pManager#createGroup createGroup()}</td> + <td>Creates a peer-to-peer group with the current device as the group owner.</td> + </tr> + + <tr> + <td>{@link android.net.wifi.p2p.WifiP2pManager#removeGroup removeGroup()}</td> + <td>Removes the current peer-to-peer group.</td> + </tr> + + <tr> + <td>{@link android.net.wifi.p2p.WifiP2pManager#requestGroupInfo requestGroupInfo()}</td> + <td>Requests peer-to-peer group information.</td> + </tr> + + <tr> + <td>{@link android.net.wifi.p2p.WifiP2pManager.PeerListListener#discoverPeers discoverPeers()}</td> + <td>Initiates peer discovery </td> + </tr> + + <tr> + <td>{@link android.net.wifi.p2p.WifiP2pManager#requestPeers requestPeers()}</td> + <td>Requests the current list of discovered peers.</td> + </tr> + </table> + + + <p>{@link android.net.wifi.p2p.WifiP2pManager} methods let you pass in a listener, + so that the Wi-Fi Direct framework can notify your + activity of the status of a call. The available listener interfaces and the + corresponding {@link android.net.wifi.p2p.WifiP2pManager} method calls that use the listeners + are described in the following table:</p> + + <p class="table-caption"><strong>Table 2.</strong> Wi-Fi Direct Listeners</p> + + <table> + <tr> + <th>Listener interface</th> + <th>Associated actions</th> + </tr> + <tr> + <td>{@link android.net.wifi.p2p.WifiP2pManager.ActionListener}</td> + <td>{@link android.net.wifi.p2p.WifiP2pManager#connect connect()}, {@link + android.net.wifi.p2p.WifiP2pManager#cancelConnect cancelConnect()}, {@link + android.net.wifi.p2p.WifiP2pManager#createGroup createGroup()}, {@link + android.net.wifi.p2p.WifiP2pManager#removeGroup removeGroup()}, and {@link + android.net.wifi.p2p.WifiP2pManager.PeerListListener#discoverPeers discoverPeers()}</td> + </tr> + + <tr> + <td>{@link android.net.wifi.p2p.WifiP2pManager.ChannelListener}</td> + <td>{@link android.net.wifi.p2p.WifiP2pManager#initialize initialize()}</td> + </tr> + + <tr> + <td>{@link android.net.wifi.p2p.WifiP2pManager.ConnectionInfoListener}</td> + <td>{@link android.net.wifi.p2p.WifiP2pManager#requestConnectionInfo requestConnectInfo()}</td> + </tr> + + <tr> + <td>{@link android.net.wifi.p2p.WifiP2pManager.GroupInfoListener}</td> + <td>{@link android.net.wifi.p2p.WifiP2pManager#requestGroupInfo requestGroupInfo()}</td> + </tr> + + <tr> + <td>{@link android.net.wifi.p2p.WifiP2pManager.PeerListListener}</td> + <td>{@link android.net.wifi.p2p.WifiP2pManager#requestPeers requestPeers()}</td> + </tr> + </table> + +<p>The Wi-Fi Direct APIs define intents that are broadcast when certain Wi-Fi Direct events happen, + such as when a new peer is discovered or when a device's Wi-Fi state changes. You can register + to receive these intents in your application by <a href="#creating-br">creating a broadcast + receiver</a> that handles these intents:</p> + +<p class="table-caption"><strong>Table 3.</strong> Wi-Fi Direct Intents</p> + + <table> + <tr> + <th>Intent</th> + <th>Description</th> + </tr> + <tr> + <td>{@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_CONNECTION_CHANGED_ACTION}</td> + <td>Broadcast when the state of the device's Wi-Fi connection changes.</td> + </tr> + <tr> + <td>{@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_PEERS_CHANGED_ACTION}</td> + <td>Broadcast when you call {@link + android.net.wifi.p2p.WifiP2pManager.PeerListListener#discoverPeers discoverPeers()}. You + usually want to call {@link android.net.wifi.p2p.WifiP2pManager.PeerListListener#requestPeers + requestPeers()} to get an updated list of peers if you handle this intent in your + application.</td> + </tr> + <tr> + <td>{@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_STATE_CHANGED_ACTION}</td> + <td>Broadcast when Wi-Fi Direct is enabled or disabled on the device.</td> + </tr> + <tr> + <td>{@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_THIS_DEVICE_CHANGED_ACTION}</td> + <td>Broadcast when a device's details have changed, such as the device's name.</td> + </tr> + </table> + + + + <h2 id="creating-br">Creating a Broadcast Receiver for Wi-Fi Direct Intents</h2> + + <p>A broadcast receiver allows you to receive intents broadcast by the Android system, + so that your application can respond to events that you are interested in. The basic steps + for creating a broadcast receiver to handle Wi-Fi Direct intents are as follows:</p> + + <ol> + <li>Create a class that extends the {@link android.content.BroadcastReceiver} class. For the + class' constructor, you most likely want to have parameters for the {@link + android.net.wifi.p2p.WifiP2pManager}, {@link android.net.wifi.p2p.WifiP2pManager.Channel}, and + the activity that this broadcast receiver will be registered in. This allows the broadcast + receiver to send updates to the activity as well as have access to the Wi-Fi hardware and a + communication channel if needed.</li> + + <li>In the broadcast receiver, check for the intents that you are interested in + <code>{@link android.content.BroadcastReceiver#onReceive onReceive()}</code>. + Carry out any necessary actions depending on the intent that is + received. For example, if the broadcast receiver receives a {@link + android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_PEERS_CHANGED_ACTION} intent, you can call the + {@link android.net.wifi.p2p.WifiP2pManager#requestPeers requestPeers()} method to get a list of + the currently discovered peers.</li> + </ol> + + <p>The following code shows you how to create a typical broadcast receiver. The broadcast + receiver takes a {@link android.net.wifi.p2p.WifiP2pManager} object and an activity as + arguments and uses these two classes to appropriately carry out the needed actions when the + broadcast receiver receives an intent:</p> + +<pre> +/** + * A BroadcastReceiver that notifies of important Wi-Fi p2p events. + */ +public class WiFiDirectBroadcastReceiver extends BroadcastReceiver { + + private WifiP2pManager manager; + private Channel channel; + private MyWiFiActivity activity; + + public WiFiDirectBroadcastReceiver(WifiP2pManager manager, Channel channel, + MyWifiActivity activity) { + super(); + this.manager = manager; + this.channel = channel; + this.activity = activity; + } + + @Override + public void onReceive(Context context, Intent intent) { + String action = intent.getAction(); + + if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) { + // Check to see if Wi-Fi is enabled and notify appropriate activity + } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) { + // Call WifiP2pManager.requestPeers() to get a list of current peers + } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) { + // Respond to new connection or disconnections + } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) { + // Respond to this device's wifi state changing + } + } +} +</pre> + + <h2 id="creating-app">Creating a Wi-Fi Direct Application</h2> + + <p>Creating a Wi-Fi Direct application involves creating and registering a + broadcast receiver for your application, discovering peers, connecting to a peer, and + transferring data to a peer. The following sections describe how to do this.</p> + + <h3 id="setup">Initial setup</h3> + <p>Before using the Wi-Fi Direct APIs, you must ensure that your application can access + the hardware and that the device supports the Wi-Fi Direct protocol. If Wi-Fi Direct is supported, + you can obtain an instance of {@link android.net.wifi.p2p.WifiP2pManager}, create and register + your broadcast receiver, and begin using the Wi-Fi Direct APIs.</p> + <ol> + <li> + <p>Request permission to use the Wi-Fi hardware on the device and also declare + your application to have the correct minimum SDK version in the Android manifest:</p> + <pre> +<uses-sdk android:minSdkVersion="14" /> +<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> +<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> +<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /> +<uses-permission android:name="android.permission.INTERNET" /> +<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> +</pre> + </li> + + <li>Check to see if Wi-Fi Direct is on and supported. A good place to check this is in your + broadcast receiver when it receives the {@link + android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_STATE_CHANGED_ACTION} intent. Notify your + activity of the Wi-Fi Direct state and react accordingly: +<pre> +@Override +public void onReceive(Context context, Intent intent) { + ... + String action = intent.getAction(); + if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) { + int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1); + if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) { + // Wifi Direct is enabled + } else { + // Wi-Fi Direct is not enabled + } + } + ... +} +</pre> + </li> + + <li>In your activity's {@link android.app.Activity#onCreate onCreate()} method, obtain an instance of {@link + android.net.wifi.p2p.WifiP2pManager} and register your application with the Wi-Fi Direct + framework by calling {@link android.net.wifi.p2p.WifiP2pManager#initialize initialize()}. This + method returns a {@link android.net.wifi.p2p.WifiP2pManager.Channel}, which is used to connect + your application to the Wi-Fi Direct framework. You should also create an instance of your + broadcast receiver with the {@link + android.net.wifi.p2p.WifiP2pManager} and {@link android.net.wifi.p2p.WifiP2pManager.Channel} + objects along with a reference to your activity. This allows your broadcast receiver to notify + your activity of interesting events and update it accordingly. It also lets you manipulate the device's + Wi-Fi state if necessary: +<pre> +WifiP2pManager mManager; +Channel mChannel; +BroadcastReceiver mReceiver; +... +@Override +protected void onCreate(Bundle savedInstanceState){ + ... + mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE); + mChannel = mManager.initialize(this, getMainLooper(), null); + mReceiver = new WiFiDirectBroadcastReceiver(manager, channel, this); + ... +} +</pre> + </li> + + <li>Create an intent filter and add the same intents that your + broadcast receiver checks for: + <pre> +IntentFilter mIntentFilter; +... +@Override +protected void onCreate(Bundle savedInstanceState){ + ... + mIntentFilter = new IntentFilter(); + mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION); + mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION); + mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION); + mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION); + ... +} +</pre> + </li> + + <li>Register the broadcast receiver in the {@link android.app.Activity#onResume()} method + of your activity and unregister it in the {@link android.app.Activity#onPause()} method of your activity: + <pre> +/* register the broadcast receiver with the intent values to be matched */ +@Override +protected void onResume() { + super.onResume(); + registerReceiver(mReceiver, mIntentFilter); +} +/* unregister the broadcast receiver */ +@Override +protected void onPause() { + super.onPause(); + unregisterReceiver(mReceiver); +} +</pre> + + <p>When you have obtained a {@link android.net.wifi.p2p.WifiP2pManager.Channel} and + set up a broadcast receiver, your application can make Wi-Fi Direct method calls and receive + Wi-Fi Direct intents.</p> + </li> + + <p>You can now implement your application and use the Wi-Fi Direct features by calling the + methods in {@link android.net.wifi.p2p.WifiP2pManager}. The next sections describe how to do common actions + such as discovering and connecting to peers.</p> + </ol> + + <h3 id="discovering">Discovering peers</h3> + + <p>To discover peers that are available to connect to, call {@link + android.net.wifi.p2p.WifiP2pManager#discoverPeers discoverPeers()} to detect + available peers that are in range. The call to this function is asynchronous and a success or + failure is communicated to your application with {@link + android.net.wifi.p2p.WifiP2pManager.ActionListener#onSuccess onSuccess()} and {@link + android.net.wifi.p2p.WifiP2pManager.ActionListener#onFailure onFailure()} if you created a + {@link android.net.wifi.p2p.WifiP2pManager.ActionListener}. The + {@link android.net.wifi.p2p.WifiP2pManager.ActionListener#onSuccess onSuccess()} method only notifies you + that the discovery process succeeded and does not provide any information about the actual peers + that it discovered, if any:</p> + <pre> +manager.discoverPeers(channel, new WifiP2pManager.ActionListener() { + @Override + public void onSuccess() { + ... + } + + @Override + public void onFailure(int reasonCode) { + ... + } +}); + +</pre> + +<p>If the discovery process succeeds and detects peers, the system broadcasts the {@link + android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_PEERS_CHANGED_ACTION} intent, which you can listen + for in a broadcast receiver to obtain a list of peers. When your application receives the {@link + android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_PEERS_CHANGED_ACTION} intent, you can request a + list of the discovered peers with {@link + android.net.wifi.p2p.WifiP2pManager#requestPeers requestPeers()}. The following code shows how to set this up:</p> + <pre> +PeerListListener myPeerListListener; +... +if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) { + + // request available peers from the wifi p2p manager. This is an + // asynchronous call and the calling activity is notified with a + // callback on PeerListListener.onPeersAvailable() + if (manager != null) { + manager.requestPeers(channel, myPeerListListener); + } +} +</pre> + + <p>The {@link android.net.wifi.p2p.WifiP2pManager#requestPeers requestPeers()} method is also + asynchronous and can notify your activity when a list of peers is available with {@link + android.net.wifi.p2p.WifiP2pManager.PeerListListener#onPeersAvailable onPeersAvailable()}, which is defined in the + the {@link android.net.wifi.p2p.WifiP2pManager.PeerListListener} interface. The {@link + android.net.wifi.p2p.WifiP2pManager.PeerListListener#onPeersAvailable onPeersAvailable()} method + provides you with an {@link android.net.wifi.p2p.WifiP2pDeviceList}, which you can iterate + through to find the peer that you want to connect to.</p> + + <h3 id="connecting">Connecting to peers</h3> + + <p>When you have figured out the device that you want to connect to after obtaining a list of + possible peers, call the {@link android.net.wifi.p2p.WifiP2pManager#connect connect()} method to + connect to the device. This method call requires a {@link android.net.wifi.p2p.WifiP2pConfig} + object that contains the information of the device to connect to. + You can be notified of a connection success or failure through the {@link + android.net.wifi.p2p.WifiP2pManager.ActionListener}. The following code + shows you how to create a connection to a desired device:</p> + <pre> +//obtain a peer from the WifiP2pDeviceList +WifiP2pDevice device; +WifiP2pConfig config = new WifiP2pConfig(); +config.deviceAddress = device.deviceAddress; +manager.connect(channel, config, new ActionListener() { + + @Override + public void onSuccess() { + //success logic + } + + @Override + public void onFailure(int reason) { + //failure logic + } +}); + +</pre> + + + <h3 id="transferring">Transferring data</h3> + <p>Once a connection is established, you can transfer data between the devices with + sockets. The basic steps of transferring data are as follows:</p> + + <ol> + <li>Create a {@link java.net.ServerSocket}. This socket waits for a connection from a client on a specified + port and blocks until it happens, so do this in a background thread.</li> + + <li>Create a client {@link java.net.Socket}. The client uses the IP address and port of + the server socket to connect to the server device.</li> + + <li>Send data from the client to the server. When the client + socket successfully connects to the server socket, you can send data from the client to the server + with byte streams. </li> + + <li>The server socket waits for a client connection (with the {@link java.net.ServerSocket#accept()} method). This + call blocks until a client connects, so call this is another thread. When a connection happens, the server device can receive + the data from the client. Carry out any actions with this data, such as saving it to a file + or presenting it to the user.</li> + </ol> + + <p>The following example, modified from the <a href= + "{@docRoot}resources/samples/WiFiDirectDemo/index.html">Wi-Fi Direct Demo</a> sample, shows you how + to create this client-server socket communication and transfer JPEG images from a client + to a server with a service. For a complete working example, compile and run the <a href= + "{@docRoot}resources/samples/WiFiDirectDemo/index.html">Wi-Fi Direct Demo</a> sample.</p> +<pre> +public static class FileServerAsyncTask extends AsyncTask<Void, Void, String> { + + private Context context; + private TextView statusText; + + public FileServerAsyncTask(Context context, View statusText) { + this.context = context; + this.statusText = (TextView) statusText; + } + + @Override + protected String doInBackground(Void... params) { + try { + + /** + * Create a server socket and wait for client connections. This + * call blocks until a connection is accepted from a client + */ + ServerSocket serverSocket = new ServerSocket(8888); + Socket client = serverSocket.accept(); + + /** + * If this code is reached, a client has connected and transferred data + * Save the input stream from the client as a JPEG file + */ + final File f = new File(Environment.getExternalStorageDirectory() + "/" + + context.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis() + + ".jpg"); + + File dirs = new File(f.getParent()); + if (!dirs.exists()) + dirs.mkdirs(); + f.createNewFile(); + InputStream inputstream = client.getInputStream(); + copyFile(inputstream, new FileOutputStream(f)); + serverSocket.close(); + return f.getAbsolutePath(); + } catch (IOException e) { + Log.e(WiFiDirectActivity.TAG, e.getMessage()); + return null; + } + } + + /** + * Start activity that can handle the JPEG image + */ + @Override + protected void onPostExecute(String result) { + if (result != null) { + statusText.setText("File copied - " + result); + Intent intent = new Intent(); + intent.setAction(android.content.Intent.ACTION_VIEW); + intent.setDataAndType(Uri.parse("file://" + result), "image/*"); + context.startActivity(intent); + } + } +} +</pre> + + <p>On the client, connect to the server socket with a client socket and transfer data. This example + transfers a JPEG file on the client device's file system.</p> + +<pre> +Context context = this.getApplicationContext(); +String host; +int port; +int len; +Socket socket = new Socket(); +byte buf[] = new byte[1024]; +... +try { + /** + * Create a client socket with the host, + * port, and timeout information. + */ + socket.bind(null); + socket.connect((new InetSocketAddress(host, port)), 500); + + /** + * Create a byte stream from a JPEG file and pipe it to the output stream + * of the socket. This data will be retrieved by the server device. + */ + OutputStream outputStream = socket.getOutputStream(); + ContentResolver cr = context.getContentResolver(); + InputStream inputStream = null; + inputStream = cr.openInputStream(Uri.parse("path/to/picture.jpg")); + while ((len = inputStream.read(buf)) != -1) { + outputStream.write(buf, 0, len); + } + outputStream.close(); + inputStream.close(); +} catch (FileNotFoundException e) { + //catch logic +} catch (IOException e) { + //catch logic +} + +/** + * Clean up any open sockets when done + * transferring or if an exception occurred. + */ +finally { + if (socket != null) { + if (socket.isConnected()) { + try { + socket.close(); + } catch (IOException e) { + //catch logic + } + } + } +} +</pre> |